blob: 1cbd5a925f2cb5aaae2a22b2273ce6dc243b34e1 [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 Olesen00005782011-07-26 23:41:46 +000041#include "llvm/Support/CommandLine.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 Olesen21384c42011-07-30 17:19:14 +000055cl::opt<bool> CompactRegions("compact-regions");
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000056
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000057static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
58 createGreedyRegisterAllocator);
59
60namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000061class RAGreedy : public MachineFunctionPass,
62 public RegAllocBase,
63 private LiveRangeEdit::Delegate {
64
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000065 // context
66 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000067
68 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000069 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000070 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000071 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000072 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000073 EdgeBundles *Bundles;
74 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000075 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000076
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000077 // state
78 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000079 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000080 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000081
82 // Live ranges pass through a number of stages as we try to allocate them.
83 // Some of the stages may also create new live ranges:
84 //
85 // - Region splitting.
86 // - Per-block splitting.
87 // - Local splitting.
88 // - Spilling.
89 //
90 // Ranges produced by one of the stages skip the previous stages when they are
91 // dequeued. This improves performance because we can skip interference checks
92 // that are unlikely to give any results. It also guarantees that the live
93 // range splitting algorithm terminates, something that is otherwise hard to
94 // ensure.
95 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +000096 /// Newly created live range that has never been queued.
97 RS_New,
98
99 /// Only attempt assignment and eviction. Then requeue as RS_Split.
100 RS_Assign,
101
102 /// Attempt live range splitting if assignment is impossible.
103 RS_Split,
104
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000105 /// Attempt more aggressive live range splitting that is guaranteed to make
106 /// progress. This is used for split products that may not be making
107 /// progress.
108 RS_Split2,
109
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000110 /// Live range will be spilled. No more splitting will be attempted.
111 RS_Spill,
112
113 /// There is nothing more we can do to this live range. Abort compilation
114 /// if it can't be assigned.
115 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000116 };
117
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000118 static const char *const StageName[];
119
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000120 // RegInfo - Keep additional information about each live range.
121 struct RegInfo {
122 LiveRangeStage Stage;
123
124 // Cascade - Eviction loop prevention. See canEvictInterference().
125 unsigned Cascade;
126
127 RegInfo() : Stage(RS_New), Cascade(0) {}
128 };
129
130 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000131
132 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000133 return ExtraRegInfo[VirtReg.reg].Stage;
134 }
135
136 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
137 ExtraRegInfo.resize(MRI->getNumVirtRegs());
138 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000139 }
140
141 template<typename Iterator>
142 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000143 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000144 for (;Begin != End; ++Begin) {
145 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000146 if (ExtraRegInfo[Reg].Stage == RS_New)
147 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000148 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000149 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000150
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000151 /// Cost of evicting interference.
152 struct EvictionCost {
153 unsigned BrokenHints; ///< Total number of broken hints.
154 float MaxWeight; ///< Maximum spill weight evicted.
155
156 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
157
158 bool operator<(const EvictionCost &O) const {
159 if (BrokenHints != O.BrokenHints)
160 return BrokenHints < O.BrokenHints;
161 return MaxWeight < O.MaxWeight;
162 }
163 };
164
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000165 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000166 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000167 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000168
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000169 /// Cached per-block interference maps
170 InterferenceCache IntfCache;
171
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000172 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000173 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000174
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000175 /// Global live range splitting candidate info.
176 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000177 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000178 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000179
180 // SplitKit interval index for this candidate.
181 unsigned IntvIdx;
182
183 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000184 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000185
186 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000187 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000188 SmallVector<unsigned, 8> ActiveBlocks;
189
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000190 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000191 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000192 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000193 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000194 LiveBundles.clear();
195 ActiveBlocks.clear();
196 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000197
198 // Set B[i] = C for every live bundle where B[i] was NoCand.
199 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
200 unsigned Count = 0;
201 for (int i = LiveBundles.find_first(); i >= 0;
202 i = LiveBundles.find_next(i))
203 if (B[i] == NoCand) {
204 B[i] = C;
205 Count++;
206 }
207 return Count;
208 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000209 };
210
211 /// Candidate info for for each PhysReg in AllocationOrder.
212 /// This vector never shrinks, but grows to the size of the largest register
213 /// class.
214 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
215
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000216 enum { NoCand = ~0u };
217
218 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
219 /// NoCand which indicates the stack interval.
220 SmallVector<unsigned, 32> BundleCand;
221
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000222public:
223 RAGreedy();
224
225 /// Return the pass name.
226 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000227 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000228 }
229
230 /// RAGreedy analysis usage.
231 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000232 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000233 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000234 virtual void enqueue(LiveInterval *LI);
235 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000236 virtual unsigned selectOrSplit(LiveInterval&,
237 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000238
239 /// Perform register allocation.
240 virtual bool runOnMachineFunction(MachineFunction &mf);
241
242 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000243
244private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000245 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000246 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000247 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000248 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000249
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000250 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000251 bool addSplitConstraints(InterferenceCache::Cursor, float&);
252 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000253 void growRegion(GlobalSplitCandidate &Cand);
254 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000255 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000256 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000257 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000258 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
259 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
260 void evictInterference(LiveInterval&, unsigned,
261 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000262
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000263 unsigned tryAssign(LiveInterval&, AllocationOrder&,
264 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000265 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000266 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000267 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
268 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000269 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000271 unsigned trySplit(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000273};
274} // end anonymous namespace
275
276char RAGreedy::ID = 0;
277
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000278#ifndef NDEBUG
279const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000280 "RS_New",
281 "RS_Assign",
282 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000283 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000284 "RS_Spill",
285 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000286};
287#endif
288
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000289// Hysteresis to use when comparing floats.
290// This helps stabilize decisions based on float comparisons.
291const float Hysteresis = 0.98f;
292
293
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000294FunctionPass* llvm::createGreedyRegisterAllocator() {
295 return new RAGreedy();
296}
297
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000298RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000299 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000300 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000301 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
302 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
303 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000304 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000305 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
306 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
307 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
308 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
309 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000310 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
311 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000312}
313
314void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
315 AU.setPreservesCFG();
316 AU.addRequired<AliasAnalysis>();
317 AU.addPreserved<AliasAnalysis>();
318 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000319 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000320 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000321 AU.addRequired<LiveDebugVariables>();
322 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000323 if (StrongPHIElim)
324 AU.addRequiredID(StrongPHIEliminationID);
325 AU.addRequiredTransitive<RegisterCoalescer>();
326 AU.addRequired<CalculateSpillWeights>();
327 AU.addRequired<LiveStacks>();
328 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000329 AU.addRequired<MachineDominatorTree>();
330 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000331 AU.addRequired<MachineLoopInfo>();
332 AU.addPreserved<MachineLoopInfo>();
333 AU.addRequired<VirtRegMap>();
334 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000335 AU.addRequired<EdgeBundles>();
336 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000337 MachineFunctionPass::getAnalysisUsage(AU);
338}
339
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000340
341//===----------------------------------------------------------------------===//
342// LiveRangeEdit delegate methods
343//===----------------------------------------------------------------------===//
344
345void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
346 // LRE itself will remove from SlotIndexes and parent basic block.
347 VRM->RemoveMachineInstrFromMaps(MI);
348}
349
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000350bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
351 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
352 unassign(LIS->getInterval(VirtReg), PhysReg);
353 return true;
354 }
355 // Unassigned virtreg is probably in the priority queue.
356 // RegAllocBase will erase it after dequeueing.
357 return false;
358}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000359
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000360void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
361 unsigned PhysReg = VRM->getPhys(VirtReg);
362 if (!PhysReg)
363 return;
364
365 // Register is assigned, put it back on the queue for reassignment.
366 LiveInterval &LI = LIS->getInterval(VirtReg);
367 unassign(LI, PhysReg);
368 enqueue(&LI);
369}
370
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000371void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
372 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000373 // be split into connected components. The new components are much smaller
374 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000375 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000376 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000377 ExtraRegInfo.grow(New);
378 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000379}
380
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000381void RAGreedy::releaseMemory() {
382 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000383 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000384 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000385 RegAllocBase::releaseMemory();
386}
387
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000388void RAGreedy::enqueue(LiveInterval *LI) {
389 // Prioritize live ranges by size, assigning larger ranges first.
390 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000391 const unsigned Size = LI->getSize();
392 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000393 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
394 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000395 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000396
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000397 ExtraRegInfo.grow(Reg);
398 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000399 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000400
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000401 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000402 // Unsplit ranges that couldn't be allocated immediately are deferred until
403 // everything else has been allocated. Long ranges are allocated last so
404 // they are split against realistic interference.
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000405 if (CompactRegions)
406 Prio = Size;
407 else
408 Prio = (1u << 31) - Size;
409 } else {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000410 // Everything else is allocated in long->short order. Long ranges that don't
411 // fit should be spilled ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000412 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000413
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000414 // Boost ranges that have a physical register hint.
415 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
416 Prio |= (1u << 30);
417 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000418
419 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000420}
421
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000422LiveInterval *RAGreedy::dequeue() {
423 if (Queue.empty())
424 return 0;
425 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
426 Queue.pop();
427 return LI;
428}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000429
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000430
431//===----------------------------------------------------------------------===//
432// Direct Assignment
433//===----------------------------------------------------------------------===//
434
435/// tryAssign - Try to assign VirtReg to an available register.
436unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
437 AllocationOrder &Order,
438 SmallVectorImpl<LiveInterval*> &NewVRegs) {
439 Order.rewind();
440 unsigned PhysReg;
441 while ((PhysReg = Order.next()))
442 if (!checkPhysRegInterference(VirtReg, PhysReg))
443 break;
444 if (!PhysReg || Order.isHint(PhysReg))
445 return PhysReg;
446
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000447 // PhysReg is available, but there may be a better choice.
448
449 // If we missed a simple hint, try to cheaply evict interference from the
450 // preferred register.
451 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
452 if (Order.isHint(Hint)) {
453 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
454 EvictionCost MaxCost(1);
455 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
456 evictInterference(VirtReg, Hint, NewVRegs);
457 return Hint;
458 }
459 }
460
461 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000462 unsigned Cost = TRI->getCostPerUse(PhysReg);
463
464 // Most registers have 0 additional cost.
465 if (!Cost)
466 return PhysReg;
467
468 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
469 << '\n');
470 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
471 return CheapReg ? CheapReg : PhysReg;
472}
473
474
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000475//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000476// Interference eviction
477//===----------------------------------------------------------------------===//
478
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000479/// shouldEvict - determine if A should evict the assigned live range B. The
480/// eviction policy defined by this function together with the allocation order
481/// defined by enqueue() decides which registers ultimately end up being split
482/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000483///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000484/// Cascade numbers are used to prevent infinite loops if this function is a
485/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000486///
487/// @param A The live range to be assigned.
488/// @param IsHint True when A is about to be assigned to its preferred
489/// register.
490/// @param B The live range to be evicted.
491/// @param BreaksHint True when B is already assigned to its preferred register.
492bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
493 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000494 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000495
496 // Be fairly aggressive about following hints as long as the evictee can be
497 // split.
498 if (CanSplit && IsHint && !BreaksHint)
499 return true;
500
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000501 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000502}
503
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000504/// canEvictInterference - Return true if all interferences between VirtReg and
505/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
506///
507/// @param VirtReg Live range that is about to be assigned.
508/// @param PhysReg Desired register for assignment.
509/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
510/// @param MaxCost Only look for cheaper candidates and update with new cost
511/// when returning true.
512/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000513bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000514 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000515 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
516 // involved in an eviction before. If a cascade number was assigned, deny
517 // evicting anything with the same or a newer cascade number. This prevents
518 // infinite eviction loops.
519 //
520 // This works out so a register without a cascade number is allowed to evict
521 // anything, and it can be evicted by anything.
522 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
523 if (!Cascade)
524 Cascade = NextCascade;
525
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000526 EvictionCost Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000527 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
528 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000529 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000530 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000531 return false;
532
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000533 // Check if any interfering live range is heavier than MaxWeight.
534 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
535 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000536 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
537 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000538 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000539 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000540 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000541 // Once a live range becomes small enough, it is urgent that we find a
542 // register for it. This is indicated by an infinite spill weight. These
543 // urgent live ranges get to evict almost anything.
544 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
545 // Only evict older cascades or live ranges without a cascade.
546 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
547 if (Cascade <= IntfCascade) {
548 if (!Urgent)
549 return false;
550 // We permit breaking cascades for urgent evictions. It should be the
551 // last resort, though, so make it really expensive.
552 Cost.BrokenHints += 10;
553 }
554 // Would this break a satisfied hint?
555 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
556 // Update eviction cost.
557 Cost.BrokenHints += BreaksHint;
558 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
559 // Abort if this would be too expensive.
560 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000561 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000562 // Finally, apply the eviction policy for non-urgent evictions.
563 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000564 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000565 }
566 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000567 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000568 return true;
569}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000570
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000571/// evictInterference - Evict any interferring registers that prevent VirtReg
572/// from being assigned to Physreg. This assumes that canEvictInterference
573/// returned true.
574void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
575 SmallVectorImpl<LiveInterval*> &NewVRegs) {
576 // Make sure that VirtReg has a cascade number, and assign that cascade
577 // number to every evicted register. These live ranges than then only be
578 // evicted by a newer cascade, preventing infinite loops.
579 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
580 if (!Cascade)
581 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
582
583 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
584 << " interference: Cascade " << Cascade << '\n');
585 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
586 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
587 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
588 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
589 LiveInterval *Intf = Q.interferingVRegs()[i];
590 unassign(*Intf, VRM->getPhys(Intf->reg));
591 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
592 VirtReg.isSpillable() < Intf->isSpillable()) &&
593 "Cannot decrease cascade number, illegal eviction");
594 ExtraRegInfo[Intf->reg].Cascade = Cascade;
595 ++NumEvicted;
596 NewVRegs.push_back(Intf);
597 }
598 }
599}
600
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000601/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000602/// @param VirtReg Currently unassigned virtual register.
603/// @param Order Physregs to try.
604/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000605unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
606 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000607 SmallVectorImpl<LiveInterval*> &NewVRegs,
608 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000609 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
610
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000611 // Keep track of the cheapest interference seen so far.
612 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000613 unsigned BestPhys = 0;
614
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000615 // When we are just looking for a reduced cost per use, don't break any
616 // hints, and only evict smaller spill weights.
617 if (CostPerUseLimit < ~0u) {
618 BestCost.BrokenHints = 0;
619 BestCost.MaxWeight = VirtReg.weight;
620 }
621
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000622 Order.rewind();
623 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000624 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
625 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000626 // The first use of a callee-saved register in a function has cost 1.
627 // Don't start using a CSR when the CostPerUseLimit is low.
628 if (CostPerUseLimit == 1)
629 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
630 if (!MRI->isPhysRegUsed(CSR)) {
631 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
632 << PrintReg(CSR, TRI) << '\n');
633 continue;
634 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000635
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000636 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000637 continue;
638
639 // Best so far.
640 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000641
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000642 // Stop if the hint can be used.
643 if (Order.isHint(PhysReg))
644 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000645 }
646
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000647 if (!BestPhys)
648 return 0;
649
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000650 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000651 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000652}
653
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000654
655//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000656// Region Splitting
657//===----------------------------------------------------------------------===//
658
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000659/// addSplitConstraints - Fill out the SplitConstraints vector based on the
660/// interference pattern in Physreg and its aliases. Add the constraints to
661/// SpillPlacement and return the static cost of this split in Cost, assuming
662/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000663/// Return false if there are no bundles with positive bias.
664bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
665 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000666 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000667
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000668 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000669 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000670 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000671 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
672 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000673 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000674
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000675 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000676 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000677 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
678 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000679 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000680
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000681 if (!Intf.hasInterference())
682 continue;
683
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000684 // Number of spill code instructions to insert.
685 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000686
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000687 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000688 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000689 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000690 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000691 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000692 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000693 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000694 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000695 }
696
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000697 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000698 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000699 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000700 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000701 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000702 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000703 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000704 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000705 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000706
707 // Accumulate the total frequency of inserted spill code.
708 if (Ins)
709 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000710 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000711 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000712
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000713 // Add constraints for use-blocks. Note that these are the only constraints
714 // that may add a positive bias, it is downhill from here.
715 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000716 return SpillPlacer->scanActiveBundles();
717}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000718
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000719
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000720/// addThroughConstraints - Add constraints and links to SpillPlacer from the
721/// live-through blocks in Blocks.
722void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
723 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000724 const unsigned GroupSize = 8;
725 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000726 unsigned TBS[GroupSize];
727 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000728
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000729 for (unsigned i = 0; i != Blocks.size(); ++i) {
730 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000731 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000732
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000733 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000734 assert(T < GroupSize && "Array overflow");
735 TBS[T] = Number;
736 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000737 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000738 T = 0;
739 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000740 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000741 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000742
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000743 assert(B < GroupSize && "Array overflow");
744 BCS[B].Number = Number;
745
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000746 // Interference for the live-in value.
747 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
748 BCS[B].Entry = SpillPlacement::MustSpill;
749 else
750 BCS[B].Entry = SpillPlacement::PrefSpill;
751
752 // Interference for the live-out value.
753 if (Intf.last() >= SA->getLastSplitPoint(Number))
754 BCS[B].Exit = SpillPlacement::MustSpill;
755 else
756 BCS[B].Exit = SpillPlacement::PrefSpill;
757
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000758 if (++B == GroupSize) {
759 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
760 SpillPlacer->addConstraints(Array);
761 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000762 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000763 }
764
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000765 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
766 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000767 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000768}
769
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000770void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000771 // Keep track of through blocks that have not been added to SpillPlacer.
772 BitVector Todo = SA->getThroughBlocks();
773 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
774 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000775#ifndef NDEBUG
776 unsigned Visited = 0;
777#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000778
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000779 for (;;) {
780 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000781 // Find new through blocks in the periphery of PrefRegBundles.
782 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
783 unsigned Bundle = NewBundles[i];
784 // Look at all blocks connected to Bundle in the full graph.
785 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
786 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
787 I != E; ++I) {
788 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000789 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000790 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000791 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000792 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000793 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000794#ifndef NDEBUG
795 ++Visited;
796#endif
797 }
798 }
799 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000800 if (ActiveBlocks.size() == AddedTo)
801 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000802
803 // Compute through constraints from the interference, or assume that all
804 // through blocks prefer spilling when forming compact regions.
805 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
806 if (Cand.PhysReg)
807 addThroughConstraints(Cand.Intf, NewBlocks);
808 else
809 SpillPlacer->addPrefSpill(NewBlocks);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000810 AddedTo = ActiveBlocks.size();
811
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000812 // Perhaps iterating can enable more bundles?
813 SpillPlacer->iterate();
814 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000815 DEBUG(dbgs() << ", v=" << Visited);
816}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000817
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000818/// calcCompactRegion - Compute the set of edge bundles that should be live
819/// when splitting the current live range into compact regions. Compact
820/// regions can be computed without looking at interference. They are the
821/// regions formed by removing all the live-through blocks from the live range.
822///
823/// Returns false if the current live range is already compact, or if the
824/// compact regions would form single block regions anyway.
825bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
826 // Without any through blocks, the live range is already compact.
827 if (!SA->getNumThroughBlocks())
828 return false;
829
830 // Compact regions don't correspond to any physreg.
831 Cand.reset(IntfCache, 0);
832
833 DEBUG(dbgs() << "Compact region bundles");
834
835 // Use the spill placer to determine the live bundles. GrowRegion pretends
836 // that all the through blocks have interference when PhysReg is unset.
837 SpillPlacer->prepare(Cand.LiveBundles);
838
839 // The static split cost will be zero since Cand.Intf reports no interference.
840 float Cost;
841 if (!addSplitConstraints(Cand.Intf, Cost)) {
842 DEBUG(dbgs() << ", none.\n");
843 return false;
844 }
845
846 growRegion(Cand);
847 SpillPlacer->finish();
848
849 if (!Cand.LiveBundles.any()) {
850 DEBUG(dbgs() << ", none.\n");
851 return false;
852 }
853
854 DEBUG({
855 for (int i = Cand.LiveBundles.find_first(); i>=0;
856 i = Cand.LiveBundles.find_next(i))
857 dbgs() << " EB#" << i;
858 dbgs() << ".\n";
859 });
860 return true;
861}
862
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000863/// calcSpillCost - Compute how expensive it would be to split the live range in
864/// SA around all use blocks instead of forming bundle regions.
865float RAGreedy::calcSpillCost() {
866 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000867 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
868 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
869 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
870 unsigned Number = BI.MBB->getNumber();
871 // We normally only need one spill instruction - a load or a store.
872 Cost += SpillPlacer->getBlockFrequency(Number);
873
874 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000875 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
876 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000877 }
878 return Cost;
879}
880
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000881/// calcGlobalSplitCost - Return the global split cost of following the split
882/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000883/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000884///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000885float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000886 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000887 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000888 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
889 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
890 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000891 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000892 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
893 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
894 unsigned Ins = 0;
895
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000896 if (BI.LiveIn)
897 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
898 if (BI.LiveOut)
899 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000900 if (Ins)
901 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000902 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000903
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000904 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
905 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000906 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
907 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000908 if (!RegIn && !RegOut)
909 continue;
910 if (RegIn && RegOut) {
911 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000912 Cand.Intf.moveToBlock(Number);
913 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000914 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
915 continue;
916 }
917 // live-in / stack-out or stack-in live-out.
918 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000919 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000920 return GlobalCost;
921}
922
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000923/// splitAroundRegion - Split the current live range around the regions
924/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000925///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000926/// Before calling this function, GlobalCand and BundleCand must be initialized
927/// so each bundle is assigned to a valid candidate, or NoCand for the
928/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
929/// objects must be initialized for the current live range, and intervals
930/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000931///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000932/// @param LREdit The LiveRangeEdit object handling the current split.
933/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
934/// must appear in this list.
935void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
936 ArrayRef<unsigned> UsedCands) {
937 // These are the intervals created for new global ranges. We may create more
938 // intervals for local ranges.
939 const unsigned NumGlobalIntvs = LREdit.size();
940 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
941 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000942
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000943 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000944 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
945 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
946 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000947 unsigned Number = BI.MBB->getNumber();
948 unsigned IntvIn = 0, IntvOut = 0;
949 SlotIndex IntfIn, IntfOut;
950 if (BI.LiveIn) {
951 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
952 if (CandIn != NoCand) {
953 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
954 IntvIn = Cand.IntvIdx;
955 Cand.Intf.moveToBlock(Number);
956 IntfIn = Cand.Intf.first();
957 }
958 }
959 if (BI.LiveOut) {
960 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
961 if (CandOut != NoCand) {
962 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
963 IntvOut = Cand.IntvIdx;
964 Cand.Intf.moveToBlock(Number);
965 IntfOut = Cand.Intf.last();
966 }
967 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000968
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000969 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000970 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000971 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000972 if (!BI.isOneInstr())
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000973 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000974 continue;
975 }
976
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000977 if (IntvIn && IntvOut)
978 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
979 else if (IntvIn)
980 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +0000981 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000982 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000983 }
984
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000985 // Handle live-through blocks. The relevant live-through blocks are stored in
986 // the ActiveBlocks list with each candidate. We need to filter out
987 // duplicates.
988 BitVector Todo = SA->getThroughBlocks();
989 for (unsigned c = 0; c != UsedCands.size(); ++c) {
990 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
991 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
992 unsigned Number = Blocks[i];
993 if (!Todo.test(Number))
994 continue;
995 Todo.reset(Number);
996
997 unsigned IntvIn = 0, IntvOut = 0;
998 SlotIndex IntfIn, IntfOut;
999
1000 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1001 if (CandIn != NoCand) {
1002 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1003 IntvIn = Cand.IntvIdx;
1004 Cand.Intf.moveToBlock(Number);
1005 IntfIn = Cand.Intf.first();
1006 }
1007
1008 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1009 if (CandOut != NoCand) {
1010 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1011 IntvOut = Cand.IntvIdx;
1012 Cand.Intf.moveToBlock(Number);
1013 IntfOut = Cand.Intf.last();
1014 }
1015 if (!IntvIn && !IntvOut)
1016 continue;
1017 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1018 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001019 }
1020
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001021 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001022
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001023 SmallVector<unsigned, 8> IntvMap;
1024 SE->finish(&IntvMap);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001025 DebugVars->splitRegister(SA->getParent().reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001026
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001027 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001028 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001029
1030 // Sort out the new intervals created by splitting. We get four kinds:
1031 // - Remainder intervals should not be split again.
1032 // - Candidate intervals can be assigned to Cand.PhysReg.
1033 // - Block-local splits are candidates for local splitting.
1034 // - DCE leftovers should go back on the queue.
1035 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001036 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001037
1038 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001039 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001040 continue;
1041
1042 // Remainder interval. Don't try splitting again, spill if it doesn't
1043 // allocate.
1044 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001045 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001046 continue;
1047 }
1048
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001049 // Global intervals. Allow repeated splitting as long as the number of live
1050 // blocks is strictly decreasing.
1051 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001052 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001053 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1054 << " blocks as original.\n");
1055 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001056 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001057 }
1058 continue;
1059 }
1060
1061 // Other intervals are treated as new. This includes local intervals created
1062 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001063 }
1064
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001065 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001066 MF->verify(this, "After splitting live range around region");
1067}
1068
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001069unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1070 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001071 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001072 unsigned BestCand = NoCand;
1073 float BestCost;
1074 SmallVector<unsigned, 8> UsedCands;
1075
1076 // Check if we can split this live range around a compact region.
1077 bool HasCompact = CompactRegions && calcCompactRegion(GlobalCand.front());
1078 if (HasCompact) {
1079 // Yes, keep GlobalCand[0] as the compact region candidate.
1080 NumCands = 1;
1081 BestCost = HUGE_VALF;
1082 } else {
1083 // No benefit from the compact region, our fallback will be per-block
1084 // splitting. Make sure we find a solution that is cheaper than spilling.
1085 BestCost = Hysteresis * calcSpillCost();
1086 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1087 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001088
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001089 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001090 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001091 // Discard bad candidates before we run out of interference cache cursors.
1092 // This will only affect register classes with a lot of registers (>32).
1093 if (NumCands == IntfCache.getMaxCursors()) {
1094 unsigned WorstCount = ~0u;
1095 unsigned Worst = 0;
1096 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001097 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001098 continue;
1099 unsigned Count = GlobalCand[i].LiveBundles.count();
1100 if (Count < WorstCount)
1101 Worst = i, WorstCount = Count;
1102 }
1103 --NumCands;
1104 GlobalCand[Worst] = GlobalCand[NumCands];
1105 }
1106
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001107 if (GlobalCand.size() <= NumCands)
1108 GlobalCand.resize(NumCands+1);
1109 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1110 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001111
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001112 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001113 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001114 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001115 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001116 continue;
1117 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001118 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001119 if (Cost >= BestCost) {
1120 DEBUG({
1121 if (BestCand == NoCand)
1122 dbgs() << " worse than no bundles\n";
1123 else
1124 dbgs() << " worse than "
1125 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1126 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001127 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001128 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001129 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001130
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001131 SpillPlacer->finish();
1132
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001133 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001134 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001135 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001136 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001137 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001138
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001139 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001140 DEBUG({
1141 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001142 for (int i = Cand.LiveBundles.find_first(); i>=0;
1143 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001144 dbgs() << " EB#" << i;
1145 dbgs() << ".\n";
1146 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001147 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001148 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001149 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001150 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001151 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001152 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001153
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001154 // No solutions found, fall back to single block splitting.
1155 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001156 return 0;
1157
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001158 // Prepare split editor.
1159 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1160 SE->reset(LREdit);
1161
1162 // Assign all edge bundles to the preferred candidate, or NoCand.
1163 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1164
1165 // Assign bundles for the best candidate region.
1166 if (BestCand != NoCand) {
1167 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1168 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1169 UsedCands.push_back(BestCand);
1170 Cand.IntvIdx = SE->openIntv();
1171 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1172 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001173 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001174 }
1175 }
1176
1177 // Assign bundles for the compact region.
1178 if (HasCompact) {
1179 GlobalSplitCandidate &Cand = GlobalCand.front();
1180 assert(!Cand.PhysReg && "Compact region has no physreg");
1181 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1182 UsedCands.push_back(0);
1183 Cand.IntvIdx = SE->openIntv();
1184 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1185 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001186 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001187 }
1188 }
1189
1190 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001191 return 0;
1192}
1193
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001194
1195//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001196// Local Splitting
1197//===----------------------------------------------------------------------===//
1198
1199
1200/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1201/// in order to use PhysReg between two entries in SA->UseSlots.
1202///
1203/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1204///
1205void RAGreedy::calcGapWeights(unsigned PhysReg,
1206 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001207 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1208 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001209 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1210 const unsigned NumGaps = Uses.size()-1;
1211
1212 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001213 SlotIndex StartIdx =
1214 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1215 SlotIndex StopIdx =
1216 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001217
1218 GapWeight.assign(NumGaps, 0.0f);
1219
1220 // Add interference from each overlapping register.
1221 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1222 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1223 .checkInterference())
1224 continue;
1225
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001226 // We know that VirtReg is a continuous interval from FirstInstr to
1227 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001228 //
1229 // Interference that overlaps an instruction is counted in both gaps
1230 // surrounding the instruction. The exception is interference before
1231 // StartIdx and after StopIdx.
1232 //
1233 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1234 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1235 // Skip the gaps before IntI.
1236 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1237 if (++Gap == NumGaps)
1238 break;
1239 if (Gap == NumGaps)
1240 break;
1241
1242 // Update the gaps covered by IntI.
1243 const float weight = IntI.value()->weight;
1244 for (; Gap != NumGaps; ++Gap) {
1245 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1246 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1247 break;
1248 }
1249 if (Gap == NumGaps)
1250 break;
1251 }
1252 }
1253}
1254
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001255/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1256/// basic block.
1257///
1258unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1259 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001260 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1261 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001262
1263 // Note that it is possible to have an interval that is live-in or live-out
1264 // while only covering a single block - A phi-def can use undef values from
1265 // predecessors, and the block could be a single-block loop.
1266 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001267 // that the interval is continuous from FirstInstr to LastInstr. We should
1268 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001269
1270 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1271 if (Uses.size() <= 2)
1272 return 0;
1273 const unsigned NumGaps = Uses.size()-1;
1274
1275 DEBUG({
1276 dbgs() << "tryLocalSplit: ";
1277 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1278 dbgs() << ' ' << SA->UseSlots[i];
1279 dbgs() << '\n';
1280 });
1281
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001282 // Since we allow local split results to be split again, there is a risk of
1283 // creating infinite loops. It is tempting to require that the new live
1284 // ranges have less instructions than the original. That would guarantee
1285 // convergence, but it is too strict. A live range with 3 instructions can be
1286 // split 2+3 (including the COPY), and we want to allow that.
1287 //
1288 // Instead we use these rules:
1289 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001290 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001291 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001292 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001293 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001294 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001295 // smaller ranges are marked RS_New.
1296 //
1297 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1298 // excessive splitting and infinite loops.
1299 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001300 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001301
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001302 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001303 unsigned BestBefore = NumGaps;
1304 unsigned BestAfter = 0;
1305 float BestDiff = 0;
1306
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001307 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001308 SmallVector<float, 8> GapWeight;
1309
1310 Order.rewind();
1311 while (unsigned PhysReg = Order.next()) {
1312 // Keep track of the largest spill weight that would need to be evicted in
1313 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1314 calcGapWeights(PhysReg, GapWeight);
1315
1316 // Try to find the best sequence of gaps to close.
1317 // The new spill weight must be larger than any gap interference.
1318
1319 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001320 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001321
1322 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1323 // It is the spill weight that needs to be evicted.
1324 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001325
1326 for (;;) {
1327 // Live before/after split?
1328 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1329 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1330
1331 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1332 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1333 << " i=" << MaxGap);
1334
1335 // Stop before the interval gets so big we wouldn't be making progress.
1336 if (!LiveBefore && !LiveAfter) {
1337 DEBUG(dbgs() << " all\n");
1338 break;
1339 }
1340 // Should the interval be extended or shrunk?
1341 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001342
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001343 // How many gaps would the new range have?
1344 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1345
1346 // Legally, without causing looping?
1347 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1348
1349 if (Legal && MaxGap < HUGE_VALF) {
1350 // Estimate the new spill weight. Each instruction reads or writes the
1351 // register. Conservatively assume there are no read-modify-write
1352 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001353 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001354 // Try to guess the size of the new interval.
1355 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1356 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1357 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001358 // Would this split be possible to allocate?
1359 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001360 DEBUG(dbgs() << " w=" << EstWeight);
1361 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001362 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001363 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001364 if (Diff > BestDiff) {
1365 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001366 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001367 BestBefore = SplitBefore;
1368 BestAfter = SplitAfter;
1369 }
1370 }
1371 }
1372
1373 // Try to shrink.
1374 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001375 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001376 DEBUG(dbgs() << " shrink\n");
1377 // Recompute the max when necessary.
1378 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1379 MaxGap = GapWeight[SplitBefore];
1380 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1381 MaxGap = std::max(MaxGap, GapWeight[i]);
1382 }
1383 continue;
1384 }
1385 MaxGap = 0;
1386 }
1387
1388 // Try to extend the interval.
1389 if (SplitAfter >= NumGaps) {
1390 DEBUG(dbgs() << " end\n");
1391 break;
1392 }
1393
1394 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001395 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001396 }
1397 }
1398
1399 // Didn't find any candidates?
1400 if (BestBefore == NumGaps)
1401 return 0;
1402
1403 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1404 << '-' << Uses[BestAfter] << ", " << BestDiff
1405 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1406
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001407 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001408 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001409
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001410 SE->openIntv();
1411 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1412 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1413 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001414 SmallVector<unsigned, 8> IntvMap;
1415 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001416 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001417
1418 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001419 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001420 // leave the new intervals as RS_New so they can compete.
1421 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1422 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1423 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1424 if (NewGaps >= NumGaps) {
1425 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1426 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001427 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1428 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001429 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001430 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1431 }
1432 DEBUG(dbgs() << '\n');
1433 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001434 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001435
1436 return 0;
1437}
1438
1439//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001440// Live Range Splitting
1441//===----------------------------------------------------------------------===//
1442
1443/// trySplit - Try to split VirtReg or one of its interferences, making it
1444/// assignable.
1445/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1446unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1447 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001448 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001449 if (LIS->intervalIsInOneMBB(VirtReg)) {
1450 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001451 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001452 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001453 }
1454
1455 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001456
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001457 // Ranges must be Split2 or less.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001458 if (getStage(VirtReg) >= RS_Spill)
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001459 return 0;
1460
1461 SA->analyze(&VirtReg);
1462
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001463 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1464 // coalescer. That may cause the range to become allocatable which means that
1465 // tryRegionSplit won't be making progress. This check should be replaced with
1466 // an assertion when the coalescer is fixed.
1467 if (SA->didRepairRange()) {
1468 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001469 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001470 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1471 return PhysReg;
1472 }
1473
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001474 // First try to split around a region spanning multiple blocks. RS_Split2
1475 // ranges already made dubious progress with region splitting, so they go
1476 // straight to single block splitting.
1477 if (getStage(VirtReg) < RS_Split2) {
1478 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1479 if (PhysReg || !NewVRegs.empty())
1480 return PhysReg;
1481 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001482
1483 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001484 SplitAnalysis::BlockPtrSet Blocks;
1485 if (SA->getMultiUseBlocks(Blocks)) {
1486 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1487 SE->reset(LREdit);
1488 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001489 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001490 if (VerifyEnabled)
1491 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001492 }
1493
1494 // Don't assign any physregs.
1495 return 0;
1496}
1497
1498
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001499//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001500// Main Entry Point
1501//===----------------------------------------------------------------------===//
1502
1503unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001504 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001505 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001506 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001507 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1508 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001509
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001510 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001511 DEBUG(dbgs() << StageName[Stage]
1512 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001513
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001514 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001515 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001516 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001517 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001518 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1519 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001520
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001521 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1522
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001523 // The first time we see a live range, don't try to split or spill.
1524 // Wait until the second time, when all smaller ranges have been allocated.
1525 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001526 if (Stage < RS_Split) {
1527 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001528 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001529 NewVRegs.push_back(&VirtReg);
1530 return 0;
1531 }
1532
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001533 // If we couldn't allocate a register from spilling, there is probably some
1534 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001535 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001536 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001537
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001538 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001539 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1540 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001541 return PhysReg;
1542
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001543 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001544 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001545 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1546 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001547 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001548
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001549 if (VerifyEnabled)
1550 MF->verify(this, "After spilling");
1551
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001552 // The live virtual register requesting allocation was spilled, so tell
1553 // the caller not to allocate anything during this round.
1554 return 0;
1555}
1556
1557bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1558 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1559 << "********** Function: "
1560 << ((Value*)mf.getFunction())->getName() << '\n');
1561
1562 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001563 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001564 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001565
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001566 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001567 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001568 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001569 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001570 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001571 Bundles = &getAnalysis<EdgeBundles>();
1572 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001573 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001574
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001575 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001576 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001577 ExtraRegInfo.clear();
1578 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1579 NextCascade = 1;
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +00001580 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001581 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001582
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001583 allocatePhysRegs();
1584 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001585 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001586
1587 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001588 {
1589 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001590 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001591 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001592
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001593 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenc4769022011-07-31 03:53:42 +00001594 {
1595 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1596 DebugVars->emitDebugValues(VRM);
1597 }
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001598
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001599 // The pass output is in VirtRegMap. Release all the transient data.
1600 releaseMemory();
1601
1602 return true;
1603}