blob: 4590145a1c3140c3b80c45c51eb5447e62468fe7 [file] [log] [blame]
Jakob Stoklund Olesenb8812a12010-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 Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen4d7432e2010-12-10 22:21:05 +000017#include "AllocationOrder.h"
Jakob Stoklund Olesen91cbcaf2011-04-02 06:03:35 +000018#include "InterferenceCache.h"
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +000019#include "LiveDebugVariables.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000020#include "RegAllocBase.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "Spiller.h"
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +000023#include "SplitKit.h"
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000026#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000027#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000029#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000030#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000031#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000032#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000033#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000035#include "llvm/CodeGen/MachineLoopInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000037#include "llvm/CodeGen/RegAllocRegistry.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/CodeGen/VirtRegMap.h"
39#include "llvm/PassAnalysisSupport.h"
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +000040#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +000043#include "llvm/Support/Timer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000045#include <queue>
46
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000047using namespace llvm;
48
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000049STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000051STATISTIC(NumEvicted, "Number of interferences evicted");
52
Jakob Stoklund Oleseneecb2fb2011-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 Olesenb8812a12010-12-08 03:26:16 +000062static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
63 createGreedyRegisterAllocator);
64
65namespace {
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +000066class RAGreedy : public MachineFunctionPass,
67 public RegAllocBase,
68 private LiveRangeEdit::Delegate {
69
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000070 // context
71 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000072
73 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000074 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +000075 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000076 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +000077 MachineLoopInfo *Loops;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000078 EdgeBundles *Bundles;
79 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +000080 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000081
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000082 // state
Andy Gibbs95777552013-04-12 10:56:28 +000083 OwningPtr<Spiller> SpillerInstance;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000084 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +000085 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +000086
87 // Live ranges pass through a number of stages as we try to allocate them.
88 // Some of the stages may also create new live ranges:
89 //
90 // - Region splitting.
91 // - Per-block splitting.
92 // - Local splitting.
93 // - Spilling.
94 //
95 // Ranges produced by one of the stages skip the previous stages when they are
96 // dequeued. This improves performance because we can skip interference checks
97 // that are unlikely to give any results. It also guarantees that the live
98 // range splitting algorithm terminates, something that is otherwise hard to
99 // ensure.
100 enum LiveRangeStage {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000101 /// Newly created live range that has never been queued.
102 RS_New,
103
104 /// Only attempt assignment and eviction. Then requeue as RS_Split.
105 RS_Assign,
106
107 /// Attempt live range splitting if assignment is impossible.
108 RS_Split,
109
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000110 /// Attempt more aggressive live range splitting that is guaranteed to make
111 /// progress. This is used for split products that may not be making
112 /// progress.
113 RS_Split2,
114
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000115 /// Live range will be spilled. No more splitting will be attempted.
116 RS_Spill,
117
118 /// There is nothing more we can do to this live range. Abort compilation
119 /// if it can't be assigned.
120 RS_Done
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000121 };
122
Eli Friedman78bffa52013-09-10 23:18:14 +0000123#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000124 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000125#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000126
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000127 // RegInfo - Keep additional information about each live range.
128 struct RegInfo {
129 LiveRangeStage Stage;
130
131 // Cascade - Eviction loop prevention. See canEvictInterference().
132 unsigned Cascade;
133
134 RegInfo() : Stage(RS_New), Cascade(0) {}
135 };
136
137 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000138
139 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000140 return ExtraRegInfo[VirtReg.reg].Stage;
141 }
142
143 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
144 ExtraRegInfo.resize(MRI->getNumVirtRegs());
145 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000146 }
147
148 template<typename Iterator>
149 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000150 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000151 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000152 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000153 if (ExtraRegInfo[Reg].Stage == RS_New)
154 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000155 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000156 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000157
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000158 /// Cost of evicting interference.
159 struct EvictionCost {
160 unsigned BrokenHints; ///< Total number of broken hints.
161 float MaxWeight; ///< Maximum spill weight evicted.
162
Andrew Trick3621b8a2013-11-22 19:07:38 +0000163 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000164
Andrew Trick84852572013-07-25 18:35:14 +0000165 bool isMax() const { return BrokenHints == ~0u; }
166
Andrew Trick3621b8a2013-11-22 19:07:38 +0000167 void setMax() { BrokenHints = ~0u; }
168
169 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
170
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000171 bool operator<(const EvictionCost &O) const {
172 if (BrokenHints != O.BrokenHints)
173 return BrokenHints < O.BrokenHints;
174 return MaxWeight < O.MaxWeight;
175 }
176 };
177
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000178 // splitting state.
Andy Gibbs95777552013-04-12 10:56:28 +0000179 OwningPtr<SplitAnalysis> SA;
180 OwningPtr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000181
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000182 /// Cached per-block interference maps
183 InterferenceCache IntfCache;
184
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000185 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000186 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000187
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000188 /// Global live range splitting candidate info.
189 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000190 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000191 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000192
193 // SplitKit interval index for this candidate.
194 unsigned IntvIdx;
195
196 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000197 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000198
199 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000200 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000201 SmallVector<unsigned, 8> ActiveBlocks;
202
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000203 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000204 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000205 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000206 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000207 LiveBundles.clear();
208 ActiveBlocks.clear();
209 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000210
211 // Set B[i] = C for every live bundle where B[i] was NoCand.
212 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
213 unsigned Count = 0;
214 for (int i = LiveBundles.find_first(); i >= 0;
215 i = LiveBundles.find_next(i))
216 if (B[i] == NoCand) {
217 B[i] = C;
218 Count++;
219 }
220 return Count;
221 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000222 };
223
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000224 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000225 /// This vector never shrinks, but grows to the size of the largest register
226 /// class.
227 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
228
Reid Klecknercd4a25d2013-10-08 20:15:11 +0000229 enum LLVM_ENUM_INT_TYPE(unsigned) { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000230
231 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
232 /// NoCand which indicates the stack interval.
233 SmallVector<unsigned, 32> BundleCand;
234
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000235public:
236 RAGreedy();
237
238 /// Return the pass name.
239 virtual const char* getPassName() const {
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +0000240 return "Greedy Register Allocator";
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000241 }
242
243 /// RAGreedy analysis usage.
244 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000245 virtual void releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000246 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000247 virtual void enqueue(LiveInterval *LI);
248 virtual LiveInterval *dequeue();
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +0000249 virtual unsigned selectOrSplit(LiveInterval&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000250 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000251
252 /// Perform register allocation.
253 virtual bool runOnMachineFunction(MachineFunction &mf);
254
255 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000256
257private:
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000258 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000259 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000260 void LRE_DidCloneVirtReg(unsigned, unsigned);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000261
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000262 BlockFrequency calcSpillCost();
263 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000264 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000265 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000266 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000267 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000268 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000269 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000270 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000271 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
272 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
273 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000274 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000275
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000276 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000277 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000278 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000279 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000280 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000281 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000282 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000283 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000284 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000285 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000286 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000287 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000288 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000289 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000290};
291} // end anonymous namespace
292
293char RAGreedy::ID = 0;
294
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000295#ifndef NDEBUG
296const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000297 "RS_New",
298 "RS_Assign",
299 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000300 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000301 "RS_Spill",
302 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000303};
304#endif
305
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000306// Hysteresis to use when comparing floats.
307// This helps stabilize decisions based on float comparisons.
308const float Hysteresis = 0.98f;
309
310
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000311FunctionPass* llvm::createGreedyRegisterAllocator() {
312 return new RAGreedy();
313}
314
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000315RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000316 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000317 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000318 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
319 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola676c4052011-06-26 22:34:10 +0000320 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Tricke1c034f2012-01-17 06:55:03 +0000321 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000322 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
323 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
324 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
325 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000326 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000327 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
328 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000329}
330
331void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
332 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000333 AU.addRequired<MachineBlockFrequencyInfo>();
334 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000335 AU.addRequired<AliasAnalysis>();
336 AU.addPreserved<AliasAnalysis>();
337 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000338 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000339 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000340 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000341 AU.addRequired<LiveDebugVariables>();
342 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000343 AU.addRequired<LiveStacks>();
344 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000345 AU.addRequired<MachineDominatorTree>();
346 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000347 AU.addRequired<MachineLoopInfo>();
348 AU.addPreserved<MachineLoopInfo>();
349 AU.addRequired<VirtRegMap>();
350 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000351 AU.addRequired<LiveRegMatrix>();
352 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000353 AU.addRequired<EdgeBundles>();
354 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000355 MachineFunctionPass::getAnalysisUsage(AU);
356}
357
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000358
359//===----------------------------------------------------------------------===//
360// LiveRangeEdit delegate methods
361//===----------------------------------------------------------------------===//
362
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000363bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000364 if (VRM->hasPhys(VirtReg)) {
365 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000366 return true;
367 }
368 // Unassigned virtreg is probably in the priority queue.
369 // RegAllocBase will erase it after dequeueing.
370 return false;
371}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000372
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000373void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000374 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000375 return;
376
377 // Register is assigned, put it back on the queue for reassignment.
378 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000379 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000380 enqueue(&LI);
381}
382
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000383void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000384 // Cloning a register we haven't even heard about yet? Just ignore it.
385 if (!ExtraRegInfo.inBounds(Old))
386 return;
387
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000388 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000389 // be split into connected components. The new components are much smaller
390 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000391 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000392 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000393 ExtraRegInfo.grow(New);
394 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000395}
396
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000397void RAGreedy::releaseMemory() {
398 SpillerInstance.reset(0);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000399 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000400 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000401}
402
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000403void RAGreedy::enqueue(LiveInterval *LI) {
404 // Prioritize live ranges by size, assigning larger ranges first.
405 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000406 const unsigned Size = LI->getSize();
407 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000408 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
409 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000410 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000411
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000412 ExtraRegInfo.grow(Reg);
413 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000414 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000415
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000416 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000417 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000418 // everything else has been allocated.
419 Prio = Size;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000420 } else {
Andrew Trick84852572013-07-25 18:35:14 +0000421 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
422 LIS->intervalIsInOneMBB(*LI)) {
423 // Allocate original local ranges in linear instruction order. Since they
424 // are singly defined, this produces optimal coloring in the absence of
425 // global interference and other constraints.
Andrew Trick2d8826a2013-12-11 03:40:15 +0000426 if (!TRI->reverseLocalAssignment())
427 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
428 else {
429 // Allocating bottom up may allow many short LRGs to be assigned first
430 // to one of the cheap registers. This could be much faster for very
431 // large blocks on targets with many physical registers.
432 Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
433 }
Andrew Trick84852572013-07-25 18:35:14 +0000434 }
435 else {
436 // Allocate global and split ranges in long->short order. Long ranges that
437 // don't fit should be spilled (or split) ASAP so they don't create
438 // interference. Mark a bit to prioritize global above local ranges.
439 Prio = (1u << 29) + Size;
440 }
441 // Mark a higher bit to prioritize global and local above RS_Split.
442 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000443
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000444 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000445 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000446 Prio |= (1u << 30);
447 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000448 // The virtual register number is a tie breaker for same-sized ranges.
449 // Give lower vreg numbers higher priority to assign them first.
Jakob Stoklund Olesen291007b2012-04-02 22:30:39 +0000450 Queue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000451}
452
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000453LiveInterval *RAGreedy::dequeue() {
454 if (Queue.empty())
455 return 0;
Jakob Stoklund Olesen291007b2012-04-02 22:30:39 +0000456 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000457 Queue.pop();
458 return LI;
459}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000460
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000461
462//===----------------------------------------------------------------------===//
463// Direct Assignment
464//===----------------------------------------------------------------------===//
465
466/// tryAssign - Try to assign VirtReg to an available register.
467unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
468 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000469 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000470 Order.rewind();
471 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000472 while ((PhysReg = Order.next()))
473 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000474 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000475 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000476 return PhysReg;
477
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000478 // PhysReg is available, but there may be a better choice.
479
480 // If we missed a simple hint, try to cheaply evict interference from the
481 // preferred register.
482 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000483 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000484 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000485 EvictionCost MaxCost;
486 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000487 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
488 evictInterference(VirtReg, Hint, NewVRegs);
489 return Hint;
490 }
491 }
492
493 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000494 unsigned Cost = TRI->getCostPerUse(PhysReg);
495
496 // Most registers have 0 additional cost.
497 if (!Cost)
498 return PhysReg;
499
500 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
501 << '\n');
502 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
503 return CheapReg ? CheapReg : PhysReg;
504}
505
506
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000507//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000508// Interference eviction
509//===----------------------------------------------------------------------===//
510
Andrew Trick8bb0a252013-07-25 18:35:19 +0000511unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
512 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
513 unsigned PhysReg;
514 while ((PhysReg = Order.next())) {
515 if (PhysReg == PrevReg)
516 continue;
517
518 MCRegUnitIterator Units(PhysReg, TRI);
519 for (; Units.isValid(); ++Units) {
520 // Instantiate a "subquery", not to be confused with the Queries array.
521 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
522 if (subQ.checkInterference())
523 break;
524 }
525 // If no units have interference, break out with the current PhysReg.
526 if (!Units.isValid())
527 break;
528 }
529 if (PhysReg)
530 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
531 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
532 << '\n');
533 return PhysReg;
534}
535
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000536/// shouldEvict - determine if A should evict the assigned live range B. The
537/// eviction policy defined by this function together with the allocation order
538/// defined by enqueue() decides which registers ultimately end up being split
539/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000540///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000541/// Cascade numbers are used to prevent infinite loops if this function is a
542/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000543///
544/// @param A The live range to be assigned.
545/// @param IsHint True when A is about to be assigned to its preferred
546/// register.
547/// @param B The live range to be evicted.
548/// @param BreaksHint True when B is already assigned to its preferred register.
549bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
550 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000551 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000552
553 // Be fairly aggressive about following hints as long as the evictee can be
554 // split.
555 if (CanSplit && IsHint && !BreaksHint)
556 return true;
557
Andrew Trick059e8002013-11-22 19:07:42 +0000558 if (A.weight > B.weight) {
559 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
560 return true;
561 }
562 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000563}
564
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000565/// canEvictInterference - Return true if all interferences between VirtReg and
566/// PhysReg can be evicted. When OnlyCheap is set, don't do anything
567///
568/// @param VirtReg Live range that is about to be assigned.
569/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000570/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000571/// @param MaxCost Only look for cheaper candidates and update with new cost
572/// when returning true.
573/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000574bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000575 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000576 // It is only possible to evict virtual register interference.
577 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
578 return false;
579
Andrew Trick84852572013-07-25 18:35:14 +0000580 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
581
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000582 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
583 // involved in an eviction before. If a cascade number was assigned, deny
584 // evicting anything with the same or a newer cascade number. This prevents
585 // infinite eviction loops.
586 //
587 // This works out so a register without a cascade number is allowed to evict
588 // anything, and it can be evicted by anything.
589 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
590 if (!Cascade)
591 Cascade = NextCascade;
592
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000593 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000594 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
595 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000596 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000597 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000598 return false;
599
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000600 // Check if any interfering live range is heavier than MaxWeight.
601 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
602 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000603 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
604 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000605 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000606 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000607 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000608 // Once a live range becomes small enough, it is urgent that we find a
609 // register for it. This is indicated by an infinite spill weight. These
610 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000611 //
612 // Also allow urgent evictions of unspillable ranges from a strictly
613 // larger allocation order.
614 bool Urgent = !VirtReg.isSpillable() &&
615 (Intf->isSpillable() ||
616 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
617 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000618 // Only evict older cascades or live ranges without a cascade.
619 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
620 if (Cascade <= IntfCascade) {
621 if (!Urgent)
622 return false;
623 // We permit breaking cascades for urgent evictions. It should be the
624 // last resort, though, so make it really expensive.
625 Cost.BrokenHints += 10;
626 }
627 // Would this break a satisfied hint?
628 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
629 // Update eviction cost.
630 Cost.BrokenHints += BreaksHint;
631 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
632 // Abort if this would be too expensive.
633 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000634 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000635 if (Urgent)
636 continue;
Andrew Trickc2ab53a2013-11-29 23:49:38 +0000637 // Apply the eviction policy for non-urgent evictions.
638 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
639 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000640 // If !MaxCost.isMax(), then we're just looking for a cheap register.
641 // Evicting another local live range in this case could lead to suboptimal
642 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000643 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
644 !canReassign(*Intf, PhysReg)) {
Andrew Trick84852572013-07-25 18:35:14 +0000645 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000646 }
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000647 }
648 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000649 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000650 return true;
651}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000652
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000653/// evictInterference - Evict any interferring registers that prevent VirtReg
654/// from being assigned to Physreg. This assumes that canEvictInterference
655/// returned true.
656void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000657 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000658 // Make sure that VirtReg has a cascade number, and assign that cascade
659 // number to every evicted register. These live ranges than then only be
660 // evicted by a newer cascade, preventing infinite loops.
661 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
662 if (!Cascade)
663 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
664
665 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
666 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000667
668 // Collect all interfering virtregs first.
669 SmallVector<LiveInterval*, 8> Intfs;
670 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
671 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000672 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000673 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
674 Intfs.append(IVR.begin(), IVR.end());
675 }
676
677 // Evict them second. This will invalidate the queries.
678 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
679 LiveInterval *Intf = Intfs[i];
680 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
681 if (!VRM->hasPhys(Intf->reg))
682 continue;
683 Matrix->unassign(*Intf);
684 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
685 VirtReg.isSpillable() < Intf->isSpillable()) &&
686 "Cannot decrease cascade number, illegal eviction");
687 ExtraRegInfo[Intf->reg].Cascade = Cascade;
688 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +0000689 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000690 }
691}
692
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000693/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +0000694/// @param VirtReg Currently unassigned virtual register.
695/// @param Order Physregs to try.
696/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000697unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
698 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000699 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000700 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000701 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
702
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000703 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +0000704 EvictionCost BestCost;
705 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000706 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000707 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000708
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000709 // When we are just looking for a reduced cost per use, don't break any
710 // hints, and only evict smaller spill weights.
711 if (CostPerUseLimit < ~0u) {
712 BestCost.BrokenHints = 0;
713 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000714
715 // Check of any registers in RC are below CostPerUseLimit.
716 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
717 unsigned MinCost = RegClassInfo.getMinCost(RC);
718 if (MinCost >= CostPerUseLimit) {
719 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
720 << ", no cheaper registers to be found.\n");
721 return 0;
722 }
723
724 // It is normal for register classes to have a long tail of registers with
725 // the same cost. We don't need to look at them if they're too expensive.
726 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
727 OrderLimit = RegClassInfo.getLastCostChange(RC);
728 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
729 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000730 }
731
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000732 Order.rewind();
Aditya Nandakumar73f3d332013-12-05 21:18:40 +0000733 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000734 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
735 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000736 // The first use of a callee-saved register in a function has cost 1.
737 // Don't start using a CSR when the CostPerUseLimit is low.
738 if (CostPerUseLimit == 1)
739 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
740 if (!MRI->isPhysRegUsed(CSR)) {
741 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
742 << PrintReg(CSR, TRI) << '\n');
743 continue;
744 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000745
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000746 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000747 continue;
748
749 // Best so far.
750 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000751
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000752 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000753 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000754 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000755 }
756
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000757 if (!BestPhys)
758 return 0;
759
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000760 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000761 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +0000762}
763
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000764
765//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000766// Region Splitting
767//===----------------------------------------------------------------------===//
768
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000769/// addSplitConstraints - Fill out the SplitConstraints vector based on the
770/// interference pattern in Physreg and its aliases. Add the constraints to
771/// SpillPlacement and return the static cost of this split in Cost, assuming
772/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000773/// Return false if there are no bundles with positive bias.
774bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000775 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000776 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000777
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000778 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000779 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000780 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000781 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
782 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000783 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000784
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +0000785 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000786 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000787 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
788 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +0000789 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000790
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000791 if (!Intf.hasInterference())
792 continue;
793
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000794 // Number of spill code instructions to insert.
795 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000796
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000797 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000798 if (BI.LiveIn) {
Jakob Stoklund Olesen89339072011-04-04 15:32:15 +0000799 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000800 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000801 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000802 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000803 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000804 ++Ins;
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +0000805 }
806
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000807 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000808 if (BI.LiveOut) {
Jakob Stoklund Olesend93b0e32011-04-05 04:20:29 +0000809 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000810 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000811 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000812 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000813 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000814 ++Ins;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000815 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000816
817 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000818 while (Ins--)
819 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000820 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000821 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000822
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000823 // Add constraints for use-blocks. Note that these are the only constraints
824 // that may add a positive bias, it is downhill from here.
825 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000826 return SpillPlacer->scanActiveBundles();
827}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000828
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000829
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000830/// addThroughConstraints - Add constraints and links to SpillPlacer from the
831/// live-through blocks in Blocks.
832void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
833 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000834 const unsigned GroupSize = 8;
835 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000836 unsigned TBS[GroupSize];
837 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000838
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000839 for (unsigned i = 0; i != Blocks.size(); ++i) {
840 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000841 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000842
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000843 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000844 assert(T < GroupSize && "Array overflow");
845 TBS[T] = Number;
846 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000847 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000848 T = 0;
849 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000850 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000851 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000852
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000853 assert(B < GroupSize && "Array overflow");
854 BCS[B].Number = Number;
855
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000856 // Interference for the live-in value.
857 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
858 BCS[B].Entry = SpillPlacement::MustSpill;
859 else
860 BCS[B].Entry = SpillPlacement::PrefSpill;
861
862 // Interference for the live-out value.
863 if (Intf.last() >= SA->getLastSplitPoint(Number))
864 BCS[B].Exit = SpillPlacement::MustSpill;
865 else
866 BCS[B].Exit = SpillPlacement::PrefSpill;
867
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000868 if (++B == GroupSize) {
869 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
870 SpillPlacer->addConstraints(Array);
871 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000872 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000873 }
874
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000875 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
876 SpillPlacer->addConstraints(Array);
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000877 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000878}
879
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000880void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000881 // Keep track of through blocks that have not been added to SpillPlacer.
882 BitVector Todo = SA->getThroughBlocks();
883 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
884 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000885#ifndef NDEBUG
886 unsigned Visited = 0;
887#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000888
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000889 for (;;) {
890 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000891 // Find new through blocks in the periphery of PrefRegBundles.
892 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
893 unsigned Bundle = NewBundles[i];
894 // Look at all blocks connected to Bundle in the full graph.
895 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
896 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
897 I != E; ++I) {
898 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000899 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000900 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000901 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000902 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000903 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000904#ifndef NDEBUG
905 ++Visited;
906#endif
907 }
908 }
909 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +0000910 if (ActiveBlocks.size() == AddedTo)
911 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +0000912
913 // Compute through constraints from the interference, or assume that all
914 // through blocks prefer spilling when forming compact regions.
915 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
916 if (Cand.PhysReg)
917 addThroughConstraints(Cand.Intf, NewBlocks);
918 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +0000919 // Provide a strong negative bias on through blocks to prevent unwanted
920 // liveness on loop backedges.
921 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +0000922 AddedTo = ActiveBlocks.size();
923
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000924 // Perhaps iterating can enable more bundles?
925 SpillPlacer->iterate();
926 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000927 DEBUG(dbgs() << ", v=" << Visited);
928}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000929
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000930/// calcCompactRegion - Compute the set of edge bundles that should be live
931/// when splitting the current live range into compact regions. Compact
932/// regions can be computed without looking at interference. They are the
933/// regions formed by removing all the live-through blocks from the live range.
934///
935/// Returns false if the current live range is already compact, or if the
936/// compact regions would form single block regions anyway.
937bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
938 // Without any through blocks, the live range is already compact.
939 if (!SA->getNumThroughBlocks())
940 return false;
941
942 // Compact regions don't correspond to any physreg.
943 Cand.reset(IntfCache, 0);
944
945 DEBUG(dbgs() << "Compact region bundles");
946
947 // Use the spill placer to determine the live bundles. GrowRegion pretends
948 // that all the through blocks have interference when PhysReg is unset.
949 SpillPlacer->prepare(Cand.LiveBundles);
950
951 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000952 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000953 if (!addSplitConstraints(Cand.Intf, Cost)) {
954 DEBUG(dbgs() << ", none.\n");
955 return false;
956 }
957
958 growRegion(Cand);
959 SpillPlacer->finish();
960
961 if (!Cand.LiveBundles.any()) {
962 DEBUG(dbgs() << ", none.\n");
963 return false;
964 }
965
966 DEBUG({
967 for (int i = Cand.LiveBundles.find_first(); i>=0;
968 i = Cand.LiveBundles.find_next(i))
969 dbgs() << " EB#" << i;
970 dbgs() << ".\n";
971 });
972 return true;
973}
974
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000975/// calcSpillCost - Compute how expensive it would be to split the live range in
976/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000977BlockFrequency RAGreedy::calcSpillCost() {
978 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000979 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
980 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
981 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
982 unsigned Number = BI.MBB->getNumber();
983 // We normally only need one spill instruction - a load or a store.
984 Cost += SpillPlacer->getBlockFrequency(Number);
985
986 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +0000987 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
988 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000989 }
990 return Cost;
991}
992
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000993/// calcGlobalSplitCost - Return the global split cost of following the split
994/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000995/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000996///
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000997BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
998 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000999 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001000 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1001 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1002 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001003 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001004 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1005 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1006 unsigned Ins = 0;
1007
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001008 if (BI.LiveIn)
1009 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1010 if (BI.LiveOut)
1011 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001012 while (Ins--)
1013 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001014 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001015
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001016 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1017 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001018 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1019 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001020 if (!RegIn && !RegOut)
1021 continue;
1022 if (RegIn && RegOut) {
1023 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001024 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001025 if (Cand.Intf.hasInterference()) {
1026 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1027 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1028 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001029 continue;
1030 }
1031 // live-in / stack-out or stack-in live-out.
1032 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001033 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001034 return GlobalCost;
1035}
1036
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001037/// splitAroundRegion - Split the current live range around the regions
1038/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001039///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001040/// Before calling this function, GlobalCand and BundleCand must be initialized
1041/// so each bundle is assigned to a valid candidate, or NoCand for the
1042/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1043/// objects must be initialized for the current live range, and intervals
1044/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001045///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001046/// @param LREdit The LiveRangeEdit object handling the current split.
1047/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1048/// must appear in this list.
1049void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1050 ArrayRef<unsigned> UsedCands) {
1051 // These are the intervals created for new global ranges. We may create more
1052 // intervals for local ranges.
1053 const unsigned NumGlobalIntvs = LREdit.size();
1054 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1055 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001056
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001057 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001058 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001059 // is all copies.
1060 unsigned Reg = SA->getParent().reg;
1061 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1062
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001063 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001064 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1065 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1066 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001067 unsigned Number = BI.MBB->getNumber();
1068 unsigned IntvIn = 0, IntvOut = 0;
1069 SlotIndex IntfIn, IntfOut;
1070 if (BI.LiveIn) {
1071 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1072 if (CandIn != NoCand) {
1073 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1074 IntvIn = Cand.IntvIdx;
1075 Cand.Intf.moveToBlock(Number);
1076 IntfIn = Cand.Intf.first();
1077 }
1078 }
1079 if (BI.LiveOut) {
1080 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1081 if (CandOut != NoCand) {
1082 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1083 IntvOut = Cand.IntvIdx;
1084 Cand.Intf.moveToBlock(Number);
1085 IntfOut = Cand.Intf.last();
1086 }
1087 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001088
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001089 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001090 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001091 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001092 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001093 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001094 continue;
1095 }
1096
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001097 if (IntvIn && IntvOut)
1098 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1099 else if (IntvIn)
1100 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001101 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001102 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001103 }
1104
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001105 // Handle live-through blocks. The relevant live-through blocks are stored in
1106 // the ActiveBlocks list with each candidate. We need to filter out
1107 // duplicates.
1108 BitVector Todo = SA->getThroughBlocks();
1109 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1110 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1111 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1112 unsigned Number = Blocks[i];
1113 if (!Todo.test(Number))
1114 continue;
1115 Todo.reset(Number);
1116
1117 unsigned IntvIn = 0, IntvOut = 0;
1118 SlotIndex IntfIn, IntfOut;
1119
1120 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1121 if (CandIn != NoCand) {
1122 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1123 IntvIn = Cand.IntvIdx;
1124 Cand.Intf.moveToBlock(Number);
1125 IntfIn = Cand.Intf.first();
1126 }
1127
1128 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1129 if (CandOut != NoCand) {
1130 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1131 IntvOut = Cand.IntvIdx;
1132 Cand.Intf.moveToBlock(Number);
1133 IntfOut = Cand.Intf.last();
1134 }
1135 if (!IntvIn && !IntvOut)
1136 continue;
1137 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1138 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001139 }
1140
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001141 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001142
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001143 SmallVector<unsigned, 8> IntvMap;
1144 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001145 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001146
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001147 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001148 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001149
1150 // Sort out the new intervals created by splitting. We get four kinds:
1151 // - Remainder intervals should not be split again.
1152 // - Candidate intervals can be assigned to Cand.PhysReg.
1153 // - Block-local splits are candidates for local splitting.
1154 // - DCE leftovers should go back on the queue.
1155 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001156 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001157
1158 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001159 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001160 continue;
1161
1162 // Remainder interval. Don't try splitting again, spill if it doesn't
1163 // allocate.
1164 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001165 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001166 continue;
1167 }
1168
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001169 // Global intervals. Allow repeated splitting as long as the number of live
1170 // blocks is strictly decreasing.
1171 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001172 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001173 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1174 << " blocks as original.\n");
1175 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001176 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001177 }
1178 continue;
1179 }
1180
1181 // Other intervals are treated as new. This includes local intervals created
1182 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001183 }
1184
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001185 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001186 MF->verify(this, "After splitting live range around region");
1187}
1188
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001189unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001190 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001191 unsigned NumCands = 0;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001192 unsigned BestCand = NoCand;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001193 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001194 SmallVector<unsigned, 8> UsedCands;
1195
1196 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001197 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001198 if (HasCompact) {
1199 // Yes, keep GlobalCand[0] as the compact region candidate.
1200 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001201 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001202 } else {
1203 // No benefit from the compact region, our fallback will be per-block
1204 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001205 BestCost = calcSpillCost();
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001206 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1207 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001208 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001209
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001210 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001211 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001212 // Discard bad candidates before we run out of interference cache cursors.
1213 // This will only affect register classes with a lot of registers (>32).
1214 if (NumCands == IntfCache.getMaxCursors()) {
1215 unsigned WorstCount = ~0u;
1216 unsigned Worst = 0;
1217 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001218 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001219 continue;
1220 unsigned Count = GlobalCand[i].LiveBundles.count();
1221 if (Count < WorstCount)
1222 Worst = i, WorstCount = Count;
1223 }
1224 --NumCands;
1225 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001226 if (BestCand == NumCands)
1227 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001228 }
1229
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001230 if (GlobalCand.size() <= NumCands)
1231 GlobalCand.resize(NumCands+1);
1232 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1233 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001234
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001235 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001236 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001237 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001238 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001239 continue;
1240 }
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001241 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1242 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001243 if (Cost >= BestCost) {
1244 DEBUG({
1245 if (BestCand == NoCand)
1246 dbgs() << " worse than no bundles\n";
1247 else
1248 dbgs() << " worse than "
1249 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1250 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001251 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001252 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001253 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001254
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001255 SpillPlacer->finish();
1256
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001257 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001258 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001259 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001260 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001261 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001262
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001263 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001264 DEBUG({
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001265 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1266 << " with bundles";
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001267 for (int i = Cand.LiveBundles.find_first(); i>=0;
1268 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001269 dbgs() << " EB#" << i;
1270 dbgs() << ".\n";
1271 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001272 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001273 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001274 BestCost = Cost;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001275 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001276 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001277 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001278
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001279 // No solutions found, fall back to single block splitting.
1280 if (!HasCompact && BestCand == NoCand)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001281 return 0;
1282
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001283 // Prepare split editor.
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001284 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001285 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001286
1287 // Assign all edge bundles to the preferred candidate, or NoCand.
1288 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1289
1290 // Assign bundles for the best candidate region.
1291 if (BestCand != NoCand) {
1292 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1293 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1294 UsedCands.push_back(BestCand);
1295 Cand.IntvIdx = SE->openIntv();
1296 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1297 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001298 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001299 }
1300 }
1301
1302 // Assign bundles for the compact region.
1303 if (HasCompact) {
1304 GlobalSplitCandidate &Cand = GlobalCand.front();
1305 assert(!Cand.PhysReg && "Compact region has no physreg");
1306 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1307 UsedCands.push_back(0);
1308 Cand.IntvIdx = SE->openIntv();
1309 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1310 << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001311 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001312 }
1313 }
1314
1315 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001316 return 0;
1317}
1318
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001319
1320//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001321// Per-Block Splitting
1322//===----------------------------------------------------------------------===//
1323
1324/// tryBlockSplit - Split a global live range around every block with uses. This
1325/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1326/// they don't allocate.
1327unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001328 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001329 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1330 unsigned Reg = VirtReg.reg;
1331 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001332 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001333 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001334 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1335 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1336 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1337 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1338 SE->splitSingleBlock(BI);
1339 }
1340 // No blocks were split.
1341 if (LREdit.empty())
1342 return 0;
1343
1344 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001345 SmallVector<unsigned, 8> IntvMap;
1346 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001347
1348 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00001349 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001350
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001351 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1352
1353 // Sort out the new intervals created by splitting. The remainder interval
1354 // goes straight to spilling, the new local ranges get to stay RS_New.
1355 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001356 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001357 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1358 setStage(LI, RS_Spill);
1359 }
1360
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001361 if (VerifyEnabled)
1362 MF->verify(this, "After splitting live range around basic blocks");
1363 return 0;
1364}
1365
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001366
1367//===----------------------------------------------------------------------===//
1368// Per-Instruction Splitting
1369//===----------------------------------------------------------------------===//
1370
1371/// tryInstructionSplit - Split a live range around individual instructions.
1372/// This is normally not worthwhile since the spiller is doing essentially the
1373/// same thing. However, when the live range is in a constrained register
1374/// class, it may help to insert copies such that parts of the live range can
1375/// be moved to a larger register class.
1376///
1377/// This is similar to spilling to a larger register class.
1378unsigned
1379RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001380 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001381 // There is no point to this if there are no larger sub-classes.
1382 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1383 return 0;
1384
1385 // Always enable split spill mode, since we're effectively spilling to a
1386 // register.
1387 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1388 SE->reset(LREdit, SplitEditor::SM_Size);
1389
1390 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1391 if (Uses.size() <= 1)
1392 return 0;
1393
1394 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1395
1396 // Split around every non-copy instruction.
1397 for (unsigned i = 0; i != Uses.size(); ++i) {
1398 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1399 if (MI->isFullCopy()) {
1400 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1401 continue;
1402 }
1403 SE->openIntv();
1404 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1405 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1406 SE->useIntv(SegStart, SegStop);
1407 }
1408
1409 if (LREdit.empty()) {
1410 DEBUG(dbgs() << "All uses were copies.\n");
1411 return 0;
1412 }
1413
1414 SmallVector<unsigned, 8> IntvMap;
1415 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001416 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001417 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1418
1419 // Assign all new registers to RS_Spill. This was the last chance.
1420 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1421 return 0;
1422}
1423
1424
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001425//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001426// Local Splitting
1427//===----------------------------------------------------------------------===//
1428
1429
1430/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1431/// in order to use PhysReg between two entries in SA->UseSlots.
1432///
1433/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1434///
1435void RAGreedy::calcGapWeights(unsigned PhysReg,
1436 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001437 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1438 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001439 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001440 const unsigned NumGaps = Uses.size()-1;
1441
1442 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001443 SlotIndex StartIdx =
1444 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1445 SlotIndex StopIdx =
1446 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001447
1448 GapWeight.assign(NumGaps, 0.0f);
1449
1450 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001451 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1452 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1453 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001454 continue;
1455
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001456 // We know that VirtReg is a continuous interval from FirstInstr to
1457 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001458 //
1459 // Interference that overlaps an instruction is counted in both gaps
1460 // surrounding the instruction. The exception is interference before
1461 // StartIdx and after StopIdx.
1462 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001463 LiveIntervalUnion::SegmentIter IntI =
1464 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001465 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1466 // Skip the gaps before IntI.
1467 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1468 if (++Gap == NumGaps)
1469 break;
1470 if (Gap == NumGaps)
1471 break;
1472
1473 // Update the gaps covered by IntI.
1474 const float weight = IntI.value()->weight;
1475 for (; Gap != NumGaps; ++Gap) {
1476 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1477 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1478 break;
1479 }
1480 if (Gap == NumGaps)
1481 break;
1482 }
1483 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001484
1485 // Add fixed interference.
1486 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001487 const LiveRange &LR = LIS->getRegUnit(*Units);
1488 LiveRange::const_iterator I = LR.find(StartIdx);
1489 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001490
1491 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1492 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1493 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1494 if (++Gap == NumGaps)
1495 break;
1496 if (Gap == NumGaps)
1497 break;
1498
1499 for (; Gap != NumGaps; ++Gap) {
Aaron Ballman04999042013-11-13 00:15:44 +00001500 GapWeight[Gap] = llvm::huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001501 if (Uses[Gap+1].getBaseIndex() >= I->end)
1502 break;
1503 }
1504 if (Gap == NumGaps)
1505 break;
1506 }
1507 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001508}
1509
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001510/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1511/// basic block.
1512///
1513unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001514 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001515 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1516 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001517
1518 // Note that it is possible to have an interval that is live-in or live-out
1519 // while only covering a single block - A phi-def can use undef values from
1520 // predecessors, and the block could be a single-block loop.
1521 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001522 // that the interval is continuous from FirstInstr to LastInstr. We should
1523 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001524
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001525 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001526 if (Uses.size() <= 2)
1527 return 0;
1528 const unsigned NumGaps = Uses.size()-1;
1529
1530 DEBUG({
1531 dbgs() << "tryLocalSplit: ";
1532 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001533 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001534 dbgs() << '\n';
1535 });
1536
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001537 // If VirtReg is live across any register mask operands, compute a list of
1538 // gaps with register masks.
1539 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001540 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001541 // Get regmask slots for the whole block.
1542 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001543 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001544 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001545 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1546 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001547 unsigned re = RMS.size();
1548 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001549 // Look for Uses[i] <= RMS <= Uses[i+1].
1550 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1551 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001552 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001553 // Skip a regmask on the same instruction as the last use. It doesn't
1554 // overlap the live range.
1555 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1556 break;
1557 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001558 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001559 // Advance ri to the next gap. A regmask on one of the uses counts in
1560 // both gaps.
1561 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1562 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001563 }
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001564 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001565 }
1566
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001567 // Since we allow local split results to be split again, there is a risk of
1568 // creating infinite loops. It is tempting to require that the new live
1569 // ranges have less instructions than the original. That would guarantee
1570 // convergence, but it is too strict. A live range with 3 instructions can be
1571 // split 2+3 (including the COPY), and we want to allow that.
1572 //
1573 // Instead we use these rules:
1574 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001575 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001576 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001577 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001578 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001579 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001580 // smaller ranges are marked RS_New.
1581 //
1582 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1583 // excessive splitting and infinite loops.
1584 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001585 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001586
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001587 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001588 unsigned BestBefore = NumGaps;
1589 unsigned BestAfter = 0;
1590 float BestDiff = 0;
1591
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001592 const float blockFreq =
1593 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001594 (1.0f / MBFI->getEntryFrequency());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001595 SmallVector<float, 8> GapWeight;
1596
1597 Order.rewind();
1598 while (unsigned PhysReg = Order.next()) {
1599 // Keep track of the largest spill weight that would need to be evicted in
1600 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1601 calcGapWeights(PhysReg, GapWeight);
1602
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001603 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001604 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001605 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Aaron Ballman04999042013-11-13 00:15:44 +00001606 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001607
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001608 // Try to find the best sequence of gaps to close.
1609 // The new spill weight must be larger than any gap interference.
1610
1611 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001612 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001613
1614 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1615 // It is the spill weight that needs to be evicted.
1616 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001617
1618 for (;;) {
1619 // Live before/after split?
1620 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1621 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1622
1623 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1624 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1625 << " i=" << MaxGap);
1626
1627 // Stop before the interval gets so big we wouldn't be making progress.
1628 if (!LiveBefore && !LiveAfter) {
1629 DEBUG(dbgs() << " all\n");
1630 break;
1631 }
1632 // Should the interval be extended or shrunk?
1633 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001634
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001635 // How many gaps would the new range have?
1636 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1637
1638 // Legally, without causing looping?
1639 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1640
Aaron Ballman04999042013-11-13 00:15:44 +00001641 if (Legal && MaxGap < llvm::huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001642 // Estimate the new spill weight. Each instruction reads or writes the
1643 // register. Conservatively assume there are no read-modify-write
1644 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001645 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001646 // Try to guess the size of the new interval.
1647 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1648 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1649 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001650 // Would this split be possible to allocate?
1651 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001652 DEBUG(dbgs() << " w=" << EstWeight);
1653 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001654 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001655 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001656 if (Diff > BestDiff) {
1657 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001658 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001659 BestBefore = SplitBefore;
1660 BestAfter = SplitAfter;
1661 }
1662 }
1663 }
1664
1665 // Try to shrink.
1666 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001667 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001668 DEBUG(dbgs() << " shrink\n");
1669 // Recompute the max when necessary.
1670 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1671 MaxGap = GapWeight[SplitBefore];
1672 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1673 MaxGap = std::max(MaxGap, GapWeight[i]);
1674 }
1675 continue;
1676 }
1677 MaxGap = 0;
1678 }
1679
1680 // Try to extend the interval.
1681 if (SplitAfter >= NumGaps) {
1682 DEBUG(dbgs() << " end\n");
1683 break;
1684 }
1685
1686 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001687 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001688 }
1689 }
1690
1691 // Didn't find any candidates?
1692 if (BestBefore == NumGaps)
1693 return 0;
1694
1695 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1696 << '-' << Uses[BestAfter] << ", " << BestDiff
1697 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1698
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001699 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001700 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001701
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001702 SE->openIntv();
1703 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1704 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1705 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001706 SmallVector<unsigned, 8> IntvMap;
1707 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001708 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001709
1710 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001711 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001712 // leave the new intervals as RS_New so they can compete.
1713 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1714 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1715 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1716 if (NewGaps >= NumGaps) {
1717 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1718 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001719 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1720 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001721 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1722 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001723 }
1724 DEBUG(dbgs() << '\n');
1725 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001726 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001727
1728 return 0;
1729}
1730
1731//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001732// Live Range Splitting
1733//===----------------------------------------------------------------------===//
1734
1735/// trySplit - Try to split VirtReg or one of its interferences, making it
1736/// assignable.
1737/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1738unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001739 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00001740 // Ranges must be Split2 or less.
1741 if (getStage(VirtReg) >= RS_Spill)
1742 return 0;
1743
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001744 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001745 if (LIS->intervalIsInOneMBB(VirtReg)) {
1746 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001747 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001748 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1749 if (PhysReg || !NewVRegs.empty())
1750 return PhysReg;
1751 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001752 }
1753
1754 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001755
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001756 SA->analyze(&VirtReg);
1757
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001758 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1759 // coalescer. That may cause the range to become allocatable which means that
1760 // tryRegionSplit won't be making progress. This check should be replaced with
1761 // an assertion when the coalescer is fixed.
1762 if (SA->didRepairRange()) {
1763 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001764 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001765 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1766 return PhysReg;
1767 }
1768
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001769 // First try to split around a region spanning multiple blocks. RS_Split2
1770 // ranges already made dubious progress with region splitting, so they go
1771 // straight to single block splitting.
1772 if (getStage(VirtReg) < RS_Split2) {
1773 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1774 if (PhysReg || !NewVRegs.empty())
1775 return PhysReg;
1776 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001777
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001778 // Then isolate blocks.
1779 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001780}
1781
1782
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001783//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001784// Main Entry Point
1785//===----------------------------------------------------------------------===//
1786
1787unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001788 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001789 // First try assigning a free register.
Jakob Stoklund Olesenb8bf3c02011-06-03 20:34:53 +00001790 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001791 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1792 return PhysReg;
Andrew Trickccef0982010-12-09 18:15:21 +00001793
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00001794 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001795 DEBUG(dbgs() << StageName[Stage]
1796 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00001797
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001798 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001799 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001800 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001801 if (Stage != RS_Split)
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001802 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1803 return PhysReg;
Andrew Trickccef0982010-12-09 18:15:21 +00001804
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001805 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1806
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00001807 // The first time we see a live range, don't try to split or spill.
1808 // Wait until the second time, when all smaller ranges have been allocated.
1809 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001810 if (Stage < RS_Split) {
1811 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +00001812 DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00001813 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00001814 return 0;
1815 }
1816
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00001817 // If we couldn't allocate a register from spilling, there is probably some
1818 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001819 if (Stage >= RS_Done || !VirtReg.isSpillable())
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00001820 return ~0u;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001821
Jakob Stoklund Olesen903b6d32010-12-14 00:37:49 +00001822 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001823 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1824 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +00001825 return PhysReg;
1826
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001827 // Finally spill VirtReg itself.
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +00001828 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001829 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen4d6eafa2011-03-10 01:51:42 +00001830 spiller().spill(LRE);
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001831 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001832
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00001833 if (VerifyEnabled)
1834 MF->verify(this, "After spilling");
1835
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001836 // The live virtual register requesting allocation was spilled, so tell
1837 // the caller not to allocate anything during this round.
1838 return 0;
1839}
1840
1841bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1842 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +00001843 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001844
1845 MF = &mf;
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00001846 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00001847 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00001848
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00001849 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1850 getAnalysis<LiveIntervals>(),
1851 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001852 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00001853 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00001854 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00001855 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00001856 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001857 Bundles = &getAnalysis<EdgeBundles>();
1858 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001859 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001860
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +00001861 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00001862
Andrew Trick97064962013-07-25 07:26:26 +00001863 DEBUG(LIS->dump());
1864
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00001865 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramere2a1d892013-06-17 19:00:36 +00001866 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001867 ExtraRegInfo.clear();
1868 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1869 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001870 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001871 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00001872
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001873 allocatePhysRegs();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001874 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00001875 return true;
1876}