blob: 3d1b580207d364ec07be78f6dc62f5d10be4f9dc [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000017#include "AllocationOrder.h"
Jakob Stoklund Olesen5907d862011-04-02 06:03:35 +000018#include "InterferenceCache.h"
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +000019#include "LiveDebugVariables.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000020#include "RegAllocBase.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "Spiller.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000023#include "SplitKit.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"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000026#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000027#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper789d5d82012-04-02 22:44:18 +000029#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000030#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000032#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineLoopInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/RegAllocRegistry.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000037#include "llvm/CodeGen/VirtRegMap.h"
38#include "llvm/PassAnalysisSupport.h"
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +000039#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000042#include "llvm/Support/Timer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000043#include "llvm/Support/raw_ostream.h"
44#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000045#include <queue>
46
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000047using namespace llvm;
48
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000049STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000051STATISTIC(NumEvicted, "Number of interferences evicted");
52
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +000053static cl::opt<SplitEditor::ComplementSpillMode>
54SplitSpillMode("split-spill-mode", cl::Hidden,
55 cl::desc("Spill mode for splitting live ranges"),
56 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
57 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
58 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
59 clEnumValEnd),
60 cl::init(SplitEditor::SM_Partition));
61
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000062static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
63 createGreedyRegisterAllocator);
64
65namespace {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000066class RAGreedy : public MachineFunctionPass,
67 public RegAllocBase,
68 private LiveRangeEdit::Delegate {
69
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000070 // context
71 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000072
73 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000074 SlotIndexes *Indexes;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000075 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000076 MachineLoopInfo *Loops;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000077 EdgeBundles *Bundles;
78 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +000079 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000080
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000081 // state
82 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000083 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +000084 unsigned NextCascade;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000085
86 // Live ranges pass through a number of stages as we try to allocate them.
87 // Some of the stages may also create new live ranges:
88 //
89 // - Region splitting.
90 // - Per-block splitting.
91 // - Local splitting.
92 // - Spilling.
93 //
94 // Ranges produced by one of the stages skip the previous stages when they are
95 // dequeued. This improves performance because we can skip interference checks
96 // that are unlikely to give any results. It also guarantees that the live
97 // range splitting algorithm terminates, something that is otherwise hard to
98 // ensure.
99 enum LiveRangeStage {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000100 /// Newly created live range that has never been queued.
101 RS_New,
102
103 /// Only attempt assignment and eviction. Then requeue as RS_Split.
104 RS_Assign,
105
106 /// Attempt live range splitting if assignment is impossible.
107 RS_Split,
108
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000109 /// Attempt more aggressive live range splitting that is guaranteed to make
110 /// progress. This is used for split products that may not be making
111 /// progress.
112 RS_Split2,
113
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000114 /// Live range will be spilled. No more splitting will be attempted.
115 RS_Spill,
116
117 /// There is nothing more we can do to this live range. Abort compilation
118 /// if it can't be assigned.
119 RS_Done
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000120 };
121
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000122 static const char *const StageName[];
123
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000124 // RegInfo - Keep additional information about each live range.
125 struct RegInfo {
126 LiveRangeStage Stage;
127
128 // Cascade - Eviction loop prevention. See canEvictInterference().
129 unsigned Cascade;
130
131 RegInfo() : Stage(RS_New), Cascade(0) {}
132 };
133
134 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000135
136 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000137 return ExtraRegInfo[VirtReg.reg].Stage;
138 }
139
140 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
141 ExtraRegInfo.resize(MRI->getNumVirtRegs());
142 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000143 }
144
145 template<typename Iterator>
146 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000147 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000148 for (;Begin != End; ++Begin) {
149 unsigned Reg = (*Begin)->reg;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000150 if (ExtraRegInfo[Reg].Stage == RS_New)
151 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000152 }
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000153 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000154
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000155 /// Cost of evicting interference.
156 struct EvictionCost {
157 unsigned BrokenHints; ///< Total number of broken hints.
158 float MaxWeight; ///< Maximum spill weight evicted.
159
160 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
161
162 bool operator<(const EvictionCost &O) const {
163 if (BrokenHints != O.BrokenHints)
164 return BrokenHints < O.BrokenHints;
165 return MaxWeight < O.MaxWeight;
166 }
167 };
168
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000169 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000170 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000171 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000172
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000173 /// Cached per-block interference maps
174 InterferenceCache IntfCache;
175
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000176 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000177 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000178
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000179 /// Global live range splitting candidate info.
180 struct GlobalSplitCandidate {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000181 // Register intended for assignment, or 0.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000182 unsigned PhysReg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000183
184 // SplitKit interval index for this candidate.
185 unsigned IntvIdx;
186
187 // Interference for PhysReg.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000188 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000189
190 // Bundles where this candidate should be live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000191 BitVector LiveBundles;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000192 SmallVector<unsigned, 8> ActiveBlocks;
193
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000194 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000195 PhysReg = Reg;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000196 IntvIdx = 0;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000197 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000198 LiveBundles.clear();
199 ActiveBlocks.clear();
200 }
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000201
202 // Set B[i] = C for every live bundle where B[i] was NoCand.
203 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
204 unsigned Count = 0;
205 for (int i = LiveBundles.find_first(); i >= 0;
206 i = LiveBundles.find_next(i))
207 if (B[i] == NoCand) {
208 B[i] = C;
209 Count++;
210 }
211 return Count;
212 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000213 };
214
215 /// Candidate info for for each PhysReg in AllocationOrder.
216 /// This vector never shrinks, but grows to the size of the largest register
217 /// class.
218 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
219
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000220 enum { NoCand = ~0u };
221
222 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
223 /// NoCand which indicates the stack interval.
224 SmallVector<unsigned, 32> BundleCand;
225
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000226public:
227 RAGreedy();
228
229 /// Return the pass name.
230 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000231 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000232 }
233
234 /// RAGreedy analysis usage.
235 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000236 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000237 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000238 virtual void enqueue(LiveInterval *LI);
239 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000240 virtual unsigned selectOrSplit(LiveInterval&,
241 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000242
243 /// Perform register allocation.
244 virtual bool runOnMachineFunction(MachineFunction &mf);
245
246 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000247
248private:
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000249 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000250 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000251 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000252
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000253 float calcSpillCost();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000254 bool addSplitConstraints(InterferenceCache::Cursor, float&);
255 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000256 void growRegion(GlobalSplitCandidate &Cand);
257 float calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000258 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000259 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000260 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000261 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
262 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
263 void evictInterference(LiveInterval&, unsigned,
264 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000265
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000266 unsigned tryAssign(LiveInterval&, AllocationOrder&,
267 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000268 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000269 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000270 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
271 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +0000272 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
273 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +0000274 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
275 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000276 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
277 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000278 unsigned trySplit(LiveInterval&, AllocationOrder&,
279 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000280};
281} // end anonymous namespace
282
283char RAGreedy::ID = 0;
284
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000285#ifndef NDEBUG
286const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000287 "RS_New",
288 "RS_Assign",
289 "RS_Split",
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000290 "RS_Split2",
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000291 "RS_Spill",
292 "RS_Done"
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000293};
294#endif
295
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000296// Hysteresis to use when comparing floats.
297// This helps stabilize decisions based on float comparisons.
298const float Hysteresis = 0.98f;
299
300
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000301FunctionPass* llvm::createGreedyRegisterAllocator() {
302 return new RAGreedy();
303}
304
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000305RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000306 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000307 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000308 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
309 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola5b220212011-06-26 22:34:10 +0000310 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Trick42b7a712012-01-17 06:55:03 +0000311 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000312 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
313 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
314 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
315 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
316 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000317 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000318 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
319 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000320}
321
322void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
323 AU.setPreservesCFG();
324 AU.addRequired<AliasAnalysis>();
325 AU.addPreserved<AliasAnalysis>();
326 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen05ec7122012-06-08 23:44:45 +0000327 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000328 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000329 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesencfafc542011-04-05 21:40:37 +0000330 AU.addRequired<LiveDebugVariables>();
331 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000332 AU.addRequired<LiveStacks>();
333 AU.addPreserved<LiveStacks>();
Evan Chengbb36a432012-09-21 20:04:28 +0000334 AU.addRequired<CalculateSpillWeights>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000335 AU.addRequired<MachineDominatorTree>();
336 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000337 AU.addRequired<MachineLoopInfo>();
338 AU.addPreserved<MachineLoopInfo>();
339 AU.addRequired<VirtRegMap>();
340 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000341 AU.addRequired<LiveRegMatrix>();
342 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000343 AU.addRequired<EdgeBundles>();
344 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000345 MachineFunctionPass::getAnalysisUsage(AU);
346}
347
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000348
349//===----------------------------------------------------------------------===//
350// LiveRangeEdit delegate methods
351//===----------------------------------------------------------------------===//
352
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000353bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000354 if (VRM->hasPhys(VirtReg)) {
355 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000356 return true;
357 }
358 // Unassigned virtreg is probably in the priority queue.
359 // RegAllocBase will erase it after dequeueing.
360 return false;
361}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000362
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000363void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000364 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000365 return;
366
367 // Register is assigned, put it back on the queue for reassignment.
368 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000369 Matrix->unassign(LI);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000370 enqueue(&LI);
371}
372
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000373void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen0d4fea72011-09-14 17:34:37 +0000374 // Cloning a register we haven't even heard about yet? Just ignore it.
375 if (!ExtraRegInfo.inBounds(Old))
376 return;
377
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000378 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000379 // be split into connected components. The new components are much smaller
380 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000381 // same stage as the parent.
Jakob Stoklund Olesen165e2312011-07-26 00:54:56 +0000382 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000383 ExtraRegInfo.grow(New);
384 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000385}
386
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000387void RAGreedy::releaseMemory() {
388 SpillerInstance.reset(0);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000389 ExtraRegInfo.clear();
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000390 GlobalCand.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000391}
392
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000393void RAGreedy::enqueue(LiveInterval *LI) {
394 // Prioritize live ranges by size, assigning larger ranges first.
395 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000396 const unsigned Size = LI->getSize();
397 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000398 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
399 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000400 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000401
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000402 ExtraRegInfo.grow(Reg);
403 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000404 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesenf22ca3f2011-03-30 02:52:39 +0000405
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000406 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000407 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000408 // everything else has been allocated.
409 Prio = Size;
Jakob Stoklund Olesencc07e042011-07-28 20:48:23 +0000410 } else {
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +0000411 // Everything is allocated in long->short order. Long ranges that don't fit
412 // should be spilled (or split) ASAP so they don't create interference.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000413 Prio = (1u << 31) + Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000414
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +0000415 // Boost ranges that have a physical register hint.
416 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
417 Prio |= (1u << 30);
418 }
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000419
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000420 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000421}
422
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000423LiveInterval *RAGreedy::dequeue() {
424 if (Queue.empty())
425 return 0;
Jakob Stoklund Olesene3b23cd2012-04-02 22:30:39 +0000426 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000427 Queue.pop();
428 return LI;
429}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000430
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000431
432//===----------------------------------------------------------------------===//
433// Direct Assignment
434//===----------------------------------------------------------------------===//
435
436/// tryAssign - Try to assign VirtReg to an available register.
437unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
438 AllocationOrder &Order,
439 SmallVectorImpl<LiveInterval*> &NewVRegs) {
440 Order.rewind();
441 unsigned PhysReg;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000442 while ((PhysReg = Order.next()))
443 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000444 break;
445 if (!PhysReg || Order.isHint(PhysReg))
446 return PhysReg;
447
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000448 // PhysReg is available, but there may be a better choice.
449
450 // If we missed a simple hint, try to cheaply evict interference from the
451 // preferred register.
452 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000453 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000454 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
455 EvictionCost MaxCost(1);
456 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
457 evictInterference(VirtReg, Hint, NewVRegs);
458 return Hint;
459 }
460 }
461
462 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000463 unsigned Cost = TRI->getCostPerUse(PhysReg);
464
465 // Most registers have 0 additional cost.
466 if (!Cost)
467 return PhysReg;
468
469 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
470 << '\n');
471 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
472 return CheapReg ? CheapReg : PhysReg;
473}
474
475
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000476//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000477// Interference eviction
478//===----------------------------------------------------------------------===//
479
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000480/// shouldEvict - determine if A should evict the assigned live range B. The
481/// eviction policy defined by this function together with the allocation order
482/// defined by enqueue() decides which registers ultimately end up being split
483/// and spilled.
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000484///
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000485/// Cascade numbers are used to prevent infinite loops if this function is a
486/// cyclic relation.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000487///
488/// @param A The live range to be assigned.
489/// @param IsHint True when A is about to be assigned to its preferred
490/// register.
491/// @param B The live range to be evicted.
492/// @param BreaksHint True when B is already assigned to its preferred register.
493bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
494 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +0000495 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000496
497 // Be fairly aggressive about following hints as long as the evictee can be
498 // split.
499 if (CanSplit && IsHint && !BreaksHint)
500 return true;
501
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000502 return A.weight > B.weight;
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +0000503}
504
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000505/// canEvictInterference - Return true if all interferences between VirtReg and
506/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
507///
508/// @param VirtReg Live range that is about to be assigned.
509/// @param PhysReg Desired register for assignment.
Dmitri Gribenko67c89782012-09-12 16:59:47 +0000510/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000511/// @param MaxCost Only look for cheaper candidates and update with new cost
512/// when returning true.
513/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000514bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000515 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000516 // It is only possible to evict virtual register interference.
517 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
518 return false;
519
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000520 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
521 // involved in an eviction before. If a cascade number was assigned, deny
522 // evicting anything with the same or a newer cascade number. This prevents
523 // infinite eviction loops.
524 //
525 // This works out so a register without a cascade number is allowed to evict
526 // anything, and it can be evicted by anything.
527 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
528 if (!Cascade)
529 Cascade = NextCascade;
530
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000531 EvictionCost Cost;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000532 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
533 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000534 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000535 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000536 return false;
537
Jakob Stoklund Olesen3f5bedf2011-04-11 21:47:01 +0000538 // Check if any interfering live range is heavier than MaxWeight.
539 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
540 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000541 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
542 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000543 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +0000544 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +0000545 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000546 // Once a live range becomes small enough, it is urgent that we find a
547 // register for it. This is indicated by an infinite spill weight. These
548 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen9cda1be2012-05-30 21:46:58 +0000549 //
550 // Also allow urgent evictions of unspillable ranges from a strictly
551 // larger allocation order.
552 bool Urgent = !VirtReg.isSpillable() &&
553 (Intf->isSpillable() ||
554 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
555 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000556 // Only evict older cascades or live ranges without a cascade.
557 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
558 if (Cascade <= IntfCascade) {
559 if (!Urgent)
560 return false;
561 // We permit breaking cascades for urgent evictions. It should be the
562 // last resort, though, so make it really expensive.
563 Cost.BrokenHints += 10;
564 }
565 // Would this break a satisfied hint?
566 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
567 // Update eviction cost.
568 Cost.BrokenHints += BreaksHint;
569 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
570 // Abort if this would be too expensive.
571 if (!(Cost < MaxCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000572 return false;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000573 // Finally, apply the eviction policy for non-urgent evictions.
574 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
Jakob Stoklund Olesend2056e52011-05-31 21:02:44 +0000575 return false;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000576 }
577 }
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000578 MaxCost = Cost;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000579 return true;
580}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000581
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000582/// evictInterference - Evict any interferring registers that prevent VirtReg
583/// from being assigned to Physreg. This assumes that canEvictInterference
584/// returned true.
585void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
586 SmallVectorImpl<LiveInterval*> &NewVRegs) {
587 // Make sure that VirtReg has a cascade number, and assign that cascade
588 // number to every evicted register. These live ranges than then only be
589 // evicted by a newer cascade, preventing infinite loops.
590 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
591 if (!Cascade)
592 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
593
594 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
595 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000596
597 // Collect all interfering virtregs first.
598 SmallVector<LiveInterval*, 8> Intfs;
599 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
600 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000601 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +0000602 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
603 Intfs.append(IVR.begin(), IVR.end());
604 }
605
606 // Evict them second. This will invalidate the queries.
607 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
608 LiveInterval *Intf = Intfs[i];
609 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
610 if (!VRM->hasPhys(Intf->reg))
611 continue;
612 Matrix->unassign(*Intf);
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);
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000619 }
620}
621
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000622/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +0000623/// @param VirtReg Currently unassigned virtual register.
624/// @param Order Physregs to try.
625/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000626unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
627 AllocationOrder &Order,
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000628 SmallVectorImpl<LiveInterval*> &NewVRegs,
629 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000630 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
631
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000632 // Keep track of the cheapest interference seen so far.
633 EvictionCost BestCost(~0u);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000634 unsigned BestPhys = 0;
635
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000636 // When we are just looking for a reduced cost per use, don't break any
637 // hints, and only evict smaller spill weights.
638 if (CostPerUseLimit < ~0u) {
639 BestCost.BrokenHints = 0;
640 BestCost.MaxWeight = VirtReg.weight;
641 }
642
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000643 Order.rewind();
644 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000645 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
646 continue;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000647 // The first use of a callee-saved register in a function has cost 1.
648 // Don't start using a CSR when the CostPerUseLimit is low.
649 if (CostPerUseLimit == 1)
650 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
651 if (!MRI->isPhysRegUsed(CSR)) {
652 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
653 << PrintReg(CSR, TRI) << '\n');
654 continue;
655 }
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +0000656
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000657 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000658 continue;
659
660 // Best so far.
661 BestPhys = PhysReg;
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000662
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000663 // Stop if the hint can be used.
664 if (Order.isHint(PhysReg))
665 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000666 }
667
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000668 if (!BestPhys)
669 return 0;
670
Jakob Stoklund Olesen51458ed2011-07-08 20:46:18 +0000671 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000672 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000673}
674
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000675
676//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000677// Region Splitting
678//===----------------------------------------------------------------------===//
679
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000680/// addSplitConstraints - Fill out the SplitConstraints vector based on the
681/// interference pattern in Physreg and its aliases. Add the constraints to
682/// SpillPlacement and return the static cost of this split in Cost, assuming
683/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000684/// Return false if there are no bundles with positive bias.
685bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
686 float &Cost) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000687 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000688
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000689 // Reset interference dependent info.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000690 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000691 float StaticCost = 0;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000692 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
693 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000694 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000695
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000696 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000697 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000698 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
699 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesen5ebca792011-08-02 23:04:06 +0000700 BC.ChangesValue = BI.FirstDef;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000701
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000702 if (!Intf.hasInterference())
703 continue;
704
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000705 // Number of spill code instructions to insert.
706 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000707
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000708 // Interference for the live-in value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000709 if (BI.LiveIn) {
Jakob Stoklund Olesen6c8afd72011-04-04 15:32:15 +0000710 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000711 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000712 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000713 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000714 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000715 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000716 }
717
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000718 // Interference for the live-out value.
Jakob Stoklund Oleseneda0fe82011-04-02 06:03:38 +0000719 if (BI.LiveOut) {
Jakob Stoklund Olesen612f7802011-04-05 04:20:29 +0000720 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000721 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000722 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000723 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +0000724 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000725 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000726 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000727
728 // Accumulate the total frequency of inserted spill code.
729 if (Ins)
730 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000731 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000732 Cost = StaticCost;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000733
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000734 // Add constraints for use-blocks. Note that these are the only constraints
735 // that may add a positive bias, it is downhill from here.
736 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000737 return SpillPlacer->scanActiveBundles();
738}
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000739
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000740
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000741/// addThroughConstraints - Add constraints and links to SpillPlacer from the
742/// live-through blocks in Blocks.
743void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
744 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000745 const unsigned GroupSize = 8;
746 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000747 unsigned TBS[GroupSize];
748 unsigned B = 0, T = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000749
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000750 for (unsigned i = 0; i != Blocks.size(); ++i) {
751 unsigned Number = Blocks[i];
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000752 Intf.moveToBlock(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000753
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000754 if (!Intf.hasInterference()) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000755 assert(T < GroupSize && "Array overflow");
756 TBS[T] = Number;
757 if (++T == GroupSize) {
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000758 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000759 T = 0;
760 }
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000761 continue;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000762 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000763
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000764 assert(B < GroupSize && "Array overflow");
765 BCS[B].Number = Number;
766
Jakob Stoklund Olesen7b41fbe2011-04-07 17:27:46 +0000767 // Interference for the live-in value.
768 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
769 BCS[B].Entry = SpillPlacement::MustSpill;
770 else
771 BCS[B].Entry = SpillPlacement::PrefSpill;
772
773 // Interference for the live-out value.
774 if (Intf.last() >= SA->getLastSplitPoint(Number))
775 BCS[B].Exit = SpillPlacement::MustSpill;
776 else
777 BCS[B].Exit = SpillPlacement::PrefSpill;
778
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000779 if (++B == GroupSize) {
780 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
781 SpillPlacer->addConstraints(Array);
782 B = 0;
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000783 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000784 }
785
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +0000786 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
787 SpillPlacer->addConstraints(Array);
Frits van Bommel39b5abf2011-07-18 12:00:32 +0000788 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000789}
790
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000791void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000792 // Keep track of through blocks that have not been added to SpillPlacer.
793 BitVector Todo = SA->getThroughBlocks();
794 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
795 unsigned AddedTo = 0;
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000796#ifndef NDEBUG
797 unsigned Visited = 0;
798#endif
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000799
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000800 for (;;) {
801 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000802 // Find new through blocks in the periphery of PrefRegBundles.
803 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
804 unsigned Bundle = NewBundles[i];
805 // Look at all blocks connected to Bundle in the full graph.
806 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
807 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
808 I != E; ++I) {
809 unsigned Block = *I;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000810 if (!Todo.test(Block))
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000811 continue;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000812 Todo.reset(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000813 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000814 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000815#ifndef NDEBUG
816 ++Visited;
817#endif
818 }
819 }
820 // Any new blocks to add?
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000821 if (ActiveBlocks.size() == AddedTo)
822 break;
Jakob Stoklund Olesenb4666362011-07-23 03:22:33 +0000823
824 // Compute through constraints from the interference, or assume that all
825 // through blocks prefer spilling when forming compact regions.
826 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
827 if (Cand.PhysReg)
828 addThroughConstraints(Cand.Intf, NewBlocks);
829 else
Jakob Stoklund Olesenb87f91b2011-08-03 23:09:38 +0000830 // Provide a strong negative bias on through blocks to prevent unwanted
831 // liveness on loop backedges.
832 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen54901972011-07-05 18:46:42 +0000833 AddedTo = ActiveBlocks.size();
834
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000835 // Perhaps iterating can enable more bundles?
836 SpillPlacer->iterate();
837 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +0000838 DEBUG(dbgs() << ", v=" << Visited);
839}
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000840
Jakob Stoklund Olesen87972fa2011-07-23 03:41:57 +0000841/// calcCompactRegion - Compute the set of edge bundles that should be live
842/// when splitting the current live range into compact regions. Compact
843/// regions can be computed without looking at interference. They are the
844/// regions formed by removing all the live-through blocks from the live range.
845///
846/// Returns false if the current live range is already compact, or if the
847/// compact regions would form single block regions anyway.
848bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
849 // Without any through blocks, the live range is already compact.
850 if (!SA->getNumThroughBlocks())
851 return false;
852
853 // Compact regions don't correspond to any physreg.
854 Cand.reset(IntfCache, 0);
855
856 DEBUG(dbgs() << "Compact region bundles");
857
858 // Use the spill placer to determine the live bundles. GrowRegion pretends
859 // that all the through blocks have interference when PhysReg is unset.
860 SpillPlacer->prepare(Cand.LiveBundles);
861
862 // The static split cost will be zero since Cand.Intf reports no interference.
863 float Cost;
864 if (!addSplitConstraints(Cand.Intf, Cost)) {
865 DEBUG(dbgs() << ", none.\n");
866 return false;
867 }
868
869 growRegion(Cand);
870 SpillPlacer->finish();
871
872 if (!Cand.LiveBundles.any()) {
873 DEBUG(dbgs() << ", none.\n");
874 return false;
875 }
876
877 DEBUG({
878 for (int i = Cand.LiveBundles.find_first(); i>=0;
879 i = Cand.LiveBundles.find_next(i))
880 dbgs() << " EB#" << i;
881 dbgs() << ".\n";
882 });
883 return true;
884}
885
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000886/// calcSpillCost - Compute how expensive it would be to split the live range in
887/// SA around all use blocks instead of forming bundle regions.
888float RAGreedy::calcSpillCost() {
889 float Cost = 0;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000890 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
891 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
892 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
893 unsigned Number = BI.MBB->getNumber();
894 // We normally only need one spill instruction - a load or a store.
895 Cost += SpillPlacer->getBlockFrequency(Number);
896
897 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3f5beed2011-08-02 23:04:08 +0000898 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
899 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +0000900 }
901 return Cost;
902}
903
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000904/// calcGlobalSplitCost - Return the global split cost of following the split
905/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000906/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000907///
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000908float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000909 float GlobalCost = 0;
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000910 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000911 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
912 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
913 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000914 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000915 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
916 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
917 unsigned Ins = 0;
918
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000919 if (BI.LiveIn)
920 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
921 if (BI.LiveOut)
922 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000923 if (Ins)
924 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000925 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000926
Jakob Stoklund Olesen5db42892011-04-12 21:30:53 +0000927 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
928 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000929 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
930 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000931 if (!RegIn && !RegOut)
932 continue;
933 if (RegIn && RegOut) {
934 // We need double spill code if this block has interference.
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +0000935 Cand.Intf.moveToBlock(Number);
936 if (Cand.Intf.hasInterference())
Jakob Stoklund Olesen9a543522011-04-06 21:32:41 +0000937 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
938 continue;
939 }
940 // live-in / stack-out or stack-in live-out.
941 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000942 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000943 return GlobalCost;
944}
945
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000946/// splitAroundRegion - Split the current live range around the regions
947/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000948///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000949/// Before calling this function, GlobalCand and BundleCand must be initialized
950/// so each bundle is assigned to a valid candidate, or NoCand for the
951/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
952/// objects must be initialized for the current live range, and intervals
953/// created for the used candidates.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000954///
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000955/// @param LREdit The LiveRangeEdit object handling the current split.
956/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
957/// must appear in this list.
958void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
959 ArrayRef<unsigned> UsedCands) {
960 // These are the intervals created for new global ranges. We may create more
961 // intervals for local ranges.
962 const unsigned NumGlobalIntvs = LREdit.size();
963 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
964 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000965
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000966 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen69145ba2011-08-06 18:20:24 +0000967 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +0000968 // is all copies.
969 unsigned Reg = SA->getParent().reg;
970 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
971
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +0000972 // First handle all the blocks with uses.
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +0000973 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
974 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
975 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000976 unsigned Number = BI.MBB->getNumber();
977 unsigned IntvIn = 0, IntvOut = 0;
978 SlotIndex IntfIn, IntfOut;
979 if (BI.LiveIn) {
980 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
981 if (CandIn != NoCand) {
982 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
983 IntvIn = Cand.IntvIdx;
984 Cand.Intf.moveToBlock(Number);
985 IntfIn = Cand.Intf.first();
986 }
987 }
988 if (BI.LiveOut) {
989 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
990 if (CandOut != NoCand) {
991 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
992 IntvOut = Cand.IntvIdx;
993 Cand.Intf.moveToBlock(Number);
994 IntfOut = Cand.Intf.last();
995 }
996 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000997
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +0000998 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +0000999 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001000 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen2d6d86b2011-08-05 22:20:45 +00001001 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesen87360f72011-06-30 01:30:39 +00001002 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenfd5c5132011-04-12 19:32:53 +00001003 continue;
1004 }
1005
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001006 if (IntvIn && IntvOut)
1007 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1008 else if (IntvIn)
1009 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesenb4ddedc2011-07-15 21:47:57 +00001010 else
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001011 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001012 }
1013
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001014 // Handle live-through blocks. The relevant live-through blocks are stored in
1015 // the ActiveBlocks list with each candidate. We need to filter out
1016 // duplicates.
1017 BitVector Todo = SA->getThroughBlocks();
1018 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1019 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1020 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1021 unsigned Number = Blocks[i];
1022 if (!Todo.test(Number))
1023 continue;
1024 Todo.reset(Number);
1025
1026 unsigned IntvIn = 0, IntvOut = 0;
1027 SlotIndex IntfIn, IntfOut;
1028
1029 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1030 if (CandIn != NoCand) {
1031 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1032 IntvIn = Cand.IntvIdx;
1033 Cand.Intf.moveToBlock(Number);
1034 IntfIn = Cand.Intf.first();
1035 }
1036
1037 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1038 if (CandOut != NoCand) {
1039 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1040 IntvOut = Cand.IntvIdx;
1041 Cand.Intf.moveToBlock(Number);
1042 IntfOut = Cand.Intf.last();
1043 }
1044 if (!IntvIn && !IntvOut)
1045 continue;
1046 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1047 }
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001048 }
1049
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001050 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001051
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001052 SmallVector<unsigned, 8> IntvMap;
1053 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001054 DebugVars->splitRegister(Reg, LREdit.regs());
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001055
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001056 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesenb2abfa02011-05-28 02:32:57 +00001057 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001058
1059 // Sort out the new intervals created by splitting. We get four kinds:
1060 // - Remainder intervals should not be split again.
1061 // - Candidate intervals can be assigned to Cand.PhysReg.
1062 // - Block-local splits are candidates for local splitting.
1063 // - DCE leftovers should go back on the queue.
1064 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001065 LiveInterval &Reg = *LREdit.get(i);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001066
1067 // Ignore old intervals from DCE.
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001068 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001069 continue;
1070
1071 // Remainder interval. Don't try splitting again, spill if it doesn't
1072 // allocate.
1073 if (IntvMap[i] == 0) {
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001074 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001075 continue;
1076 }
1077
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001078 // Global intervals. Allow repeated splitting as long as the number of live
1079 // blocks is strictly decreasing.
1080 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001081 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001082 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1083 << " blocks as original.\n");
1084 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001085 setStage(Reg, RS_Split2);
Jakob Stoklund Olesen9f4b8932011-04-26 22:33:12 +00001086 }
1087 continue;
1088 }
1089
1090 // Other intervals are treated as new. This includes local intervals created
1091 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen59280462011-04-21 18:38:15 +00001092 }
1093
Jakob Stoklund Oleseneb291572011-03-27 22:49:21 +00001094 if (VerifyEnabled)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001095 MF->verify(this, "After splitting live range around region");
1096}
1097
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001098unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1099 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001100 unsigned NumCands = 0;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001101 unsigned BestCand = NoCand;
1102 float BestCost;
1103 SmallVector<unsigned, 8> UsedCands;
1104
1105 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesena16a25d2011-09-12 16:54:42 +00001106 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001107 if (HasCompact) {
1108 // Yes, keep GlobalCand[0] as the compact region candidate.
1109 NumCands = 1;
1110 BestCost = HUGE_VALF;
1111 } else {
1112 // No benefit from the compact region, our fallback will be per-block
1113 // splitting. Make sure we find a solution that is cheaper than spilling.
1114 BestCost = Hysteresis * calcSpillCost();
1115 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1116 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001117
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001118 Order.rewind();
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001119 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001120 // Discard bad candidates before we run out of interference cache cursors.
1121 // This will only affect register classes with a lot of registers (>32).
1122 if (NumCands == IntfCache.getMaxCursors()) {
1123 unsigned WorstCount = ~0u;
1124 unsigned Worst = 0;
1125 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001126 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001127 continue;
1128 unsigned Count = GlobalCand[i].LiveBundles.count();
1129 if (Count < WorstCount)
1130 Worst = i, WorstCount = Count;
1131 }
1132 --NumCands;
1133 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen7bdf0062011-11-01 00:02:31 +00001134 if (BestCand == NumCands)
1135 BestCand = Worst;
Jakob Stoklund Olesenf1c70982011-07-14 05:35:11 +00001136 }
1137
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001138 if (GlobalCand.size() <= NumCands)
1139 GlobalCand.resize(NumCands+1);
1140 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1141 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +00001142
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001143 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001144 float Cost;
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001145 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001146 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen1b400e82011-04-06 21:32:38 +00001147 continue;
1148 }
Jakob Stoklund Olesenf4afdfc2011-04-09 02:59:09 +00001149 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001150 if (Cost >= BestCost) {
1151 DEBUG({
1152 if (BestCand == NoCand)
1153 dbgs() << " worse than no bundles\n";
1154 else
1155 dbgs() << " worse than "
1156 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1157 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001158 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001159 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001160 growRegion(Cand);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001161
Jakob Stoklund Olesen9efa2a22011-04-06 19:13:57 +00001162 SpillPlacer->finish();
1163
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001164 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001165 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001166 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001167 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001168 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001169
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001170 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001171 DEBUG({
1172 dbgs() << ", total = " << Cost << " with bundles";
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001173 for (int i = Cand.LiveBundles.find_first(); i>=0;
1174 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +00001175 dbgs() << " EB#" << i;
1176 dbgs() << ".\n";
1177 });
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001178 if (Cost < BestCost) {
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001179 BestCand = NumCands;
Jakob Stoklund Olesen20072982011-04-22 22:47:40 +00001180 BestCost = Hysteresis * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001181 }
Jakob Stoklund Olesenc66a37d2011-07-14 00:17:10 +00001182 ++NumCands;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001183 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001184
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001185 // No solutions found, fall back to single block splitting.
1186 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001187 return 0;
1188
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001189 // Prepare split editor.
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001190 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001191 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001192
1193 // Assign all edge bundles to the preferred candidate, or NoCand.
1194 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1195
1196 // Assign bundles for the best candidate region.
1197 if (BestCand != NoCand) {
1198 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1199 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1200 UsedCands.push_back(BestCand);
1201 Cand.IntvIdx = SE->openIntv();
1202 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1203 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001204 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001205 }
1206 }
1207
1208 // Assign bundles for the compact region.
1209 if (HasCompact) {
1210 GlobalSplitCandidate &Cand = GlobalCand.front();
1211 assert(!Cand.PhysReg && "Compact region has no physreg");
1212 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1213 UsedCands.push_back(0);
1214 Cand.IntvIdx = SE->openIntv();
1215 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1216 << Cand.IntvIdx << ".\n");
Chandler Carruth32668ea2011-08-03 23:07:27 +00001217 (void)B;
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001218 }
1219 }
1220
1221 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001222 return 0;
1223}
1224
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001225
1226//===----------------------------------------------------------------------===//
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001227// Per-Block Splitting
1228//===----------------------------------------------------------------------===//
1229
1230/// tryBlockSplit - Split a global live range around every block with uses. This
1231/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1232/// they don't allocate.
1233unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1234 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1235 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1236 unsigned Reg = VirtReg.reg;
1237 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001238 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen708d06f2011-09-12 16:49:21 +00001239 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001240 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1241 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1242 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1243 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1244 SE->splitSingleBlock(BI);
1245 }
1246 // No blocks were split.
1247 if (LREdit.empty())
1248 return 0;
1249
1250 // We did split for some blocks.
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001251 SmallVector<unsigned, 8> IntvMap;
1252 SE->finish(&IntvMap);
Jakob Stoklund Olesen1f880422011-08-05 23:10:40 +00001253
1254 // Tell LiveDebugVariables about the new ranges.
1255 DebugVars->splitRegister(Reg, LREdit.regs());
1256
Jakob Stoklund Olesena9c41d32011-08-05 23:50:31 +00001257 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1258
1259 // Sort out the new intervals created by splitting. The remainder interval
1260 // goes straight to spilling, the new local ranges get to stay RS_New.
1261 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1262 LiveInterval &LI = *LREdit.get(i);
1263 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1264 setStage(LI, RS_Spill);
1265 }
1266
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001267 if (VerifyEnabled)
1268 MF->verify(this, "After splitting live range around basic blocks");
1269 return 0;
1270}
1271
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001272
1273//===----------------------------------------------------------------------===//
1274// Per-Instruction Splitting
1275//===----------------------------------------------------------------------===//
1276
1277/// tryInstructionSplit - Split a live range around individual instructions.
1278/// This is normally not worthwhile since the spiller is doing essentially the
1279/// same thing. However, when the live range is in a constrained register
1280/// class, it may help to insert copies such that parts of the live range can
1281/// be moved to a larger register class.
1282///
1283/// This is similar to spilling to a larger register class.
1284unsigned
1285RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1286 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1287 // There is no point to this if there are no larger sub-classes.
1288 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1289 return 0;
1290
1291 // Always enable split spill mode, since we're effectively spilling to a
1292 // register.
1293 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1294 SE->reset(LREdit, SplitEditor::SM_Size);
1295
1296 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1297 if (Uses.size() <= 1)
1298 return 0;
1299
1300 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1301
1302 // Split around every non-copy instruction.
1303 for (unsigned i = 0; i != Uses.size(); ++i) {
1304 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1305 if (MI->isFullCopy()) {
1306 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1307 continue;
1308 }
1309 SE->openIntv();
1310 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1311 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1312 SE->useIntv(SegStart, SegStop);
1313 }
1314
1315 if (LREdit.empty()) {
1316 DEBUG(dbgs() << "All uses were copies.\n");
1317 return 0;
1318 }
1319
1320 SmallVector<unsigned, 8> IntvMap;
1321 SE->finish(&IntvMap);
1322 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1323 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1324
1325 // Assign all new registers to RS_Spill. This was the last chance.
1326 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1327 return 0;
1328}
1329
1330
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001331//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001332// Local Splitting
1333//===----------------------------------------------------------------------===//
1334
1335
1336/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1337/// in order to use PhysReg between two entries in SA->UseSlots.
1338///
1339/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1340///
1341void RAGreedy::calcGapWeights(unsigned PhysReg,
1342 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001343 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1344 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001345 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001346 const unsigned NumGaps = Uses.size()-1;
1347
1348 // Start and end points for the interference check.
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001349 SlotIndex StartIdx =
1350 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1351 SlotIndex StopIdx =
1352 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001353
1354 GapWeight.assign(NumGaps, 0.0f);
1355
1356 // Add interference from each overlapping register.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001357 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1358 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1359 .checkInterference())
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001360 continue;
1361
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001362 // We know that VirtReg is a continuous interval from FirstInstr to
1363 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001364 //
1365 // Interference that overlaps an instruction is counted in both gaps
1366 // surrounding the instruction. The exception is interference before
1367 // StartIdx and after StopIdx.
1368 //
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001369 LiveIntervalUnion::SegmentIter IntI =
1370 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001371 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1372 // Skip the gaps before IntI.
1373 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1374 if (++Gap == NumGaps)
1375 break;
1376 if (Gap == NumGaps)
1377 break;
1378
1379 // Update the gaps covered by IntI.
1380 const float weight = IntI.value()->weight;
1381 for (; Gap != NumGaps; ++Gap) {
1382 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1383 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1384 break;
1385 }
1386 if (Gap == NumGaps)
1387 break;
1388 }
1389 }
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001390
1391 // Add fixed interference.
1392 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1393 const LiveInterval &LI = LIS->getRegUnit(*Units);
1394 LiveInterval::const_iterator I = LI.find(StartIdx);
1395 LiveInterval::const_iterator E = LI.end();
1396
1397 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1398 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1399 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1400 if (++Gap == NumGaps)
1401 break;
1402 if (Gap == NumGaps)
1403 break;
1404
1405 for (; Gap != NumGaps; ++Gap) {
1406 GapWeight[Gap] = HUGE_VALF;
1407 if (Uses[Gap+1].getBaseIndex() >= I->end)
1408 break;
1409 }
1410 if (Gap == NumGaps)
1411 break;
1412 }
1413 }
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001414}
1415
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001416/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1417/// basic block.
1418///
1419unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1420 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesendb529a82011-04-06 03:57:00 +00001421 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1422 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001423
1424 // Note that it is possible to have an interval that is live-in or live-out
1425 // while only covering a single block - A phi-def can use undef values from
1426 // predecessors, and the block could be a single-block loop.
1427 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesenfe62d922011-08-02 22:54:14 +00001428 // that the interval is continuous from FirstInstr to LastInstr. We should
1429 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001430
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001431 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001432 if (Uses.size() <= 2)
1433 return 0;
1434 const unsigned NumGaps = Uses.size()-1;
1435
1436 DEBUG({
1437 dbgs() << "tryLocalSplit: ";
1438 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesenb20b5182012-01-12 17:53:44 +00001439 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001440 dbgs() << '\n';
1441 });
1442
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001443 // If VirtReg is live across any register mask operands, compute a list of
1444 // gaps with register masks.
1445 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001446 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001447 // Get regmask slots for the whole block.
1448 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001449 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001450 // Constrain to VirtReg's live range.
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001451 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1452 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001453 unsigned re = RMS.size();
1454 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001455 // Look for Uses[i] <= RMS <= Uses[i+1].
1456 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1457 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001458 continue;
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001459 // Skip a regmask on the same instruction as the last use. It doesn't
1460 // overlap the live range.
1461 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1462 break;
1463 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001464 RegMaskGaps.push_back(i);
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001465 // Advance ri to the next gap. A regmask on one of the uses counts in
1466 // both gaps.
1467 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1468 ++ri;
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001469 }
Jakob Stoklund Olesencac5fa32012-02-14 23:51:27 +00001470 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001471 }
1472
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001473 // Since we allow local split results to be split again, there is a risk of
1474 // creating infinite loops. It is tempting to require that the new live
1475 // ranges have less instructions than the original. That would guarantee
1476 // convergence, but it is too strict. A live range with 3 instructions can be
1477 // split 2+3 (including the COPY), and we want to allow that.
1478 //
1479 // Instead we use these rules:
1480 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001481 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001482 // noop split, of course).
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001483 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001484 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001485 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001486 // smaller ranges are marked RS_New.
1487 //
1488 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1489 // excessive splitting and infinite loops.
1490 //
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001491 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001492
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001493 // Best split candidate.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001494 unsigned BestBefore = NumGaps;
1495 unsigned BestAfter = 0;
1496 float BestDiff = 0;
1497
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001498 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001499 SmallVector<float, 8> GapWeight;
1500
1501 Order.rewind();
1502 while (unsigned PhysReg = Order.next()) {
1503 // Keep track of the largest spill weight that would need to be evicted in
1504 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1505 calcGapWeights(PhysReg, GapWeight);
1506
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001507 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001508 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesena6d513f2012-02-11 00:42:18 +00001509 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1510 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1511
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001512 // Try to find the best sequence of gaps to close.
1513 // The new spill weight must be larger than any gap interference.
1514
1515 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001516 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001517
1518 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1519 // It is the spill weight that needs to be evicted.
1520 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001521
1522 for (;;) {
1523 // Live before/after split?
1524 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1525 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1526
1527 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1528 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1529 << " i=" << MaxGap);
1530
1531 // Stop before the interval gets so big we wouldn't be making progress.
1532 if (!LiveBefore && !LiveAfter) {
1533 DEBUG(dbgs() << " all\n");
1534 break;
1535 }
1536 // Should the interval be extended or shrunk?
1537 bool Shrink = true;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001538
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001539 // How many gaps would the new range have?
1540 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1541
1542 // Legally, without causing looping?
1543 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1544
1545 if (Legal && MaxGap < HUGE_VALF) {
1546 // Estimate the new spill weight. Each instruction reads or writes the
1547 // register. Conservatively assume there are no read-modify-write
1548 // instructions.
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001549 //
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001550 // Try to guess the size of the new interval.
1551 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1552 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1553 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001554 // Would this split be possible to allocate?
1555 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001556 DEBUG(dbgs() << " w=" << EstWeight);
1557 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001558 Shrink = false;
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001559 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001560 if (Diff > BestDiff) {
1561 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen66446c82011-04-30 05:07:46 +00001562 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001563 BestBefore = SplitBefore;
1564 BestAfter = SplitAfter;
1565 }
1566 }
1567 }
1568
1569 // Try to shrink.
1570 if (Shrink) {
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001571 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001572 DEBUG(dbgs() << " shrink\n");
1573 // Recompute the max when necessary.
1574 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1575 MaxGap = GapWeight[SplitBefore];
1576 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1577 MaxGap = std::max(MaxGap, GapWeight[i]);
1578 }
1579 continue;
1580 }
1581 MaxGap = 0;
1582 }
1583
1584 // Try to extend the interval.
1585 if (SplitAfter >= NumGaps) {
1586 DEBUG(dbgs() << " end\n");
1587 break;
1588 }
1589
1590 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001591 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001592 }
1593 }
1594
1595 // Didn't find any candidates?
1596 if (BestBefore == NumGaps)
1597 return 0;
1598
1599 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1600 << '-' << Uses[BestAfter] << ", " << BestDiff
1601 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1602
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001603 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001604 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001605
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001606 SE->openIntv();
1607 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1608 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1609 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001610 SmallVector<unsigned, 8> IntvMap;
1611 SE->finish(&IntvMap);
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001612 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001613
1614 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001615 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001616 // leave the new intervals as RS_New so they can compete.
1617 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1618 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1619 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1620 if (NewGaps >= NumGaps) {
1621 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1622 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001623 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1624 if (IntvMap[i] == 1) {
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001625 setStage(*LREdit.get(i), RS_Split2);
Jakob Stoklund Olesenb3e705f2011-06-06 23:55:20 +00001626 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1627 }
1628 DEBUG(dbgs() << '\n');
1629 }
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001630 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001631
1632 return 0;
1633}
1634
1635//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001636// Live Range Splitting
1637//===----------------------------------------------------------------------===//
1638
1639/// trySplit - Try to split VirtReg or one of its interferences, making it
1640/// assignable.
1641/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1642unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1643 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesenccfa4462011-08-05 23:50:33 +00001644 // Ranges must be Split2 or less.
1645 if (getStage(VirtReg) >= RS_Spill)
1646 return 0;
1647
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001648 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001649 if (LIS->intervalIsInOneMBB(VirtReg)) {
1650 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001651 SA->analyze(&VirtReg);
Jakob Stoklund Olesend74d2842012-05-23 22:37:27 +00001652 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1653 if (PhysReg || !NewVRegs.empty())
1654 return PhysReg;
1655 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001656 }
1657
1658 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001659
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001660 SA->analyze(&VirtReg);
1661
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001662 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1663 // coalescer. That may cause the range to become allocatable which means that
1664 // tryRegionSplit won't be making progress. This check should be replaced with
1665 // an assertion when the coalescer is fixed.
1666 if (SA->didRepairRange()) {
1667 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001668 Matrix->invalidateVirtRegs();
Jakob Stoklund Olesen7d6b6a02011-05-03 20:42:13 +00001669 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1670 return PhysReg;
1671 }
1672
Jakob Stoklund Olesen49743b12011-07-25 15:25:43 +00001673 // First try to split around a region spanning multiple blocks. RS_Split2
1674 // ranges already made dubious progress with region splitting, so they go
1675 // straight to single block splitting.
1676 if (getStage(VirtReg) < RS_Split2) {
1677 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1678 if (PhysReg || !NewVRegs.empty())
1679 return PhysReg;
1680 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001681
Jakob Stoklund Olesendab35d32011-08-05 23:04:18 +00001682 // Then isolate blocks.
1683 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001684}
1685
1686
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001687//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001688// Main Entry Point
1689//===----------------------------------------------------------------------===//
1690
1691unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001692 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001693 // First try assigning a free register.
Jakob Stoklund Olesen5f2316a2011-06-03 20:34:53 +00001694 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen6bfba2e2011-04-20 18:19:48 +00001695 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1696 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001697
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001698 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001699 DEBUG(dbgs() << StageName[Stage]
1700 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesenb8d936b2011-05-25 23:58:36 +00001701
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001702 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001703 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001704 // get a second chance until they have been split.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001705 if (Stage != RS_Split)
Jakob Stoklund Olesen76395c92011-06-01 18:45:02 +00001706 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1707 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001708
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001709 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1710
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001711 // The first time we see a live range, don't try to split or spill.
1712 // Wait until the second time, when all smaller ranges have been allocated.
1713 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001714 if (Stage < RS_Split) {
1715 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001716 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001717 NewVRegs.push_back(&VirtReg);
1718 return 0;
1719 }
1720
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001721 // If we couldn't allocate a register from spilling, there is probably some
1722 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001723 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesenbf4e10f2011-05-06 21:58:30 +00001724 return ~0u;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001725
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001726 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001727 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1728 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001729 return PhysReg;
1730
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001731 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001732 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen20942dc2012-05-19 05:25:46 +00001733 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001734 spiller().spill(LRE);
Jakob Stoklund Olesenfa89a032011-07-25 15:25:41 +00001735 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001736
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001737 if (VerifyEnabled)
1738 MF->verify(this, "After spilling");
1739
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001740 // The live virtual register requesting allocation was spilled, so tell
1741 // the caller not to allocate anything during this round.
1742 return 0;
1743}
1744
1745bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1746 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +00001747 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001748
1749 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001750 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001751 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001752
Jakob Stoklund Olesend4348a22012-06-20 22:52:29 +00001753 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1754 getAnalysis<LiveIntervals>(),
1755 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001756 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001757 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001758 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001759 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001760 Bundles = &getAnalysis<EdgeBundles>();
1761 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf42b6612011-05-06 18:00:02 +00001762 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001763
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001764 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001765 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen1a988002011-07-02 01:37:09 +00001766 ExtraRegInfo.clear();
1767 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1768 NextCascade = 1;
Jakob Stoklund Olesen042888d2012-06-20 22:52:26 +00001769 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesen00005782011-07-26 23:41:46 +00001770 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001771
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001772 allocatePhysRegs();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001773 releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001774 return true;
1775}