blob: f4f1bf2bf02a0eec32e095c800343f14ff23e91e [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 Olesencba2e062010-12-08 03:26:16 +000019#include "RegAllocBase.h"
20#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000022#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000023#include "VirtRegMap.h"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
26#include "llvm/Function.h"
27#include "llvm/PassAnalysisSupport.h"
28#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000029#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000030#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000031#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000032#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000033#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineLoopInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/Passes.h"
38#include "llvm/CodeGen/RegAllocRegistry.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000039#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000040#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000045
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000052STATISTIC(NumEvicted, "Number of interferences evicted");
53
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000054static cl::opt<SplitEditor::ComplementSpillMode>
55SplitSpillMode("split-spill-mode", cl::Hidden,
56 cl::desc("Spill mode for splitting live ranges"),
57 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
58 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
59 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
60 clEnumValEnd),
61 cl::init(SplitEditor::SM_Partition));
62
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000063static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
64 createGreedyRegisterAllocator);
65
66namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000067class RAGreedy : public MachineFunctionPass,
68 public RegAllocBase,
69 private LiveRangeEdit::Delegate {
70
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000071 // context
72 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000073
74 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000075 SlotIndexes *Indexes;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000076 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000077 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000078 EdgeBundles *Bundles;
79 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000080 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000081
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000082 // state
83 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000084 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000085 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000086
87 // Live ranges pass through a number of stages as we try to allocate them.
88 // Some of the stages may also create new live ranges:
89 //
90 // - Region splitting.
91 // - Per-block splitting.
92 // - Local splitting.
93 // - Spilling.
94 //
95 // Ranges produced by one of the stages skip the previous stages when they are
96 // dequeued. This improves performance because we can skip interference checks
97 // that are unlikely to give any results. It also guarantees that the live
98 // range splitting algorithm terminates, something that is otherwise hard to
99 // ensure.
100 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000101 /// Newly created live range that has never been queued.
102 RS_New,
103
104 /// Only attempt assignment and eviction. Then requeue as RS_Split.
105 RS_Assign,
106
107 /// Attempt live range splitting if assignment is impossible.
108 RS_Split,
109
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000110 /// Attempt more aggressive live range splitting that is guaranteed to make
111 /// progress. This is used for split products that may not be making
112 /// progress.
113 RS_Split2,
114
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000115 /// Live range will be spilled. No more splitting will be attempted.
116 RS_Spill,
117
118 /// There is nothing more we can do to this live range. Abort compilation
119 /// if it can't be assigned.
120 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000121 };
122
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000123 static const char *const StageName[];
124
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000125 // RegInfo - Keep additional information about each live range.
126 struct RegInfo {
127 LiveRangeStage Stage;
128
129 // Cascade - Eviction loop prevention. See canEvictInterference().
130 unsigned Cascade;
131
132 RegInfo() : Stage(RS_New), Cascade(0) {}
133 };
134
135 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000136
137 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000138 return ExtraRegInfo[VirtReg.reg].Stage;
139 }
140
141 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
142 ExtraRegInfo.resize(MRI->getNumVirtRegs());
143 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000144 }
145
146 template<typename Iterator>
147 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000148 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000149 for (;Begin != End; ++Begin) {
150 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000151 if (ExtraRegInfo[Reg].Stage == RS_New)
152 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000153 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000154 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000155
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000156 /// Cost of evicting interference.
157 struct EvictionCost {
158 unsigned BrokenHints; ///< Total number of broken hints.
159 float MaxWeight; ///< Maximum spill weight evicted.
160
161 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
162
163 bool operator<(const EvictionCost &O) const {
164 if (BrokenHints != O.BrokenHints)
165 return BrokenHints < O.BrokenHints;
166 return MaxWeight < O.MaxWeight;
167 }
168 };
169
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000170 // Register mask interference. The current VirtReg is checked for register
171 // mask interference on entry to selectOrSplit(). If there is no
172 // interference, UsableRegs is left empty. If there is interference,
173 // UsableRegs has a bit mask of registers that can be used without register
174 // mask interference.
175 BitVector UsableRegs;
176
177 /// clobberedByRegMask - Returns true if PhysReg is not directly usable
178 /// because of register mask clobbers.
179 bool clobberedByRegMask(unsigned PhysReg) const {
180 return !UsableRegs.empty() && !UsableRegs.test(PhysReg);
181 }
182
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000183 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000184 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000185 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000186
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000187 /// Cached per-block interference maps
188 InterferenceCache IntfCache;
189
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000190 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000191 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000192
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000193 /// Global live range splitting candidate info.
194 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000195 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000196 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000197
198 // SplitKit interval index for this candidate.
199 unsigned IntvIdx;
200
201 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000202 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000203
204 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000205 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000206 SmallVector<unsigned, 8> ActiveBlocks;
207
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000208 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000209 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000210 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000211 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000212 LiveBundles.clear();
213 ActiveBlocks.clear();
214 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000215
216 // Set B[i] = C for every live bundle where B[i] was NoCand.
217 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
218 unsigned Count = 0;
219 for (int i = LiveBundles.find_first(); i >= 0;
220 i = LiveBundles.find_next(i))
221 if (B[i] == NoCand) {
222 B[i] = C;
223 Count++;
224 }
225 return Count;
226 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000227 };
228
229 /// Candidate info for for each PhysReg in AllocationOrder.
230 /// This vector never shrinks, but grows to the size of the largest register
231 /// class.
232 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
233
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000234 enum { NoCand = ~0u };
235
236 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
237 /// NoCand which indicates the stack interval.
238 SmallVector<unsigned, 32> BundleCand;
239
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000240public:
241 RAGreedy();
242
243 /// Return the pass name.
244 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000245 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000246 }
247
248 /// RAGreedy analysis usage.
249 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000250 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000251 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000252 virtual void enqueue(LiveInterval *LI);
253 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000254 virtual unsigned selectOrSplit(LiveInterval&,
255 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000256
257 /// Perform register allocation.
258 virtual bool runOnMachineFunction(MachineFunction &mf);
259
260 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000261
262private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000263 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000264 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000265 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000266
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000267 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000268 bool addSplitConstraints(InterferenceCache::Cursor, float&);
269 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000270 void growRegion(GlobalSplitCandidate &Cand);
271 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000272 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000273 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000274 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000275 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
276 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
277 void evictInterference(LiveInterval&, unsigned,
278 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000279
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000280 unsigned tryAssign(LiveInterval&, AllocationOrder&,
281 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000282 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000283 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000284 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
285 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000286 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
287 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000288 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
289 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000290 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
291 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000292 unsigned trySplit(LiveInterval&, AllocationOrder&,
293 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000294};
295} // end anonymous namespace
296
297char RAGreedy::ID = 0;
298
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000299#ifndef NDEBUG
300const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000301 "RS_New",
302 "RS_Assign",
303 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000304 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000305 "RS_Spill",
306 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000307};
308#endif
309
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000310// Hysteresis to use when comparing floats.
311// This helps stabilize decisions based on float comparisons.
312const float Hysteresis = 0.98f;
313
314
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000315FunctionPass* llvm::createGreedyRegisterAllocator() {
316 return new RAGreedy();
317}
318
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000319RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000320 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000321 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000322 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
323 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000324 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000325 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000326 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
327 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
328 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
329 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
330 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000331 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
332 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000333}
334
335void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
336 AU.setPreservesCFG();
337 AU.addRequired<AliasAnalysis>();
338 AU.addPreserved<AliasAnalysis>();
339 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000340 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000341 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000342 AU.addRequired<LiveDebugVariables>();
343 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000344 AU.addRequired<CalculateSpillWeights>();
345 AU.addRequired<LiveStacks>();
346 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000347 AU.addRequired<MachineDominatorTree>();
348 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000349 AU.addRequired<MachineLoopInfo>();
350 AU.addPreserved<MachineLoopInfo>();
351 AU.addRequired<VirtRegMap>();
352 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000353 AU.addRequired<EdgeBundles>();
354 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000355 MachineFunctionPass::getAnalysisUsage(AU);
356}
357
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000358
359//===----------------------------------------------------------------------===//
360// LiveRangeEdit delegate methods
361//===----------------------------------------------------------------------===//
362
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000363bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
364 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
365 unassign(LIS->getInterval(VirtReg), PhysReg);
366 return true;
367 }
368 // Unassigned virtreg is probably in the priority queue.
369 // RegAllocBase will erase it after dequeueing.
370 return false;
371}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000372
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000373void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
374 unsigned PhysReg = VRM->getPhys(VirtReg);
375 if (!PhysReg)
376 return;
377
378 // Register is assigned, put it back on the queue for reassignment.
379 LiveInterval &LI = LIS->getInterval(VirtReg);
380 unassign(LI, PhysReg);
381 enqueue(&LI);
382}
383
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000384void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000385 // Cloning a register we haven't even heard about yet? Just ignore it.
386 if (!ExtraRegInfo.inBounds(Old))
387 return;
388
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000389 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000390 // be split into connected components. The new components are much smaller
391 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000392 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000393 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000394 ExtraRegInfo.grow(New);
395 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000396}
397
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000398void RAGreedy::releaseMemory() {
399 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000400 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000401 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000402 RegAllocBase::releaseMemory();
403}
404
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000405void RAGreedy::enqueue(LiveInterval *LI) {
406 // Prioritize live ranges by size, assigning larger ranges first.
407 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000408 const unsigned Size = LI->getSize();
409 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000410 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
411 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000412 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000413
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000414 ExtraRegInfo.grow(Reg);
415 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000416 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000417
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000418 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000419 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000420 // everything else has been allocated.
421 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000422 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000423 // Everything is allocated in long->short order. Long ranges that don't fit
424 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000425 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000426
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000427 // Boost ranges that have a physical register hint.
428 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
429 Prio |= (1u << 30);
430 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000431
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000432 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000433}
434
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000435LiveInterval *RAGreedy::dequeue() {
436 if (Queue.empty())
437 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000438 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000439 Queue.pop();
440 return LI;
441}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000442
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000443
444//===----------------------------------------------------------------------===//
445// Direct Assignment
446//===----------------------------------------------------------------------===//
447
448/// tryAssign - Try to assign VirtReg to an available register.
449unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
450 AllocationOrder &Order,
451 SmallVectorImpl<LiveInterval*> &NewVRegs) {
452 Order.rewind();
453 unsigned PhysReg;
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000454 while ((PhysReg = Order.next())) {
455 if (clobberedByRegMask(PhysReg))
456 continue;
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000457 if (!checkPhysRegInterference(VirtReg, PhysReg))
458 break;
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000459 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000460 if (!PhysReg || Order.isHint(PhysReg))
461 return PhysReg;
462
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000463 // PhysReg is available, but there may be a better choice.
464
465 // If we missed a simple hint, try to cheaply evict interference from the
466 // preferred register.
467 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000468 if (Order.isHint(Hint) && !clobberedByRegMask(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000469 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
470 EvictionCost MaxCost(1);
471 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
472 evictInterference(VirtReg, Hint, NewVRegs);
473 return Hint;
474 }
475 }
476
477 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000478 unsigned Cost = TRI->getCostPerUse(PhysReg);
479
480 // Most registers have 0 additional cost.
481 if (!Cost)
482 return PhysReg;
483
484 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
485 << '\n');
486 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
487 return CheapReg ? CheapReg : PhysReg;
488}
489
490
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000491//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000492// Interference eviction
493//===----------------------------------------------------------------------===//
494
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000495/// shouldEvict - determine if A should evict the assigned live range B. The
496/// eviction policy defined by this function together with the allocation order
497/// defined by enqueue() decides which registers ultimately end up being split
498/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000499///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000500/// Cascade numbers are used to prevent infinite loops if this function is a
501/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000502///
503/// @param A The live range to be assigned.
504/// @param IsHint True when A is about to be assigned to its preferred
505/// register.
506/// @param B The live range to be evicted.
507/// @param BreaksHint True when B is already assigned to its preferred register.
508bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
509 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000510 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000511
512 // Be fairly aggressive about following hints as long as the evictee can be
513 // split.
514 if (CanSplit && IsHint && !BreaksHint)
515 return true;
516
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000517 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000518}
519
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000520/// canEvictInterference - Return true if all interferences between VirtReg and
521/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
522///
523/// @param VirtReg Live range that is about to be assigned.
524/// @param PhysReg Desired register for assignment.
525/// @prarm IsHint True when PhysReg is VirtReg's preferred register.
526/// @param MaxCost Only look for cheaper candidates and update with new cost
527/// when returning true.
528/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000529bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000530 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000531 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
532 // involved in an eviction before. If a cascade number was assigned, deny
533 // evicting anything with the same or a newer cascade number. This prevents
534 // infinite eviction loops.
535 //
536 // This works out so a register without a cascade number is allowed to evict
537 // anything, and it can be evicted by anything.
538 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
539 if (!Cascade)
540 Cascade = NextCascade;
541
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000542 EvictionCost Cost;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000543 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
544 LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000545 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000546 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000547 return false;
548
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000549 // Check if any interfering live range is heavier than MaxWeight.
550 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
551 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000552 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
553 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000554 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000555 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000556 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000557 // Once a live range becomes small enough, it is urgent that we find a
558 // register for it. This is indicated by an infinite spill weight. These
559 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000560 //
561 // Also allow urgent evictions of unspillable ranges from a strictly
562 // larger allocation order.
563 bool Urgent = !VirtReg.isSpillable() &&
564 (Intf->isSpillable() ||
565 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
566 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000567 // Only evict older cascades or live ranges without a cascade.
568 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
569 if (Cascade <= IntfCascade) {
570 if (!Urgent)
571 return false;
572 // We permit breaking cascades for urgent evictions. It should be the
573 // last resort, though, so make it really expensive.
574 Cost.BrokenHints += 10;
575 }
576 // Would this break a satisfied hint?
577 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
578 // Update eviction cost.
579 Cost.BrokenHints += BreaksHint;
580 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
581 // Abort if this would be too expensive.
582 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000583 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000584 // Finally, apply the eviction policy for non-urgent evictions.
585 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000586 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000587 }
588 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000589 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000590 return true;
591}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000592
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000593/// evictInterference - Evict any interferring registers that prevent VirtReg
594/// from being assigned to Physreg. This assumes that canEvictInterference
595/// returned true.
596void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
597 SmallVectorImpl<LiveInterval*> &NewVRegs) {
598 // Make sure that VirtReg has a cascade number, and assign that cascade
599 // number to every evicted register. These live ranges than then only be
600 // evicted by a newer cascade, preventing infinite loops.
601 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
602 if (!Cascade)
603 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
604
605 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
606 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000607 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
608 LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000609 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
610 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
611 LiveInterval *Intf = Q.interferingVRegs()[i];
612 unassign(*Intf, VRM->getPhys(Intf->reg));
613 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
614 VirtReg.isSpillable() < Intf->isSpillable()) &&
615 "Cannot decrease cascade number, illegal eviction");
616 ExtraRegInfo[Intf->reg].Cascade = Cascade;
617 ++NumEvicted;
618 NewVRegs.push_back(Intf);
619 }
620 }
621}
622
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000623/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000624/// @param VirtReg Currently unassigned virtual register.
625/// @param Order Physregs to try.
626/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000627unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
628 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000629 SmallVectorImpl<LiveInterval*> &NewVRegs,
630 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000631 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
632
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000633 // Keep track of the cheapest interference seen so far.
634 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000635 unsigned BestPhys = 0;
636
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000637 // When we are just looking for a reduced cost per use, don't break any
638 // hints, and only evict smaller spill weights.
639 if (CostPerUseLimit < ~0u) {
640 BestCost.BrokenHints = 0;
641 BestCost.MaxWeight = VirtReg.weight;
642 }
643
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000644 Order.rewind();
645 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +0000646 if (clobberedByRegMask(PhysReg))
647 continue;
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000648 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
649 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000650 // The first use of a callee-saved register in a function has cost 1.
651 // Don't start using a CSR when the CostPerUseLimit is low.
652 if (CostPerUseLimit == 1)
653 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
654 if (!MRI->isPhysRegUsed(CSR)) {
655 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
656 << PrintReg(CSR, TRI) << '\n');
657 continue;
658 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000659
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000660 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000661 continue;
662
663 // Best so far.
664 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000665
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000666 // Stop if the hint can be used.
667 if (Order.isHint(PhysReg))
668 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000669 }
670
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000671 if (!BestPhys)
672 return 0;
673
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000674 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000675 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000676}
677
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000678
679//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000680// Region Splitting
681//===----------------------------------------------------------------------===//
682
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000683/// addSplitConstraints - Fill out the SplitConstraints vector based on the
684/// interference pattern in Physreg and its aliases. Add the constraints to
685/// SpillPlacement and return the static cost of this split in Cost, assuming
686/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000687/// Return false if there are no bundles with positive bias.
688bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
689 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000690 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000691
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000692 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000693 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000694 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000695 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
696 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000697 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000698
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000699 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000700 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000701 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
702 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000703 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000704
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000705 if (!Intf.hasInterference())
706 continue;
707
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000708 // Number of spill code instructions to insert.
709 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000710
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000711 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000712 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000713 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000714 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000715 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000716 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000717 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000718 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000719 }
720
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000721 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000722 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000723 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000724 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000725 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000726 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000727 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000728 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000729 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000730
731 // Accumulate the total frequency of inserted spill code.
732 if (Ins)
733 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000734 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000735 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000736
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000737 // Add constraints for use-blocks. Note that these are the only constraints
738 // that may add a positive bias, it is downhill from here.
739 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000740 return SpillPlacer->scanActiveBundles();
741}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000742
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000743
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000744/// addThroughConstraints - Add constraints and links to SpillPlacer from the
745/// live-through blocks in Blocks.
746void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
747 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000748 const unsigned GroupSize = 8;
749 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000750 unsigned TBS[GroupSize];
751 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000752
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000753 for (unsigned i = 0; i != Blocks.size(); ++i) {
754 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000755 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000756
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000757 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000758 assert(T < GroupSize && "Array overflow");
759 TBS[T] = Number;
760 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000761 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000762 T = 0;
763 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000764 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000765 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000766
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000767 assert(B < GroupSize && "Array overflow");
768 BCS[B].Number = Number;
769
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000770 // Interference for the live-in value.
771 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
772 BCS[B].Entry = SpillPlacement::MustSpill;
773 else
774 BCS[B].Entry = SpillPlacement::PrefSpill;
775
776 // Interference for the live-out value.
777 if (Intf.last() >= SA->getLastSplitPoint(Number))
778 BCS[B].Exit = SpillPlacement::MustSpill;
779 else
780 BCS[B].Exit = SpillPlacement::PrefSpill;
781
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000782 if (++B == GroupSize) {
783 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
784 SpillPlacer->addConstraints(Array);
785 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000786 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000787 }
788
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000789 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
790 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000791 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000792}
793
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000794void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000795 // Keep track of through blocks that have not been added to SpillPlacer.
796 BitVector Todo = SA->getThroughBlocks();
797 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
798 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000799#ifndef NDEBUG
800 unsigned Visited = 0;
801#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000802
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000803 for (;;) {
804 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000805 // Find new through blocks in the periphery of PrefRegBundles.
806 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
807 unsigned Bundle = NewBundles[i];
808 // Look at all blocks connected to Bundle in the full graph.
809 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
810 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
811 I != E; ++I) {
812 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000813 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000814 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000815 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000816 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000817 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000818#ifndef NDEBUG
819 ++Visited;
820#endif
821 }
822 }
823 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000824 if (ActiveBlocks.size() == AddedTo)
825 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000826
827 // Compute through constraints from the interference, or assume that all
828 // through blocks prefer spilling when forming compact regions.
829 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
830 if (Cand.PhysReg)
831 addThroughConstraints(Cand.Intf, NewBlocks);
832 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000833 // Provide a strong negative bias on through blocks to prevent unwanted
834 // liveness on loop backedges.
835 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000836 AddedTo = ActiveBlocks.size();
837
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000838 // Perhaps iterating can enable more bundles?
839 SpillPlacer->iterate();
840 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000841 DEBUG(dbgs() << ", v=" << Visited);
842}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000843
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000844/// calcCompactRegion - Compute the set of edge bundles that should be live
845/// when splitting the current live range into compact regions. Compact
846/// regions can be computed without looking at interference. They are the
847/// regions formed by removing all the live-through blocks from the live range.
848///
849/// Returns false if the current live range is already compact, or if the
850/// compact regions would form single block regions anyway.
851bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
852 // Without any through blocks, the live range is already compact.
853 if (!SA->getNumThroughBlocks())
854 return false;
855
856 // Compact regions don't correspond to any physreg.
857 Cand.reset(IntfCache, 0);
858
859 DEBUG(dbgs() << "Compact region bundles");
860
861 // Use the spill placer to determine the live bundles. GrowRegion pretends
862 // that all the through blocks have interference when PhysReg is unset.
863 SpillPlacer->prepare(Cand.LiveBundles);
864
865 // The static split cost will be zero since Cand.Intf reports no interference.
866 float Cost;
867 if (!addSplitConstraints(Cand.Intf, Cost)) {
868 DEBUG(dbgs() << ", none.\n");
869 return false;
870 }
871
872 growRegion(Cand);
873 SpillPlacer->finish();
874
875 if (!Cand.LiveBundles.any()) {
876 DEBUG(dbgs() << ", none.\n");
877 return false;
878 }
879
880 DEBUG({
881 for (int i = Cand.LiveBundles.find_first(); i>=0;
882 i = Cand.LiveBundles.find_next(i))
883 dbgs() << " EB#" << i;
884 dbgs() << ".\n";
885 });
886 return true;
887}
888
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000889/// calcSpillCost - Compute how expensive it would be to split the live range in
890/// SA around all use blocks instead of forming bundle regions.
891float RAGreedy::calcSpillCost() {
892 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000893 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
894 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
895 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
896 unsigned Number = BI.MBB->getNumber();
897 // We normally only need one spill instruction - a load or a store.
898 Cost += SpillPlacer->getBlockFrequency(Number);
899
900 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000901 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
902 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000903 }
904 return Cost;
905}
906
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000907/// calcGlobalSplitCost - Return the global split cost of following the split
908/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000909/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000910///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000911float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000912 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000913 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000914 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
915 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
916 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000917 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000918 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
919 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
920 unsigned Ins = 0;
921
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000922 if (BI.LiveIn)
923 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
924 if (BI.LiveOut)
925 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000926 if (Ins)
927 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000928 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000929
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000930 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
931 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000932 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
933 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000934 if (!RegIn && !RegOut)
935 continue;
936 if (RegIn && RegOut) {
937 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000938 Cand.Intf.moveToBlock(Number);
939 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000940 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
941 continue;
942 }
943 // live-in / stack-out or stack-in live-out.
944 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000945 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000946 return GlobalCost;
947}
948
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000949/// splitAroundRegion - Split the current live range around the regions
950/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000951///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000952/// Before calling this function, GlobalCand and BundleCand must be initialized
953/// so each bundle is assigned to a valid candidate, or NoCand for the
954/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
955/// objects must be initialized for the current live range, and intervals
956/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000957///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000958/// @param LREdit The LiveRangeEdit object handling the current split.
959/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
960/// must appear in this list.
961void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
962 ArrayRef<unsigned> UsedCands) {
963 // These are the intervals created for new global ranges. We may create more
964 // intervals for local ranges.
965 const unsigned NumGlobalIntvs = LREdit.size();
966 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
967 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000968
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000969 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000970 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000971 // is all copies.
972 unsigned Reg = SA->getParent().reg;
973 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
974
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000975 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000976 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
977 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
978 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000979 unsigned Number = BI.MBB->getNumber();
980 unsigned IntvIn = 0, IntvOut = 0;
981 SlotIndex IntfIn, IntfOut;
982 if (BI.LiveIn) {
983 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
984 if (CandIn != NoCand) {
985 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
986 IntvIn = Cand.IntvIdx;
987 Cand.Intf.moveToBlock(Number);
988 IntfIn = Cand.Intf.first();
989 }
990 }
991 if (BI.LiveOut) {
992 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
993 if (CandOut != NoCand) {
994 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
995 IntvOut = Cand.IntvIdx;
996 Cand.Intf.moveToBlock(Number);
997 IntfOut = Cand.Intf.last();
998 }
999 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001000
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001001 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001002 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001003 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001004 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001005 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001006 continue;
1007 }
1008
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001009 if (IntvIn && IntvOut)
1010 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1011 else if (IntvIn)
1012 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001013 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001014 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001015 }
1016
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001017 // Handle live-through blocks. The relevant live-through blocks are stored in
1018 // the ActiveBlocks list with each candidate. We need to filter out
1019 // duplicates.
1020 BitVector Todo = SA->getThroughBlocks();
1021 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1022 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1023 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1024 unsigned Number = Blocks[i];
1025 if (!Todo.test(Number))
1026 continue;
1027 Todo.reset(Number);
1028
1029 unsigned IntvIn = 0, IntvOut = 0;
1030 SlotIndex IntfIn, IntfOut;
1031
1032 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1033 if (CandIn != NoCand) {
1034 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1035 IntvIn = Cand.IntvIdx;
1036 Cand.Intf.moveToBlock(Number);
1037 IntfIn = Cand.Intf.first();
1038 }
1039
1040 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1041 if (CandOut != NoCand) {
1042 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1043 IntvOut = Cand.IntvIdx;
1044 Cand.Intf.moveToBlock(Number);
1045 IntfOut = Cand.Intf.last();
1046 }
1047 if (!IntvIn && !IntvOut)
1048 continue;
1049 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1050 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001051 }
1052
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001053 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001054
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001055 SmallVector<unsigned, 8> IntvMap;
1056 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001057 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001058
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001059 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001060 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001061
1062 // Sort out the new intervals created by splitting. We get four kinds:
1063 // - Remainder intervals should not be split again.
1064 // - Candidate intervals can be assigned to Cand.PhysReg.
1065 // - Block-local splits are candidates for local splitting.
1066 // - DCE leftovers should go back on the queue.
1067 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001068 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001069
1070 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001071 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001072 continue;
1073
1074 // Remainder interval. Don't try splitting again, spill if it doesn't
1075 // allocate.
1076 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001077 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001078 continue;
1079 }
1080
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001081 // Global intervals. Allow repeated splitting as long as the number of live
1082 // blocks is strictly decreasing.
1083 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001084 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001085 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1086 << " blocks as original.\n");
1087 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001088 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001089 }
1090 continue;
1091 }
1092
1093 // Other intervals are treated as new. This includes local intervals created
1094 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001095 }
1096
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001097 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001098 MF->verify(this, "After splitting live range around region");
1099}
1100
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001101unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1102 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001103 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001104 unsigned BestCand = NoCand;
1105 float BestCost;
1106 SmallVector<unsigned, 8> UsedCands;
1107
1108 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001109 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001110 if (HasCompact) {
1111 // Yes, keep GlobalCand[0] as the compact region candidate.
1112 NumCands = 1;
1113 BestCost = HUGE_VALF;
1114 } else {
1115 // No benefit from the compact region, our fallback will be per-block
1116 // splitting. Make sure we find a solution that is cheaper than spilling.
1117 BestCost = Hysteresis * calcSpillCost();
1118 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1119 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001120
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001121 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001122 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001123 // Discard bad candidates before we run out of interference cache cursors.
1124 // This will only affect register classes with a lot of registers (>32).
1125 if (NumCands == IntfCache.getMaxCursors()) {
1126 unsigned WorstCount = ~0u;
1127 unsigned Worst = 0;
1128 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001129 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001130 continue;
1131 unsigned Count = GlobalCand[i].LiveBundles.count();
1132 if (Count < WorstCount)
1133 Worst = i, WorstCount = Count;
1134 }
1135 --NumCands;
1136 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001137 if (BestCand == NumCands)
1138 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001139 }
1140
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001141 if (GlobalCand.size() <= NumCands)
1142 GlobalCand.resize(NumCands+1);
1143 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1144 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001145
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001146 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001147 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001148 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001149 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001150 continue;
1151 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001152 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001153 if (Cost >= BestCost) {
1154 DEBUG({
1155 if (BestCand == NoCand)
1156 dbgs() << " worse than no bundles\n";
1157 else
1158 dbgs() << " worse than "
1159 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1160 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001161 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001162 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001163 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001164
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001165 SpillPlacer->finish();
1166
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001167 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001168 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001169 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001170 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001171 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001172
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001173 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001174 DEBUG({
1175 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001176 for (int i = Cand.LiveBundles.find_first(); i>=0;
1177 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001178 dbgs() << " EB#" << i;
1179 dbgs() << ".\n";
1180 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001181 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001182 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001183 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001184 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001185 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001186 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001187
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001188 // No solutions found, fall back to single block splitting.
1189 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001190 return 0;
1191
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001192 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001193 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001194 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001195
1196 // Assign all edge bundles to the preferred candidate, or NoCand.
1197 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1198
1199 // Assign bundles for the best candidate region.
1200 if (BestCand != NoCand) {
1201 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1202 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1203 UsedCands.push_back(BestCand);
1204 Cand.IntvIdx = SE->openIntv();
1205 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1206 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001207 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001208 }
1209 }
1210
1211 // Assign bundles for the compact region.
1212 if (HasCompact) {
1213 GlobalSplitCandidate &Cand = GlobalCand.front();
1214 assert(!Cand.PhysReg && "Compact region has no physreg");
1215 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1216 UsedCands.push_back(0);
1217 Cand.IntvIdx = SE->openIntv();
1218 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1219 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001220 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001221 }
1222 }
1223
1224 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001225 return 0;
1226}
1227
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001228
1229//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001230// Per-Block Splitting
1231//===----------------------------------------------------------------------===//
1232
1233/// tryBlockSplit - Split a global live range around every block with uses. This
1234/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1235/// they don't allocate.
1236unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1237 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1238 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1239 unsigned Reg = VirtReg.reg;
1240 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001241 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001242 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001243 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1244 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1245 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1246 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1247 SE->splitSingleBlock(BI);
1248 }
1249 // No blocks were split.
1250 if (LREdit.empty())
1251 return 0;
1252
1253 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001254 SmallVector<unsigned, 8> IntvMap;
1255 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001256
1257 // Tell LiveDebugVariables about the new ranges.
1258 DebugVars->splitRegister(Reg, LREdit.regs());
1259
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001260 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1261
1262 // Sort out the new intervals created by splitting. The remainder interval
1263 // goes straight to spilling, the new local ranges get to stay RS_New.
1264 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1265 LiveInterval &LI = *LREdit.get(i);
1266 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1267 setStage(LI, RS_Spill);
1268 }
1269
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001270 if (VerifyEnabled)
1271 MF->verify(this, "After splitting live range around basic blocks");
1272 return 0;
1273}
1274
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001275
1276//===----------------------------------------------------------------------===//
1277// Per-Instruction Splitting
1278//===----------------------------------------------------------------------===//
1279
1280/// tryInstructionSplit - Split a live range around individual instructions.
1281/// This is normally not worthwhile since the spiller is doing essentially the
1282/// same thing. However, when the live range is in a constrained register
1283/// class, it may help to insert copies such that parts of the live range can
1284/// be moved to a larger register class.
1285///
1286/// This is similar to spilling to a larger register class.
1287unsigned
1288RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1289 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1290 // There is no point to this if there are no larger sub-classes.
1291 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1292 return 0;
1293
1294 // Always enable split spill mode, since we're effectively spilling to a
1295 // register.
1296 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1297 SE->reset(LREdit, SplitEditor::SM_Size);
1298
1299 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1300 if (Uses.size() <= 1)
1301 return 0;
1302
1303 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1304
1305 // Split around every non-copy instruction.
1306 for (unsigned i = 0; i != Uses.size(); ++i) {
1307 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1308 if (MI->isFullCopy()) {
1309 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1310 continue;
1311 }
1312 SE->openIntv();
1313 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1314 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1315 SE->useIntv(SegStart, SegStop);
1316 }
1317
1318 if (LREdit.empty()) {
1319 DEBUG(dbgs() << "All uses were copies.\n");
1320 return 0;
1321 }
1322
1323 SmallVector<unsigned, 8> IntvMap;
1324 SE->finish(&IntvMap);
1325 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1326 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1327
1328 // Assign all new registers to RS_Spill. This was the last chance.
1329 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1330 return 0;
1331}
1332
1333
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001334//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001335// Local Splitting
1336//===----------------------------------------------------------------------===//
1337
1338
1339/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1340/// in order to use PhysReg between two entries in SA->UseSlots.
1341///
1342/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1343///
1344void RAGreedy::calcGapWeights(unsigned PhysReg,
1345 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001346 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1347 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001348 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001349 const unsigned NumGaps = Uses.size()-1;
1350
1351 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001352 SlotIndex StartIdx =
1353 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1354 SlotIndex StopIdx =
1355 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001356
1357 GapWeight.assign(NumGaps, 0.0f);
1358
1359 // Add interference from each overlapping register.
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +00001360 for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001361 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1362 .checkInterference())
1363 continue;
1364
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001365 // We know that VirtReg is a continuous interval from FirstInstr to
1366 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001367 //
1368 // Interference that overlaps an instruction is counted in both gaps
1369 // surrounding the instruction. The exception is interference before
1370 // StartIdx and after StopIdx.
1371 //
Jakob Stoklund Olesen93841112012-01-11 23:19:08 +00001372 LiveIntervalUnion::SegmentIter IntI = getLiveUnion(*AI).find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001373 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1374 // Skip the gaps before IntI.
1375 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1376 if (++Gap == NumGaps)
1377 break;
1378 if (Gap == NumGaps)
1379 break;
1380
1381 // Update the gaps covered by IntI.
1382 const float weight = IntI.value()->weight;
1383 for (; Gap != NumGaps; ++Gap) {
1384 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1385 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1386 break;
1387 }
1388 if (Gap == NumGaps)
1389 break;
1390 }
1391 }
1392}
1393
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001394/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1395/// basic block.
1396///
1397unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1398 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001399 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1400 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001401
1402 // Note that it is possible to have an interval that is live-in or live-out
1403 // while only covering a single block - A phi-def can use undef values from
1404 // predecessors, and the block could be a single-block loop.
1405 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001406 // that the interval is continuous from FirstInstr to LastInstr. We should
1407 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001408
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001409 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001410 if (Uses.size() <= 2)
1411 return 0;
1412 const unsigned NumGaps = Uses.size()-1;
1413
1414 DEBUG({
1415 dbgs() << "tryLocalSplit: ";
1416 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001417 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001418 dbgs() << '\n';
1419 });
1420
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001421 // If VirtReg is live across any register mask operands, compute a list of
1422 // gaps with register masks.
1423 SmallVector<unsigned, 8> RegMaskGaps;
1424 if (!UsableRegs.empty()) {
1425 // Get regmask slots for the whole block.
1426 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001427 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001428 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001429 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1430 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001431 unsigned re = RMS.size();
1432 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001433 // Look for Uses[i] <= RMS <= Uses[i+1].
1434 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1435 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001436 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001437 // Skip a regmask on the same instruction as the last use. It doesn't
1438 // overlap the live range.
1439 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1440 break;
1441 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001442 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001443 // Advance ri to the next gap. A regmask on one of the uses counts in
1444 // both gaps.
1445 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1446 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001447 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001448 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001449 }
1450
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001451 // Since we allow local split results to be split again, there is a risk of
1452 // creating infinite loops. It is tempting to require that the new live
1453 // ranges have less instructions than the original. That would guarantee
1454 // convergence, but it is too strict. A live range with 3 instructions can be
1455 // split 2+3 (including the COPY), and we want to allow that.
1456 //
1457 // Instead we use these rules:
1458 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001459 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001460 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001461 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001462 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001463 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001464 // smaller ranges are marked RS_New.
1465 //
1466 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1467 // excessive splitting and infinite loops.
1468 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001469 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001470
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001471 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001472 unsigned BestBefore = NumGaps;
1473 unsigned BestAfter = 0;
1474 float BestDiff = 0;
1475
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001476 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001477 SmallVector<float, 8> GapWeight;
1478
1479 Order.rewind();
1480 while (unsigned PhysReg = Order.next()) {
1481 // Keep track of the largest spill weight that would need to be evicted in
1482 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1483 calcGapWeights(PhysReg, GapWeight);
1484
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001485 // Remove any gaps with regmask clobbers.
1486 if (clobberedByRegMask(PhysReg))
1487 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1488 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1489
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001490 // Try to find the best sequence of gaps to close.
1491 // The new spill weight must be larger than any gap interference.
1492
1493 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001494 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001495
1496 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1497 // It is the spill weight that needs to be evicted.
1498 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001499
1500 for (;;) {
1501 // Live before/after split?
1502 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1503 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1504
1505 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1506 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1507 << " i=" << MaxGap);
1508
1509 // Stop before the interval gets so big we wouldn't be making progress.
1510 if (!LiveBefore && !LiveAfter) {
1511 DEBUG(dbgs() << " all\n");
1512 break;
1513 }
1514 // Should the interval be extended or shrunk?
1515 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001516
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001517 // How many gaps would the new range have?
1518 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1519
1520 // Legally, without causing looping?
1521 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1522
1523 if (Legal && MaxGap < HUGE_VALF) {
1524 // Estimate the new spill weight. Each instruction reads or writes the
1525 // register. Conservatively assume there are no read-modify-write
1526 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001527 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001528 // Try to guess the size of the new interval.
1529 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1530 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1531 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001532 // Would this split be possible to allocate?
1533 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001534 DEBUG(dbgs() << " w=" << EstWeight);
1535 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001536 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001537 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001538 if (Diff > BestDiff) {
1539 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001540 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001541 BestBefore = SplitBefore;
1542 BestAfter = SplitAfter;
1543 }
1544 }
1545 }
1546
1547 // Try to shrink.
1548 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001549 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001550 DEBUG(dbgs() << " shrink\n");
1551 // Recompute the max when necessary.
1552 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1553 MaxGap = GapWeight[SplitBefore];
1554 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1555 MaxGap = std::max(MaxGap, GapWeight[i]);
1556 }
1557 continue;
1558 }
1559 MaxGap = 0;
1560 }
1561
1562 // Try to extend the interval.
1563 if (SplitAfter >= NumGaps) {
1564 DEBUG(dbgs() << " end\n");
1565 break;
1566 }
1567
1568 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001569 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001570 }
1571 }
1572
1573 // Didn't find any candidates?
1574 if (BestBefore == NumGaps)
1575 return 0;
1576
1577 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1578 << '-' << Uses[BestAfter] << ", " << BestDiff
1579 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1580
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001581 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001582 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001583
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001584 SE->openIntv();
1585 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1586 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1587 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001588 SmallVector<unsigned, 8> IntvMap;
1589 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001590 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001591
1592 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001593 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001594 // leave the new intervals as RS_New so they can compete.
1595 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1596 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1597 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1598 if (NewGaps >= NumGaps) {
1599 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1600 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001601 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1602 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001603 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001604 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1605 }
1606 DEBUG(dbgs() << '\n');
1607 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001608 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001609
1610 return 0;
1611}
1612
1613//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001614// Live Range Splitting
1615//===----------------------------------------------------------------------===//
1616
1617/// trySplit - Try to split VirtReg or one of its interferences, making it
1618/// assignable.
1619/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1620unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1621 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001622 // Ranges must be Split2 or less.
1623 if (getStage(VirtReg) >= RS_Spill)
1624 return 0;
1625
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001626 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001627 if (LIS->intervalIsInOneMBB(VirtReg)) {
1628 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001629 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001630 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1631 if (PhysReg || !NewVRegs.empty())
1632 return PhysReg;
1633 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001634 }
1635
1636 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001637
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001638 SA->analyze(&VirtReg);
1639
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001640 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1641 // coalescer. That may cause the range to become allocatable which means that
1642 // tryRegionSplit won't be making progress. This check should be replaced with
1643 // an assertion when the coalescer is fixed.
1644 if (SA->didRepairRange()) {
1645 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesenbdda37d2011-05-10 17:37:41 +00001646 invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001647 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1648 return PhysReg;
1649 }
1650
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001651 // First try to split around a region spanning multiple blocks. RS_Split2
1652 // ranges already made dubious progress with region splitting, so they go
1653 // straight to single block splitting.
1654 if (getStage(VirtReg) < RS_Split2) {
1655 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1656 if (PhysReg || !NewVRegs.empty())
1657 return PhysReg;
1658 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001659
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001660 // Then isolate blocks.
1661 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001662}
1663
1664
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001665//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001666// Main Entry Point
1667//===----------------------------------------------------------------------===//
1668
1669unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001670 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesene7c2c152012-02-09 18:25:05 +00001671 // Check if VirtReg is live across any calls.
1672 UsableRegs.clear();
1673 if (LIS->checkRegMaskInterference(VirtReg, UsableRegs))
1674 DEBUG(dbgs() << "Live across regmasks.\n");
1675
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001676 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001677 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001678 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1679 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001680
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001681 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001682 DEBUG(dbgs() << StageName[Stage]
1683 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001684
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001685 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001686 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001687 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001688 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001689 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1690 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001691
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001692 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1693
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001694 // The first time we see a live range, don't try to split or spill.
1695 // Wait until the second time, when all smaller ranges have been allocated.
1696 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001697 if (Stage < RS_Split) {
1698 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001699 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001700 NewVRegs.push_back(&VirtReg);
1701 return 0;
1702 }
1703
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001704 // If we couldn't allocate a register from spilling, there is probably some
1705 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001706 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001707 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001708
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001709 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001710 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1711 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001712 return PhysReg;
1713
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001714 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001715 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001716 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001717 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001718 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001719
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001720 if (VerifyEnabled)
1721 MF->verify(this, "After spilling");
1722
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001723 // The live virtual register requesting allocation was spilled, so tell
1724 // the caller not to allocate anything during this round.
1725 return 0;
1726}
1727
1728bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1729 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1730 << "********** Function: "
1731 << ((Value*)mf.getFunction())->getName() << '\n');
1732
1733 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001734 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001735 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001736
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001737 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001738 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001739 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001740 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001741 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001742 Bundles = &getAnalysis<EdgeBundles>();
1743 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001744 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001745
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001746 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001747 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001748 ExtraRegInfo.clear();
1749 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1750 NextCascade = 1;
Jakob Stoklund Olesen6ef7da02012-02-10 18:58:34 +00001751 IntfCache.init(MF, &getLiveUnion(0), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001752 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001753
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001754 allocatePhysRegs();
1755 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001756 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001757
1758 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001759 {
1760 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001761 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001762 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001763
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001764 // Write out new DBG_VALUE instructions.
Jakob Stoklund Olesenc4769022011-07-31 03:53:42 +00001765 {
1766 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1767 DebugVars->emitDebugValues(VRM);
1768 }
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +00001769
Andrew Trick19273ae2012-02-21 04:51:23 +00001770 // All machine operands and other references to virtual registers have been
1771 // replaced. Remove the virtual registers and release all the transient data.
1772 VRM->clearAllVirt();
1773 MRI->clearVirtRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001774 releaseMemory();
1775
1776 return true;
1777}