blob: 2dde767c828d976ab67a0ba2ae92f8a0a7f142bb [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"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000037#include "llvm/CodeGen/MachineLoopRanges.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000038#include "llvm/CodeGen/MachineRegisterInfo.h"
39#include "llvm/CodeGen/Passes.h"
40#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000042#include "llvm/Support/Debug.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000045#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000046
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000047#include <queue>
48
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000049using namespace llvm;
50
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000051STATISTIC(NumGlobalSplits, "Number of split global live ranges");
52STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000053STATISTIC(NumEvicted, "Number of interferences evicted");
54
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000055static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
56 createGreedyRegisterAllocator);
57
58namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000059class RAGreedy : public MachineFunctionPass,
60 public RegAllocBase,
61 private LiveRangeEdit::Delegate {
62
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000063 // context
64 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000065
66 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000067 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000068 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000069 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000070 MachineLoopInfo *Loops;
71 MachineLoopRanges *LoopRanges;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000072 EdgeBundles *Bundles;
73 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000074 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000075
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000076 // state
77 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000078 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000079 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000080
81 // Live ranges pass through a number of stages as we try to allocate them.
82 // Some of the stages may also create new live ranges:
83 //
84 // - Region splitting.
85 // - Per-block splitting.
86 // - Local splitting.
87 // - Spilling.
88 //
89 // Ranges produced by one of the stages skip the previous stages when they are
90 // dequeued. This improves performance because we can skip interference checks
91 // that are unlikely to give any results. It also guarantees that the live
92 // range splitting algorithm terminates, something that is otherwise hard to
93 // ensure.
94 enum LiveRangeStage {
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +000095 RS_New, ///< Never seen before.
96 RS_First, ///< First time in the queue.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +000097 RS_Second, ///< Second time in the queue.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +000098 RS_Global, ///< Produced by global splitting.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000099 RS_Local, ///< Produced by local splitting.
100 RS_Spill ///< Produced by spilling.
101 };
102
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000103 static const char *const StageName[];
104
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000105 // RegInfo - Keep additional information about each live range.
106 struct RegInfo {
107 LiveRangeStage Stage;
108
109 // Cascade - Eviction loop prevention. See canEvictInterference().
110 unsigned Cascade;
111
112 RegInfo() : Stage(RS_New), Cascade(0) {}
113 };
114
115 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000116
117 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000118 return ExtraRegInfo[VirtReg.reg].Stage;
119 }
120
121 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
122 ExtraRegInfo.resize(MRI->getNumVirtRegs());
123 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000124 }
125
126 template<typename Iterator>
127 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000128 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000129 for (;Begin != End; ++Begin) {
130 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000131 if (ExtraRegInfo[Reg].Stage == RS_New)
132 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000133 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000134 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000135
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000136 /// Cost of evicting interference.
137 struct EvictionCost {
138 unsigned BrokenHints; ///< Total number of broken hints.
139 float MaxWeight; ///< Maximum spill weight evicted.
140
141 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
142
143 bool operator<(const EvictionCost &O) const {
144 if (BrokenHints != O.BrokenHints)
145 return BrokenHints < O.BrokenHints;
146 return MaxWeight < O.MaxWeight;
147 }
148 };
149
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000150 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000151 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000152 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000153
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000154 /// Cached per-block interference maps
155 InterferenceCache IntfCache;
156
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000157 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000158 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000159
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000160 /// Global live range splitting candidate info.
161 struct GlobalSplitCandidate {
162 unsigned PhysReg;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000163 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000164 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000165 SmallVector<unsigned, 8> ActiveBlocks;
166
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000167 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000168 PhysReg = Reg;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000169 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000170 LiveBundles.clear();
171 ActiveBlocks.clear();
172 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000173 };
174
175 /// Candidate info for for each PhysReg in AllocationOrder.
176 /// This vector never shrinks, but grows to the size of the largest register
177 /// class.
178 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
179
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000180public:
181 RAGreedy();
182
183 /// Return the pass name.
184 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000185 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000186 }
187
188 /// RAGreedy analysis usage.
189 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000190 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000191 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000192 virtual void enqueue(LiveInterval *LI);
193 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000194 virtual unsigned selectOrSplit(LiveInterval&,
195 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000196
197 /// Perform register allocation.
198 virtual bool runOnMachineFunction(MachineFunction &mf);
199
200 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000201
202private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000203 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000204 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000205 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000206 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000207
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000208 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000209 bool addSplitConstraints(InterferenceCache::Cursor, float&);
210 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000211 void growRegion(GlobalSplitCandidate &Cand);
212 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000213 void splitAroundRegion(LiveInterval&, GlobalSplitCandidate&,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000214 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000215 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000216 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
217 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
218 void evictInterference(LiveInterval&, unsigned,
219 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000220
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000221 unsigned tryAssign(LiveInterval&, AllocationOrder&,
222 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000223 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000224 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000225 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
226 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000227 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
228 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000229 unsigned trySplit(LiveInterval&, AllocationOrder&,
230 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000231};
232} // end anonymous namespace
233
234char RAGreedy::ID = 0;
235
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000236#ifndef NDEBUG
237const char *const RAGreedy::StageName[] = {
238 "RS_New",
239 "RS_First",
240 "RS_Second",
241 "RS_Global",
242 "RS_Local",
243 "RS_Spill"
244};
245#endif
246
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000247// Hysteresis to use when comparing floats.
248// This helps stabilize decisions based on float comparisons.
249const float Hysteresis = 0.98f;
250
251
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000252FunctionPass* llvm::createGreedyRegisterAllocator() {
253 return new RAGreedy();
254}
255
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000256RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000257 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000258 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000259 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
260 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
261 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000262 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000263 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
264 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
265 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
266 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000267 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000268 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000269 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
270 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000271}
272
273void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
274 AU.setPreservesCFG();
275 AU.addRequired<AliasAnalysis>();
276 AU.addPreserved<AliasAnalysis>();
277 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000278 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000279 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000280 AU.addRequired<LiveDebugVariables>();
281 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000282 if (StrongPHIElim)
283 AU.addRequiredID(StrongPHIEliminationID);
284 AU.addRequiredTransitive<RegisterCoalescer>();
285 AU.addRequired<CalculateSpillWeights>();
286 AU.addRequired<LiveStacks>();
287 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000288 AU.addRequired<MachineDominatorTree>();
289 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000290 AU.addRequired<MachineLoopInfo>();
291 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000292 AU.addRequired<MachineLoopRanges>();
293 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000294 AU.addRequired<VirtRegMap>();
295 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000296 AU.addRequired<EdgeBundles>();
297 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000298 MachineFunctionPass::getAnalysisUsage(AU);
299}
300
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000301
302//===----------------------------------------------------------------------===//
303// LiveRangeEdit delegate methods
304//===----------------------------------------------------------------------===//
305
306void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
307 // LRE itself will remove from SlotIndexes and parent basic block.
308 VRM->RemoveMachineInstrFromMaps(MI);
309}
310
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000311bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
312 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
313 unassign(LIS->getInterval(VirtReg), PhysReg);
314 return true;
315 }
316 // Unassigned virtreg is probably in the priority queue.
317 // RegAllocBase will erase it after dequeueing.
318 return false;
319}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000320
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000321void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
322 unsigned PhysReg = VRM->getPhys(VirtReg);
323 if (!PhysReg)
324 return;
325
326 // Register is assigned, put it back on the queue for reassignment.
327 LiveInterval &LI = LIS->getInterval(VirtReg);
328 unassign(LI, PhysReg);
329 enqueue(&LI);
330}
331
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000332void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
333 // LRE may clone a virtual register because dead code elimination causes it to
334 // be split into connected components. Ensure that the new register gets the
335 // same stage as the parent.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000336 ExtraRegInfo.grow(New);
337 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000338}
339
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000340void RAGreedy::releaseMemory() {
341 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000342 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000343 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000344 RegAllocBase::releaseMemory();
345}
346
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000347void RAGreedy::enqueue(LiveInterval *LI) {
348 // Prioritize live ranges by size, assigning larger ranges first.
349 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000350 const unsigned Size = LI->getSize();
351 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000352 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
353 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000354 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000355
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000356 ExtraRegInfo.grow(Reg);
357 if (ExtraRegInfo[Reg].Stage == RS_New)
358 ExtraRegInfo[Reg].Stage = RS_First;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000359
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000360 if (ExtraRegInfo[Reg].Stage == RS_Second)
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000361 // Unsplit ranges that couldn't be allocated immediately are deferred until
362 // everything else has been allocated. Long ranges are allocated last so
363 // they are split against realistic interference.
364 Prio = (1u << 31) - Size;
365 else {
366 // Everything else is allocated in long->short order. Long ranges that don't
367 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000368 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000369
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000370 // Boost ranges that have a physical register hint.
371 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
372 Prio |= (1u << 30);
373 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000374
375 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000376}
377
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000378LiveInterval *RAGreedy::dequeue() {
379 if (Queue.empty())
380 return 0;
381 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
382 Queue.pop();
383 return LI;
384}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000385
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000386
387//===----------------------------------------------------------------------===//
388// Direct Assignment
389//===----------------------------------------------------------------------===//
390
391/// tryAssign - Try to assign VirtReg to an available register.
392unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
393 AllocationOrder &Order,
394 SmallVectorImpl<LiveInterval*> &NewVRegs) {
395 Order.rewind();
396 unsigned PhysReg;
397 while ((PhysReg = Order.next()))
398 if (!checkPhysRegInterference(VirtReg, PhysReg))
399 break;
400 if (!PhysReg || Order.isHint(PhysReg))
401 return PhysReg;
402
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000403 // PhysReg is available, but there may be a better choice.
404
405 // If we missed a simple hint, try to cheaply evict interference from the
406 // preferred register.
407 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
408 if (Order.isHint(Hint)) {
409 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
410 EvictionCost MaxCost(1);
411 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
412 evictInterference(VirtReg, Hint, NewVRegs);
413 return Hint;
414 }
415 }
416
417 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000418 unsigned Cost = TRI->getCostPerUse(PhysReg);
419
420 // Most registers have 0 additional cost.
421 if (!Cost)
422 return PhysReg;
423
424 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
425 << '\n');
426 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
427 return CheapReg ? CheapReg : PhysReg;
428}
429
430
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000431//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000432// Interference eviction
433//===----------------------------------------------------------------------===//
434
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000435/// shouldEvict - determine if A should evict the assigned live range B. The
436/// eviction policy defined by this function together with the allocation order
437/// defined by enqueue() decides which registers ultimately end up being split
438/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000439///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000440/// Cascade numbers are used to prevent infinite loops if this function is a
441/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000442///
443/// @param A The live range to be assigned.
444/// @param IsHint True when A is about to be assigned to its preferred
445/// register.
446/// @param B The live range to be evicted.
447/// @param BreaksHint True when B is already assigned to its preferred register.
448bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
449 LiveInterval &B, bool BreaksHint) {
450 bool CanSplit = getStage(B) <= RS_Second;
451
452 // Be fairly aggressive about following hints as long as the evictee can be
453 // split.
454 if (CanSplit && IsHint && !BreaksHint)
455 return true;
456
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000457 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000458}
459
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000460/// canEvictInterference - Return true if all interferences between VirtReg and
461/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
462///
463/// @param VirtReg Live range that is about to be assigned.
464/// @param PhysReg Desired register for assignment.
465/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
466/// @param MaxCost Only look for cheaper candidates and update with new cost
467/// when returning true.
468/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000469bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000470 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000471 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
472 // involved in an eviction before. If a cascade number was assigned, deny
473 // evicting anything with the same or a newer cascade number. This prevents
474 // infinite eviction loops.
475 //
476 // This works out so a register without a cascade number is allowed to evict
477 // anything, and it can be evicted by anything.
478 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
479 if (!Cascade)
480 Cascade = NextCascade;
481
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000482 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000483 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
484 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000485 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000486 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000487 return false;
488
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000489 // Check if any interfering live range is heavier than MaxWeight.
490 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
491 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000492 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
493 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000494 // Never evict spill products. They cannot split or spill.
495 if (getStage(*Intf) == RS_Spill)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000496 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000497 // Once a live range becomes small enough, it is urgent that we find a
498 // register for it. This is indicated by an infinite spill weight. These
499 // urgent live ranges get to evict almost anything.
500 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
501 // Only evict older cascades or live ranges without a cascade.
502 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
503 if (Cascade <= IntfCascade) {
504 if (!Urgent)
505 return false;
506 // We permit breaking cascades for urgent evictions. It should be the
507 // last resort, though, so make it really expensive.
508 Cost.BrokenHints += 10;
509 }
510 // Would this break a satisfied hint?
511 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
512 // Update eviction cost.
513 Cost.BrokenHints += BreaksHint;
514 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
515 // Abort if this would be too expensive.
516 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000517 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000518 // Finally, apply the eviction policy for non-urgent evictions.
519 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000520 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000521 }
522 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000523 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000524 return true;
525}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000526
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000527/// evictInterference - Evict any interferring registers that prevent VirtReg
528/// from being assigned to Physreg. This assumes that canEvictInterference
529/// returned true.
530void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
531 SmallVectorImpl<LiveInterval*> &NewVRegs) {
532 // Make sure that VirtReg has a cascade number, and assign that cascade
533 // number to every evicted register. These live ranges than then only be
534 // evicted by a newer cascade, preventing infinite loops.
535 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
536 if (!Cascade)
537 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
538
539 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
540 << " interference: Cascade " << Cascade << '\n');
541 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
542 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
543 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
544 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
545 LiveInterval *Intf = Q.interferingVRegs()[i];
546 unassign(*Intf, VRM->getPhys(Intf->reg));
547 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
548 VirtReg.isSpillable() < Intf->isSpillable()) &&
549 "Cannot decrease cascade number, illegal eviction");
550 ExtraRegInfo[Intf->reg].Cascade = Cascade;
551 ++NumEvicted;
552 NewVRegs.push_back(Intf);
553 }
554 }
555}
556
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000557/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000558/// @param VirtReg Currently unassigned virtual register.
559/// @param Order Physregs to try.
560/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000561unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
562 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000563 SmallVectorImpl<LiveInterval*> &NewVRegs,
564 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000565 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
566
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000567 // Keep track of the cheapest interference seen so far.
568 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000569 unsigned BestPhys = 0;
570
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000571 // When we are just looking for a reduced cost per use, don't break any
572 // hints, and only evict smaller spill weights.
573 if (CostPerUseLimit < ~0u) {
574 BestCost.BrokenHints = 0;
575 BestCost.MaxWeight = VirtReg.weight;
576 }
577
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000578 Order.rewind();
579 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000580 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
581 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000582 // The first use of a callee-saved register in a function has cost 1.
583 // Don't start using a CSR when the CostPerUseLimit is low.
584 if (CostPerUseLimit == 1)
585 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
586 if (!MRI->isPhysRegUsed(CSR)) {
587 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
588 << PrintReg(CSR, TRI) << '\n');
589 continue;
590 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000591
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000592 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000593 continue;
594
595 // Best so far.
596 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000597
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000598 // Stop if the hint can be used.
599 if (Order.isHint(PhysReg))
600 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000601 }
602
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000603 if (!BestPhys)
604 return 0;
605
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000606 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000607 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000608}
609
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000610
611//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000612// Region Splitting
613//===----------------------------------------------------------------------===//
614
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000615/// addSplitConstraints - Fill out the SplitConstraints vector based on the
616/// interference pattern in Physreg and its aliases. Add the constraints to
617/// SpillPlacement and return the static cost of this split in Cost, assuming
618/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000619/// Return false if there are no bundles with positive bias.
620bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
621 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000622 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000623
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000624 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000625 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000626 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000627 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
628 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000629 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000630
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000631 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000632 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000633 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
634 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000635
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000636 if (!Intf.hasInterference())
637 continue;
638
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000639 // Number of spill code instructions to insert.
640 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000641
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000642 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000643 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000644 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000645 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000646 else if (Intf.first() < BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000647 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000648 else if (Intf.first() < BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000649 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000650 }
651
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000652 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000653 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000654 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000655 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000656 else if (Intf.last() > BI.LastUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000657 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesena2e79ef2011-05-30 01:33:26 +0000658 else if (Intf.last() > BI.FirstUse)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000659 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000660 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000661
662 // Accumulate the total frequency of inserted spill code.
663 if (Ins)
664 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000665 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000666 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000667
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000668 // Add constraints for use-blocks. Note that these are the only constraints
669 // that may add a positive bias, it is downhill from here.
670 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000671 return SpillPlacer->scanActiveBundles();
672}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000673
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000674
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000675/// addThroughConstraints - Add constraints and links to SpillPlacer from the
676/// live-through blocks in Blocks.
677void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
678 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000679 const unsigned GroupSize = 8;
680 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000681 unsigned TBS[GroupSize];
682 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000683
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000684 for (unsigned i = 0; i != Blocks.size(); ++i) {
685 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000686 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000687
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000688 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000689 assert(T < GroupSize && "Array overflow");
690 TBS[T] = Number;
691 if (++T == GroupSize) {
692 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
693 T = 0;
694 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000695 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000696 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000697
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000698 assert(B < GroupSize && "Array overflow");
699 BCS[B].Number = Number;
700
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000701 // Interference for the live-in value.
702 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
703 BCS[B].Entry = SpillPlacement::MustSpill;
704 else
705 BCS[B].Entry = SpillPlacement::PrefSpill;
706
707 // Interference for the live-out value.
708 if (Intf.last() >= SA->getLastSplitPoint(Number))
709 BCS[B].Exit = SpillPlacement::MustSpill;
710 else
711 BCS[B].Exit = SpillPlacement::PrefSpill;
712
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000713 if (++B == GroupSize) {
714 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
715 SpillPlacer->addConstraints(Array);
716 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000717 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000718 }
719
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000720 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
721 SpillPlacer->addConstraints(Array);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000722 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000723}
724
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000725void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000726 // Keep track of through blocks that have not been added to SpillPlacer.
727 BitVector Todo = SA->getThroughBlocks();
728 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
729 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000730#ifndef NDEBUG
731 unsigned Visited = 0;
732#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000733
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000734 for (;;) {
735 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000736 // Find new through blocks in the periphery of PrefRegBundles.
737 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
738 unsigned Bundle = NewBundles[i];
739 // Look at all blocks connected to Bundle in the full graph.
740 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
741 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
742 I != E; ++I) {
743 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000744 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000745 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000746 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000747 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000748 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000749#ifndef NDEBUG
750 ++Visited;
751#endif
752 }
753 }
754 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000755 if (ActiveBlocks.size() == AddedTo)
756 break;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000757 addThroughConstraints(Cand.Intf,
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000758 ArrayRef<unsigned>(ActiveBlocks).slice(AddedTo));
759 AddedTo = ActiveBlocks.size();
760
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000761 // Perhaps iterating can enable more bundles?
762 SpillPlacer->iterate();
763 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000764 DEBUG(dbgs() << ", v=" << Visited);
765}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000766
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000767/// calcSpillCost - Compute how expensive it would be to split the live range in
768/// SA around all use blocks instead of forming bundle regions.
769float RAGreedy::calcSpillCost() {
770 float Cost = 0;
771 const LiveInterval &LI = SA->getParent();
772 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
773 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
774 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
775 unsigned Number = BI.MBB->getNumber();
776 // We normally only need one spill instruction - a load or a store.
777 Cost += SpillPlacer->getBlockFrequency(Number);
778
779 // Unless the value is redefined in the block.
780 if (BI.LiveIn && BI.LiveOut) {
781 SlotIndex Start, Stop;
782 tie(Start, Stop) = Indexes->getMBBRange(Number);
783 LiveInterval::const_iterator I = LI.find(Start);
784 assert(I != LI.end() && "Expected live-in value");
785 // Is there a different live-out value? If so, we need an extra spill
786 // instruction.
787 if (I->end < Stop)
788 Cost += SpillPlacer->getBlockFrequency(Number);
789 }
790 }
791 return Cost;
792}
793
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000794/// calcGlobalSplitCost - Return the global split cost of following the split
795/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000796/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000797///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000798float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000799 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000800 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000801 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
802 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
803 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000804 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000805 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
806 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
807 unsigned Ins = 0;
808
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000809 if (BI.LiveIn)
810 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
811 if (BI.LiveOut)
812 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000813 if (Ins)
814 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000815 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000816
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000817 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
818 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000819 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
820 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000821 if (!RegIn && !RegOut)
822 continue;
823 if (RegIn && RegOut) {
824 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000825 Cand.Intf.moveToBlock(Number);
826 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000827 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
828 continue;
829 }
830 // live-in / stack-out or stack-in live-out.
831 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000832 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000833 return GlobalCost;
834}
835
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000836/// splitAroundRegion - Split VirtReg around the region determined by
837/// LiveBundles. Make an effort to avoid interference from PhysReg.
838///
839/// The 'register' interval is going to contain as many uses as possible while
840/// avoiding interference. The 'stack' interval is the complement constructed by
841/// SplitEditor. It will contain the rest.
842///
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000843void RAGreedy::splitAroundRegion(LiveInterval &VirtReg,
844 GlobalSplitCandidate &Cand,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000845 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000846 const BitVector &LiveBundles = Cand.LiveBundles;
847
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000848 DEBUG({
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000849 dbgs() << "Splitting around region for " << PrintReg(Cand.PhysReg, TRI)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000850 << " with bundles";
851 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
852 dbgs() << " EB#" << i;
853 dbgs() << ".\n";
854 });
855
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000856 InterferenceCache::Cursor &Intf = Cand.Intf;
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000857 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000858 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000859
860 // Create the main cross-block interval.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000861 const unsigned MainIntv = SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000862
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000863 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000864 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
865 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
866 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000867 bool RegIn = BI.LiveIn &&
868 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
869 bool RegOut = BI.LiveOut &&
870 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000871
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000872 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000873 if (!RegIn && !RegOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000874 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000875 if (!BI.isOneInstr()) {
876 SE->splitSingleBlock(BI);
877 SE->selectIntv(MainIntv);
878 }
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000879 continue;
880 }
881
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000882 Intf.moveToBlock(BI.MBB->getNumber());
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000883
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000884 if (RegIn && RegOut)
885 SE->splitLiveThroughBlock(BI.MBB->getNumber(),
886 MainIntv, Intf.first(),
887 MainIntv, Intf.last());
888 else if (RegIn)
889 SE->splitRegInBlock(BI, MainIntv, Intf.first());
890 else
891 SE->splitRegOutBlock(BI, MainIntv, Intf.last());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000892 }
893
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000894 // Handle live-through blocks.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000895 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
896 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000897 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
898 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000899 if (!RegIn && !RegOut)
900 continue;
901 Intf.moveToBlock(Number);
902 SE->splitLiveThroughBlock(Number, RegIn ? MainIntv : 0, Intf.first(),
903 RegOut ? MainIntv : 0, Intf.last());
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000904 }
905
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000906 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000907
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000908 SmallVector<unsigned, 8> IntvMap;
909 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +0000910 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
911
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000912 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +0000913 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000914
915 // Sort out the new intervals created by splitting. We get four kinds:
916 // - Remainder intervals should not be split again.
917 // - Candidate intervals can be assigned to Cand.PhysReg.
918 // - Block-local splits are candidates for local splitting.
919 // - DCE leftovers should go back on the queue.
920 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000921 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000922
923 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000924 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000925 continue;
926
927 // Remainder interval. Don't try splitting again, spill if it doesn't
928 // allocate.
929 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000930 setStage(Reg, RS_Global);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000931 continue;
932 }
933
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000934 // Main interval. Allow repeated splitting as long as the number of live
935 // blocks is strictly decreasing.
936 if (IntvMap[i] == MainIntv) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000937 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000938 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
939 << " blocks as original.\n");
940 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000941 setStage(Reg, RS_Global);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +0000942 }
943 continue;
944 }
945
946 // Other intervals are treated as new. This includes local intervals created
947 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +0000948 }
949
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000950 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000951 MF->verify(this, "After splitting live range around region");
952}
953
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000954unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
955 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000956 float BestCost = Hysteresis * calcSpillCost();
957 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000958 const unsigned NoCand = ~0u;
959 unsigned BestCand = NoCand;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000960 unsigned NumCands = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000961
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000962 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000963 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +0000964 // Discard bad candidates before we run out of interference cache cursors.
965 // This will only affect register classes with a lot of registers (>32).
966 if (NumCands == IntfCache.getMaxCursors()) {
967 unsigned WorstCount = ~0u;
968 unsigned Worst = 0;
969 for (unsigned i = 0; i != NumCands; ++i) {
970 if (i == BestCand)
971 continue;
972 unsigned Count = GlobalCand[i].LiveBundles.count();
973 if (Count < WorstCount)
974 Worst = i, WorstCount = Count;
975 }
976 --NumCands;
977 GlobalCand[Worst] = GlobalCand[NumCands];
978 }
979
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000980 if (GlobalCand.size() <= NumCands)
981 GlobalCand.resize(NumCands+1);
982 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
983 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000984
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000985 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000986 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000987 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000988 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000989 continue;
990 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000991 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000992 if (Cost >= BestCost) {
993 DEBUG({
994 if (BestCand == NoCand)
995 dbgs() << " worse than no bundles\n";
996 else
997 dbgs() << " worse than "
998 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
999 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001000 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001001 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001002 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001003
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001004 SpillPlacer->finish();
1005
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001006 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001007 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001008 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001009 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001010 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001011
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001012 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001013 DEBUG({
1014 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001015 for (int i = Cand.LiveBundles.find_first(); i>=0;
1016 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001017 dbgs() << " EB#" << i;
1018 dbgs() << ".\n";
1019 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001020 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001021 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001022 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001023 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001024 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001025 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001026
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001027 if (BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001028 return 0;
1029
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +00001030 splitAroundRegion(VirtReg, GlobalCand[BestCand], NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001031 return 0;
1032}
1033
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001034
1035//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001036// Local Splitting
1037//===----------------------------------------------------------------------===//
1038
1039
1040/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1041/// in order to use PhysReg between two entries in SA->UseSlots.
1042///
1043/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1044///
1045void RAGreedy::calcGapWeights(unsigned PhysReg,
1046 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001047 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1048 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001049 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1050 const unsigned NumGaps = Uses.size()-1;
1051
1052 // Start and end points for the interference check.
1053 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1054 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1055
1056 GapWeight.assign(NumGaps, 0.0f);
1057
1058 // Add interference from each overlapping register.
1059 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1060 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1061 .checkInterference())
1062 continue;
1063
1064 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1065 // so we don't need InterferenceQuery.
1066 //
1067 // Interference that overlaps an instruction is counted in both gaps
1068 // surrounding the instruction. The exception is interference before
1069 // StartIdx and after StopIdx.
1070 //
1071 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1072 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1073 // Skip the gaps before IntI.
1074 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1075 if (++Gap == NumGaps)
1076 break;
1077 if (Gap == NumGaps)
1078 break;
1079
1080 // Update the gaps covered by IntI.
1081 const float weight = IntI.value()->weight;
1082 for (; Gap != NumGaps; ++Gap) {
1083 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1084 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1085 break;
1086 }
1087 if (Gap == NumGaps)
1088 break;
1089 }
1090 }
1091}
1092
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001093/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1094/// basic block.
1095///
1096unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1097 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001098 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1099 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001100
1101 // Note that it is possible to have an interval that is live-in or live-out
1102 // while only covering a single block - A phi-def can use undef values from
1103 // predecessors, and the block could be a single-block loop.
1104 // We don't bother doing anything clever about such a case, we simply assume
1105 // that the interval is continuous from FirstUse to LastUse. We should make
1106 // sure that we don't do anything illegal to such an interval, though.
1107
1108 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1109 if (Uses.size() <= 2)
1110 return 0;
1111 const unsigned NumGaps = Uses.size()-1;
1112
1113 DEBUG({
1114 dbgs() << "tryLocalSplit: ";
1115 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1116 dbgs() << ' ' << SA->UseSlots[i];
1117 dbgs() << '\n';
1118 });
1119
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001120 // Since we allow local split results to be split again, there is a risk of
1121 // creating infinite loops. It is tempting to require that the new live
1122 // ranges have less instructions than the original. That would guarantee
1123 // convergence, but it is too strict. A live range with 3 instructions can be
1124 // split 2+3 (including the COPY), and we want to allow that.
1125 //
1126 // Instead we use these rules:
1127 //
1128 // 1. Allow any split for ranges with getStage() < RS_Local. (Except for the
1129 // noop split, of course).
1130 // 2. Require progress be made for ranges with getStage() >= RS_Local. All
1131 // the new ranges must have fewer instructions than before the split.
1132 // 3. New ranges with the same number of instructions are marked RS_Local,
1133 // smaller ranges are marked RS_New.
1134 //
1135 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1136 // excessive splitting and infinite loops.
1137 //
1138 bool ProgressRequired = getStage(VirtReg) >= RS_Local;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001139
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001140 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001141 unsigned BestBefore = NumGaps;
1142 unsigned BestAfter = 0;
1143 float BestDiff = 0;
1144
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001145 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001146 SmallVector<float, 8> GapWeight;
1147
1148 Order.rewind();
1149 while (unsigned PhysReg = Order.next()) {
1150 // Keep track of the largest spill weight that would need to be evicted in
1151 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1152 calcGapWeights(PhysReg, GapWeight);
1153
1154 // Try to find the best sequence of gaps to close.
1155 // The new spill weight must be larger than any gap interference.
1156
1157 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001158 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001159
1160 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1161 // It is the spill weight that needs to be evicted.
1162 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001163
1164 for (;;) {
1165 // Live before/after split?
1166 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1167 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1168
1169 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1170 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1171 << " i=" << MaxGap);
1172
1173 // Stop before the interval gets so big we wouldn't be making progress.
1174 if (!LiveBefore && !LiveAfter) {
1175 DEBUG(dbgs() << " all\n");
1176 break;
1177 }
1178 // Should the interval be extended or shrunk?
1179 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001180
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001181 // How many gaps would the new range have?
1182 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1183
1184 // Legally, without causing looping?
1185 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1186
1187 if (Legal && MaxGap < HUGE_VALF) {
1188 // Estimate the new spill weight. Each instruction reads or writes the
1189 // register. Conservatively assume there are no read-modify-write
1190 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001191 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001192 // Try to guess the size of the new interval.
1193 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1194 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1195 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001196 // Would this split be possible to allocate?
1197 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001198 DEBUG(dbgs() << " w=" << EstWeight);
1199 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001200 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001201 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001202 if (Diff > BestDiff) {
1203 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001204 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001205 BestBefore = SplitBefore;
1206 BestAfter = SplitAfter;
1207 }
1208 }
1209 }
1210
1211 // Try to shrink.
1212 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001213 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001214 DEBUG(dbgs() << " shrink\n");
1215 // Recompute the max when necessary.
1216 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1217 MaxGap = GapWeight[SplitBefore];
1218 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1219 MaxGap = std::max(MaxGap, GapWeight[i]);
1220 }
1221 continue;
1222 }
1223 MaxGap = 0;
1224 }
1225
1226 // Try to extend the interval.
1227 if (SplitAfter >= NumGaps) {
1228 DEBUG(dbgs() << " end\n");
1229 break;
1230 }
1231
1232 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001233 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001234 }
1235 }
1236
1237 // Didn't find any candidates?
1238 if (BestBefore == NumGaps)
1239 return 0;
1240
1241 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1242 << '-' << Uses[BestAfter] << ", " << BestDiff
1243 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1244
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001245 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001246 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001247
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001248 SE->openIntv();
1249 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1250 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1251 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001252 SmallVector<unsigned, 8> IntvMap;
1253 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001254 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001255
1256 // If the new range has the same number of instructions as before, mark it as
1257 // RS_Local so the next split will be forced to make progress. Otherwise,
1258 // leave the new intervals as RS_New so they can compete.
1259 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1260 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1261 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1262 if (NewGaps >= NumGaps) {
1263 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1264 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001265 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1266 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001267 setStage(*LREdit.get(i), RS_Local);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001268 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1269 }
1270 DEBUG(dbgs() << '\n');
1271 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001272 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001273
1274 return 0;
1275}
1276
1277//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001278// Live Range Splitting
1279//===----------------------------------------------------------------------===//
1280
1281/// trySplit - Try to split VirtReg or one of its interferences, making it
1282/// assignable.
1283/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1284unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1285 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001286 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001287 if (LIS->intervalIsInOneMBB(VirtReg)) {
1288 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001289 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001290 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001291 }
1292
1293 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001294
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001295 // Don't iterate global splitting.
1296 // Move straight to spilling if this range was produced by a global split.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001297 if (getStage(VirtReg) >= RS_Global)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001298 return 0;
1299
1300 SA->analyze(&VirtReg);
1301
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001302 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1303 // coalescer. That may cause the range to become allocatable which means that
1304 // tryRegionSplit won't be making progress. This check should be replaced with
1305 // an assertion when the coalescer is fixed.
1306 if (SA->didRepairRange()) {
1307 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001308 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001309 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1310 return PhysReg;
1311 }
1312
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001313 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001314 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1315 if (PhysReg || !NewVRegs.empty())
1316 return PhysReg;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001317
1318 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001319 SplitAnalysis::BlockPtrSet Blocks;
1320 if (SA->getMultiUseBlocks(Blocks)) {
1321 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1322 SE->reset(LREdit);
1323 SE->splitSingleBlocks(Blocks);
1324 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Global);
1325 if (VerifyEnabled)
1326 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001327 }
1328
1329 // Don't assign any physregs.
1330 return 0;
1331}
1332
1333
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001334//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001335// Main Entry Point
1336//===----------------------------------------------------------------------===//
1337
1338unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001339 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001340 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001341 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001342 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1343 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001344
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001345 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001346 DEBUG(dbgs() << StageName[Stage]
1347 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001348
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001349 // Try to evict a less worthy live range, but only for ranges from the primary
1350 // queue. The RS_Second ranges already failed to do this, and they should not
1351 // get a second chance until they have been split.
1352 if (Stage != RS_Second)
1353 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1354 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001355
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001356 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1357
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001358 // The first time we see a live range, don't try to split or spill.
1359 // Wait until the second time, when all smaller ranges have been allocated.
1360 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +00001361 if (Stage == RS_First) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001362 setStage(VirtReg, RS_Second);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001363 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001364 NewVRegs.push_back(&VirtReg);
1365 return 0;
1366 }
1367
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001368 // If we couldn't allocate a register from spilling, there is probably some
1369 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +00001370 if (Stage >= RS_Spill || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001371 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001372
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001373 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001374 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1375 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001376 return PhysReg;
1377
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001378 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001379 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001380 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1381 spiller().spill(LRE);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001382 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001383
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001384 if (VerifyEnabled)
1385 MF->verify(this, "After spilling");
1386
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001387 // The live virtual register requesting allocation was spilled, so tell
1388 // the caller not to allocate anything during this round.
1389 return 0;
1390}
1391
1392bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1393 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1394 << "********** Function: "
1395 << ((Value*)mf.getFunction())->getName() << '\n');
1396
1397 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001398 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001399 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001400
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001401 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001402 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001403 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001404 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001405 Loops = &getAnalysis<MachineLoopInfo>();
1406 LoopRanges = &getAnalysis<MachineLoopRanges>();
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}