blob: de528a7373561de60918124671e48a471572f977 [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"
Quentin Colombet1fb3362a2014-01-02 22:47:22 +000038#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/CodeGen/VirtRegMap.h"
Quentin Colombet96bd2a12014-04-04 02:05:21 +000040#include "llvm/IR/LLVMContext.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/PassAnalysisSupport.h"
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +000042#include "llvm/Support/BranchProbability.h"
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +000043#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000044#include "llvm/Support/Debug.h"
45#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +000046#include "llvm/Support/Timer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000047#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000048#include <queue>
49
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000050using namespace llvm;
51
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000052STATISTIC(NumGlobalSplits, "Number of split global live ranges");
53STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000054STATISTIC(NumEvicted, "Number of interferences evicted");
55
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +000056static cl::opt<SplitEditor::ComplementSpillMode>
57SplitSpillMode("split-spill-mode", cl::Hidden,
58 cl::desc("Spill mode for splitting live ranges"),
59 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
60 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
61 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
62 clEnumValEnd),
63 cl::init(SplitEditor::SM_Partition));
64
Quentin Colombet87769712014-02-05 22:13:59 +000065static cl::opt<unsigned>
66LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
67 cl::desc("Last chance recoloring max depth"),
68 cl::init(5));
69
70static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
71 "lcr-max-interf", cl::Hidden,
72 cl::desc("Last chance recoloring maximum number of considered"
73 " interference at a time"),
74 cl::init(8));
75
Quentin Colombet567e30b2014-04-11 21:39:44 +000076static cl::opt<bool>
Quentin Colombet4344da12014-04-11 21:51:09 +000077ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
Quentin Colombet567e30b2014-04-11 21:39:44 +000078 cl::desc("Exhaustive Search for registers bypassing the depth "
79 "and interference cutoffs of last chance recoloring"));
80
Manman Ren78cf02a2014-03-25 00:16:25 +000081// FIXME: Find a good default for this flag and remove the flag.
82static cl::opt<unsigned>
83CSRFirstTimeCost("regalloc-csr-first-time-cost",
84 cl::desc("Cost for first time use of callee-saved register."),
85 cl::init(0), cl::Hidden);
86
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000087static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
88 createGreedyRegisterAllocator);
89
90namespace {
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +000091class RAGreedy : public MachineFunctionPass,
92 public RegAllocBase,
93 private LiveRangeEdit::Delegate {
Quentin Colombet87769712014-02-05 22:13:59 +000094 // Convenient shortcuts.
95 typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
96 typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
97 typedef SmallSet<unsigned, 16> SmallVirtRegSet;
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +000098
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000099 // context
100 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000101
Quentin Colombet1fb3362a2014-01-02 22:47:22 +0000102 // Shortcuts to some useful interface.
103 const TargetInstrInfo *TII;
104 const TargetRegisterInfo *TRI;
105 RegisterClassInfo RCI;
106
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000107 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000108 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000109 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000110 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +0000111 MachineLoopInfo *Loops;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000112 EdgeBundles *Bundles;
113 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000114 LiveDebugVariables *DebugVars;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000115
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000116 // state
Ahmed Charles56440fd2014-03-06 05:51:42 +0000117 std::unique_ptr<Spiller> SpillerInstance;
Quentin Colombet87769712014-02-05 22:13:59 +0000118 PQueue Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000119 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000120
121 // Live ranges pass through a number of stages as we try to allocate them.
122 // Some of the stages may also create new live ranges:
123 //
124 // - Region splitting.
125 // - Per-block splitting.
126 // - Local splitting.
127 // - Spilling.
128 //
129 // Ranges produced by one of the stages skip the previous stages when they are
130 // dequeued. This improves performance because we can skip interference checks
131 // that are unlikely to give any results. It also guarantees that the live
132 // range splitting algorithm terminates, something that is otherwise hard to
133 // ensure.
134 enum LiveRangeStage {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000135 /// Newly created live range that has never been queued.
136 RS_New,
137
138 /// Only attempt assignment and eviction. Then requeue as RS_Split.
139 RS_Assign,
140
141 /// Attempt live range splitting if assignment is impossible.
142 RS_Split,
143
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000144 /// Attempt more aggressive live range splitting that is guaranteed to make
145 /// progress. This is used for split products that may not be making
146 /// progress.
147 RS_Split2,
148
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000149 /// Live range will be spilled. No more splitting will be attempted.
150 RS_Spill,
151
152 /// There is nothing more we can do to this live range. Abort compilation
153 /// if it can't be assigned.
154 RS_Done
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000155 };
156
Quentin Colombet96bd2a12014-04-04 02:05:21 +0000157 // Enum CutOffStage to keep a track whether the register allocation failed
158 // because of the cutoffs encountered in last chance recoloring.
159 // Note: This is used as bitmask. New value should be next power of 2.
160 enum CutOffStage {
161 // No cutoffs encountered
162 CO_None = 0,
163
164 // lcr-max-depth cutoff encountered
165 CO_Depth = 1,
166
167 // lcr-max-interf cutoff encountered
168 CO_Interf = 2
169 };
170
171 uint8_t CutOffInfo;
172
Eli Friedman78bffa52013-09-10 23:18:14 +0000173#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000174 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000175#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000176
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000177 // RegInfo - Keep additional information about each live range.
178 struct RegInfo {
179 LiveRangeStage Stage;
180
181 // Cascade - Eviction loop prevention. See canEvictInterference().
182 unsigned Cascade;
183
184 RegInfo() : Stage(RS_New), Cascade(0) {}
185 };
186
187 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000188
189 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000190 return ExtraRegInfo[VirtReg.reg].Stage;
191 }
192
193 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
194 ExtraRegInfo.resize(MRI->getNumVirtRegs());
195 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000196 }
197
198 template<typename Iterator>
199 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000200 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000201 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000202 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000203 if (ExtraRegInfo[Reg].Stage == RS_New)
204 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000205 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000206 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000207
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000208 /// Cost of evicting interference.
209 struct EvictionCost {
210 unsigned BrokenHints; ///< Total number of broken hints.
211 float MaxWeight; ///< Maximum spill weight evicted.
212
Andrew Trick3621b8a2013-11-22 19:07:38 +0000213 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000214
Andrew Trick84852572013-07-25 18:35:14 +0000215 bool isMax() const { return BrokenHints == ~0u; }
216
Andrew Trick3621b8a2013-11-22 19:07:38 +0000217 void setMax() { BrokenHints = ~0u; }
218
219 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
220
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000221 bool operator<(const EvictionCost &O) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +0000222 return std::tie(BrokenHints, MaxWeight) <
223 std::tie(O.BrokenHints, O.MaxWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000224 }
225 };
226
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000227 // splitting state.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000228 std::unique_ptr<SplitAnalysis> SA;
229 std::unique_ptr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000230
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000231 /// Cached per-block interference maps
232 InterferenceCache IntfCache;
233
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000234 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000235 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000236
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000237 /// Global live range splitting candidate info.
238 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000239 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000240 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000241
242 // SplitKit interval index for this candidate.
243 unsigned IntvIdx;
244
245 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000246 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000247
248 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000249 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000250 SmallVector<unsigned, 8> ActiveBlocks;
251
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000252 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000253 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000254 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000255 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000256 LiveBundles.clear();
257 ActiveBlocks.clear();
258 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000259
260 // Set B[i] = C for every live bundle where B[i] was NoCand.
261 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
262 unsigned Count = 0;
263 for (int i = LiveBundles.find_first(); i >= 0;
264 i = LiveBundles.find_next(i))
265 if (B[i] == NoCand) {
266 B[i] = C;
267 Count++;
268 }
269 return Count;
270 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000271 };
272
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000273 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000274 /// This vector never shrinks, but grows to the size of the largest register
275 /// class.
276 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
277
Alp Toker61007d82014-03-02 03:20:38 +0000278 enum : unsigned { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000279
280 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
281 /// NoCand which indicates the stack interval.
282 SmallVector<unsigned, 32> BundleCand;
283
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000284 /// Callee-save register cost, calculated once per machine function.
285 BlockFrequency CSRCost;
286
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000287public:
288 RAGreedy();
289
290 /// Return the pass name.
Craig Topper4584cd52014-03-07 09:26:03 +0000291 const char* getPassName() const override {
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +0000292 return "Greedy Register Allocator";
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000293 }
294
295 /// RAGreedy analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000296 void getAnalysisUsage(AnalysisUsage &AU) const override;
297 void releaseMemory() override;
298 Spiller &spiller() override { return *SpillerInstance; }
299 void enqueue(LiveInterval *LI) override;
300 LiveInterval *dequeue() override;
301 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000302
303 /// Perform register allocation.
Craig Topper4584cd52014-03-07 09:26:03 +0000304 bool runOnMachineFunction(MachineFunction &mf) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000305
306 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000307
308private:
Quentin Colombet87769712014-02-05 22:13:59 +0000309 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
310 SmallVirtRegSet &, unsigned = 0);
311
Craig Topper4584cd52014-03-07 09:26:03 +0000312 bool LRE_CanEraseVirtReg(unsigned) override;
313 void LRE_WillShrinkVirtReg(unsigned) override;
314 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
Quentin Colombet87769712014-02-05 22:13:59 +0000315 void enqueue(PQueue &CurQueue, LiveInterval *LI);
316 LiveInterval *dequeue(PQueue &CurQueue);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000317
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000318 BlockFrequency calcSpillCost();
319 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000320 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000321 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000322 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000323 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000324 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000325 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000326 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000327 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
328 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
329 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000330 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000331 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
332 SmallLISet &RecoloringCandidates,
333 const SmallVirtRegSet &FixedRegisters);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000334
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000335 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000336 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000337 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000338 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000339 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000340 SmallVectorImpl<unsigned>&);
Manman Ren9db66b32014-03-24 23:23:42 +0000341 /// Calculate cost of region splitting.
342 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
343 AllocationOrder &Order,
344 BlockFrequency &BestCost,
Manman Ren78cf02a2014-03-25 00:16:25 +0000345 unsigned &NumCands, bool IgnoreCSR);
Manman Ren9db66b32014-03-24 23:23:42 +0000346 /// Perform region splitting.
347 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
348 bool HasCompact,
349 SmallVectorImpl<unsigned> &NewVRegs);
Manman Ren9dee4492014-03-27 21:21:57 +0000350 /// Check other options before using a callee-saved register for the first
351 /// time.
352 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
353 unsigned PhysReg, unsigned &CostPerUseLimit,
354 SmallVectorImpl<unsigned> &NewVRegs);
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000355 void initializeCSRCost();
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000356 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000357 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000358 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000359 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000360 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000361 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000362 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000363 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000364 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
365 SmallVectorImpl<unsigned> &,
366 SmallVirtRegSet &, unsigned);
367 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
368 SmallVirtRegSet &, unsigned);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000369};
370} // end anonymous namespace
371
372char RAGreedy::ID = 0;
373
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000374#ifndef NDEBUG
375const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000376 "RS_New",
377 "RS_Assign",
378 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000379 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000380 "RS_Spill",
381 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000382};
383#endif
384
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000385// Hysteresis to use when comparing floats.
386// This helps stabilize decisions based on float comparisons.
NAKAMURA Takumia71003a2014-02-04 06:29:38 +0000387const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000388
389
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000390FunctionPass* llvm::createGreedyRegisterAllocator() {
391 return new RAGreedy();
392}
393
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000394RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000395 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000396 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000397 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
398 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Rafael Espindola676c4052011-06-26 22:34:10 +0000399 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
Andrew Tricke1c034f2012-01-17 06:55:03 +0000400 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000401 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
402 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
403 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
404 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000405 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000406 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
407 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000408}
409
410void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
411 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000412 AU.addRequired<MachineBlockFrequencyInfo>();
413 AU.addPreserved<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000414 AU.addRequired<AliasAnalysis>();
415 AU.addPreserved<AliasAnalysis>();
416 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000417 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000418 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000419 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000420 AU.addRequired<LiveDebugVariables>();
421 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000422 AU.addRequired<LiveStacks>();
423 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000424 AU.addRequired<MachineDominatorTree>();
425 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000426 AU.addRequired<MachineLoopInfo>();
427 AU.addPreserved<MachineLoopInfo>();
428 AU.addRequired<VirtRegMap>();
429 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000430 AU.addRequired<LiveRegMatrix>();
431 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000432 AU.addRequired<EdgeBundles>();
433 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000434 MachineFunctionPass::getAnalysisUsage(AU);
435}
436
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000437
438//===----------------------------------------------------------------------===//
439// LiveRangeEdit delegate methods
440//===----------------------------------------------------------------------===//
441
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000442bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000443 if (VRM->hasPhys(VirtReg)) {
444 Matrix->unassign(LIS->getInterval(VirtReg));
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000445 return true;
446 }
447 // Unassigned virtreg is probably in the priority queue.
448 // RegAllocBase will erase it after dequeueing.
449 return false;
450}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000451
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000452void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000453 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000454 return;
455
456 // Register is assigned, put it back on the queue for reassignment.
457 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000458 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000459 enqueue(&LI);
460}
461
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000462void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000463 // Cloning a register we haven't even heard about yet? Just ignore it.
464 if (!ExtraRegInfo.inBounds(Old))
465 return;
466
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000467 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000468 // be split into connected components. The new components are much smaller
469 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000470 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000471 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000472 ExtraRegInfo.grow(New);
473 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000474}
475
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000476void RAGreedy::releaseMemory() {
Craig Topperc0196b12014-04-14 00:51:57 +0000477 SpillerInstance.reset(nullptr);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000478 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000479 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000480}
481
Quentin Colombet87769712014-02-05 22:13:59 +0000482void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
483
484void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000485 // Prioritize live ranges by size, assigning larger ranges first.
486 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000487 const unsigned Size = LI->getSize();
488 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000489 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
490 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000491 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000492
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000493 ExtraRegInfo.grow(Reg);
494 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000495 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000496
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000497 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000498 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000499 // everything else has been allocated.
500 Prio = Size;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000501 } else {
Andrew Trick52a00932014-02-26 22:07:26 +0000502 // Giant live ranges fall back to the global assignment heuristic, which
503 // prevents excessive spilling in pathological cases.
504 bool ReverseLocal = TRI->reverseLocalAssignment();
Andrew Trickb1531e52014-02-27 21:37:33 +0000505 bool ForceGlobal = !ReverseLocal && TRI->mayOverrideLocalAssignment() &&
Andrew Trick52a00932014-02-26 22:07:26 +0000506 (Size / SlotIndex::InstrDist) > (2 * MRI->getRegClass(Reg)->getNumRegs());
507
508 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
Andrew Trick84852572013-07-25 18:35:14 +0000509 LIS->intervalIsInOneMBB(*LI)) {
510 // Allocate original local ranges in linear instruction order. Since they
511 // are singly defined, this produces optimal coloring in the absence of
512 // global interference and other constraints.
Andrew Trick52a00932014-02-26 22:07:26 +0000513 if (!ReverseLocal)
Andrew Trick2d8826a2013-12-11 03:40:15 +0000514 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
515 else {
516 // Allocating bottom up may allow many short LRGs to be assigned first
517 // to one of the cheap registers. This could be much faster for very
518 // large blocks on targets with many physical registers.
519 Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
520 }
Andrew Trick84852572013-07-25 18:35:14 +0000521 }
522 else {
523 // Allocate global and split ranges in long->short order. Long ranges that
524 // don't fit should be spilled (or split) ASAP so they don't create
525 // interference. Mark a bit to prioritize global above local ranges.
526 Prio = (1u << 29) + Size;
527 }
528 // Mark a higher bit to prioritize global and local above RS_Split.
529 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000530
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000531 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000532 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000533 Prio |= (1u << 30);
534 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000535 // The virtual register number is a tie breaker for same-sized ranges.
536 // Give lower vreg numbers higher priority to assign them first.
Quentin Colombet87769712014-02-05 22:13:59 +0000537 CurQueue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000538}
539
Quentin Colombet87769712014-02-05 22:13:59 +0000540LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
541
542LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
543 if (CurQueue.empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000544 return nullptr;
Quentin Colombet87769712014-02-05 22:13:59 +0000545 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
546 CurQueue.pop();
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000547 return LI;
548}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000549
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000550
551//===----------------------------------------------------------------------===//
552// Direct Assignment
553//===----------------------------------------------------------------------===//
554
555/// tryAssign - Try to assign VirtReg to an available register.
556unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
557 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000558 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000559 Order.rewind();
560 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000561 while ((PhysReg = Order.next()))
562 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000563 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000564 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000565 return PhysReg;
566
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000567 // PhysReg is available, but there may be a better choice.
568
569 // If we missed a simple hint, try to cheaply evict interference from the
570 // preferred register.
571 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000572 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000573 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000574 EvictionCost MaxCost;
575 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000576 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
577 evictInterference(VirtReg, Hint, NewVRegs);
578 return Hint;
579 }
580 }
581
582 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000583 unsigned Cost = TRI->getCostPerUse(PhysReg);
584
585 // Most registers have 0 additional cost.
586 if (!Cost)
587 return PhysReg;
588
589 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
590 << '\n');
591 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
592 return CheapReg ? CheapReg : PhysReg;
593}
594
595
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000596//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000597// Interference eviction
598//===----------------------------------------------------------------------===//
599
Andrew Trick8bb0a252013-07-25 18:35:19 +0000600unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
601 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
602 unsigned PhysReg;
603 while ((PhysReg = Order.next())) {
604 if (PhysReg == PrevReg)
605 continue;
606
607 MCRegUnitIterator Units(PhysReg, TRI);
608 for (; Units.isValid(); ++Units) {
609 // Instantiate a "subquery", not to be confused with the Queries array.
610 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
611 if (subQ.checkInterference())
612 break;
613 }
614 // If no units have interference, break out with the current PhysReg.
615 if (!Units.isValid())
616 break;
617 }
618 if (PhysReg)
619 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
620 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
621 << '\n');
622 return PhysReg;
623}
624
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000625/// shouldEvict - determine if A should evict the assigned live range B. The
626/// eviction policy defined by this function together with the allocation order
627/// defined by enqueue() decides which registers ultimately end up being split
628/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000629///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000630/// Cascade numbers are used to prevent infinite loops if this function is a
631/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000632///
633/// @param A The live range to be assigned.
634/// @param IsHint True when A is about to be assigned to its preferred
635/// register.
636/// @param B The live range to be evicted.
637/// @param BreaksHint True when B is already assigned to its preferred register.
638bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
639 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000640 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000641
642 // Be fairly aggressive about following hints as long as the evictee can be
643 // split.
644 if (CanSplit && IsHint && !BreaksHint)
645 return true;
646
Andrew Trick059e8002013-11-22 19:07:42 +0000647 if (A.weight > B.weight) {
648 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
649 return true;
650 }
651 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000652}
653
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000654/// canEvictInterference - Return true if all interferences between VirtReg and
Manman Renfa32ca12014-02-25 19:47:15 +0000655/// PhysReg can be evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000656///
657/// @param VirtReg Live range that is about to be assigned.
658/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000659/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000660/// @param MaxCost Only look for cheaper candidates and update with new cost
661/// when returning true.
662/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000663bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000664 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000665 // It is only possible to evict virtual register interference.
666 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
667 return false;
668
Andrew Trick84852572013-07-25 18:35:14 +0000669 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
670
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000671 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
672 // involved in an eviction before. If a cascade number was assigned, deny
673 // evicting anything with the same or a newer cascade number. This prevents
674 // infinite eviction loops.
675 //
676 // This works out so a register without a cascade number is allowed to evict
677 // anything, and it can be evicted by anything.
678 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
679 if (!Cascade)
680 Cascade = NextCascade;
681
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000682 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000683 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
684 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000685 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000686 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000687 return false;
688
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000689 // Check if any interfering live range is heavier than MaxWeight.
690 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
691 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000692 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
693 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000694 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000695 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000696 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000697 // Once a live range becomes small enough, it is urgent that we find a
698 // register for it. This is indicated by an infinite spill weight. These
699 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000700 //
701 // Also allow urgent evictions of unspillable ranges from a strictly
702 // larger allocation order.
703 bool Urgent = !VirtReg.isSpillable() &&
704 (Intf->isSpillable() ||
705 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
706 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000707 // Only evict older cascades or live ranges without a cascade.
708 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
709 if (Cascade <= IntfCascade) {
710 if (!Urgent)
711 return false;
712 // We permit breaking cascades for urgent evictions. It should be the
713 // last resort, though, so make it really expensive.
714 Cost.BrokenHints += 10;
715 }
716 // Would this break a satisfied hint?
717 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
718 // Update eviction cost.
719 Cost.BrokenHints += BreaksHint;
720 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
721 // Abort if this would be too expensive.
722 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000723 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000724 if (Urgent)
725 continue;
Andrew Trickc2ab53a2013-11-29 23:49:38 +0000726 // Apply the eviction policy for non-urgent evictions.
727 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
728 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000729 // If !MaxCost.isMax(), then we're just looking for a cheap register.
730 // Evicting another local live range in this case could lead to suboptimal
731 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000732 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
733 !canReassign(*Intf, PhysReg)) {
Andrew Trick84852572013-07-25 18:35:14 +0000734 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000735 }
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000736 }
737 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000738 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000739 return true;
740}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000741
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000742/// evictInterference - Evict any interferring registers that prevent VirtReg
743/// from being assigned to Physreg. This assumes that canEvictInterference
744/// returned true.
745void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000746 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000747 // Make sure that VirtReg has a cascade number, and assign that cascade
748 // number to every evicted register. These live ranges than then only be
749 // evicted by a newer cascade, preventing infinite loops.
750 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
751 if (!Cascade)
752 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
753
754 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
755 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000756
757 // Collect all interfering virtregs first.
758 SmallVector<LiveInterval*, 8> Intfs;
759 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
760 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000761 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000762 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
763 Intfs.append(IVR.begin(), IVR.end());
764 }
765
766 // Evict them second. This will invalidate the queries.
767 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
768 LiveInterval *Intf = Intfs[i];
769 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
770 if (!VRM->hasPhys(Intf->reg))
771 continue;
772 Matrix->unassign(*Intf);
773 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
774 VirtReg.isSpillable() < Intf->isSpillable()) &&
775 "Cannot decrease cascade number, illegal eviction");
776 ExtraRegInfo[Intf->reg].Cascade = Cascade;
777 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +0000778 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000779 }
780}
781
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000782/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +0000783/// @param VirtReg Currently unassigned virtual register.
784/// @param Order Physregs to try.
785/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000786unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
787 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000788 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000789 unsigned CostPerUseLimit) {
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000790 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
791
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000792 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +0000793 EvictionCost BestCost;
794 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000795 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000796 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000797
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000798 // When we are just looking for a reduced cost per use, don't break any
799 // hints, and only evict smaller spill weights.
800 if (CostPerUseLimit < ~0u) {
801 BestCost.BrokenHints = 0;
802 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000803
804 // Check of any registers in RC are below CostPerUseLimit.
805 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
806 unsigned MinCost = RegClassInfo.getMinCost(RC);
807 if (MinCost >= CostPerUseLimit) {
808 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
809 << ", no cheaper registers to be found.\n");
810 return 0;
811 }
812
813 // It is normal for register classes to have a long tail of registers with
814 // the same cost. We don't need to look at them if they're too expensive.
815 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
816 OrderLimit = RegClassInfo.getLastCostChange(RC);
817 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
818 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000819 }
820
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000821 Order.rewind();
Aditya Nandakumar73f3d332013-12-05 21:18:40 +0000822 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000823 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
824 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000825 // The first use of a callee-saved register in a function has cost 1.
826 // Don't start using a CSR when the CostPerUseLimit is low.
827 if (CostPerUseLimit == 1)
828 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
829 if (!MRI->isPhysRegUsed(CSR)) {
830 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
831 << PrintReg(CSR, TRI) << '\n');
832 continue;
833 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000834
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000835 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000836 continue;
837
838 // Best so far.
839 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000840
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000841 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000842 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000843 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000844 }
845
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000846 if (!BestPhys)
847 return 0;
848
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000849 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000850 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +0000851}
852
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000853
854//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000855// Region Splitting
856//===----------------------------------------------------------------------===//
857
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000858/// addSplitConstraints - Fill out the SplitConstraints vector based on the
859/// interference pattern in Physreg and its aliases. Add the constraints to
860/// SpillPlacement and return the static cost of this split in Cost, assuming
861/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000862/// Return false if there are no bundles with positive bias.
863bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000864 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000865 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000866
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000867 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000868 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000869 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000870 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
871 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000872 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000873
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +0000874 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000875 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000876 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
877 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +0000878 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000879
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000880 if (!Intf.hasInterference())
881 continue;
882
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000883 // Number of spill code instructions to insert.
884 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000885
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000886 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000887 if (BI.LiveIn) {
Jakob Stoklund Olesen89339072011-04-04 15:32:15 +0000888 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000889 BC.Entry = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000890 else if (Intf.first() < BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000891 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000892 else if (Intf.first() < BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000893 ++Ins;
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +0000894 }
895
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000896 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000897 if (BI.LiveOut) {
Jakob Stoklund Olesend93b0e32011-04-05 04:20:29 +0000898 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000899 BC.Exit = SpillPlacement::MustSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000900 else if (Intf.last() > BI.LastInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000901 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +0000902 else if (Intf.last() > BI.FirstInstr)
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000903 ++Ins;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000904 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000905
906 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000907 while (Ins--)
908 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000909 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000910 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000911
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000912 // Add constraints for use-blocks. Note that these are the only constraints
913 // that may add a positive bias, it is downhill from here.
914 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000915 return SpillPlacer->scanActiveBundles();
916}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000917
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000918
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000919/// addThroughConstraints - Add constraints and links to SpillPlacer from the
920/// live-through blocks in Blocks.
921void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
922 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000923 const unsigned GroupSize = 8;
924 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000925 unsigned TBS[GroupSize];
926 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000927
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000928 for (unsigned i = 0; i != Blocks.size(); ++i) {
929 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000930 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000931
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000932 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000933 assert(T < GroupSize && "Array overflow");
934 TBS[T] = Number;
935 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000936 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000937 T = 0;
938 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000939 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000940 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000941
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000942 assert(B < GroupSize && "Array overflow");
943 BCS[B].Number = Number;
944
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000945 // Interference for the live-in value.
946 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
947 BCS[B].Entry = SpillPlacement::MustSpill;
948 else
949 BCS[B].Entry = SpillPlacement::PrefSpill;
950
951 // Interference for the live-out value.
952 if (Intf.last() >= SA->getLastSplitPoint(Number))
953 BCS[B].Exit = SpillPlacement::MustSpill;
954 else
955 BCS[B].Exit = SpillPlacement::PrefSpill;
956
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000957 if (++B == GroupSize) {
958 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
959 SpillPlacer->addConstraints(Array);
960 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000961 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000962 }
963
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000964 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
965 SpillPlacer->addConstraints(Array);
Frits van Bommel717d7ed2011-07-18 12:00:32 +0000966 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000967}
968
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000969void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000970 // Keep track of through blocks that have not been added to SpillPlacer.
971 BitVector Todo = SA->getThroughBlocks();
972 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
973 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000974#ifndef NDEBUG
975 unsigned Visited = 0;
976#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000977
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000978 for (;;) {
979 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000980 // Find new through blocks in the periphery of PrefRegBundles.
981 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
982 unsigned Bundle = NewBundles[i];
983 // Look at all blocks connected to Bundle in the full graph.
984 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
985 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
986 I != E; ++I) {
987 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000988 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000989 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000990 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000991 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000992 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000993#ifndef NDEBUG
994 ++Visited;
995#endif
996 }
997 }
998 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +0000999 if (ActiveBlocks.size() == AddedTo)
1000 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001001
1002 // Compute through constraints from the interference, or assume that all
1003 // through blocks prefer spilling when forming compact regions.
1004 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
1005 if (Cand.PhysReg)
1006 addThroughConstraints(Cand.Intf, NewBlocks);
1007 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +00001008 // Provide a strong negative bias on through blocks to prevent unwanted
1009 // liveness on loop backedges.
1010 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001011 AddedTo = ActiveBlocks.size();
1012
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001013 // Perhaps iterating can enable more bundles?
1014 SpillPlacer->iterate();
1015 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001016 DEBUG(dbgs() << ", v=" << Visited);
1017}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001018
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001019/// calcCompactRegion - Compute the set of edge bundles that should be live
1020/// when splitting the current live range into compact regions. Compact
1021/// regions can be computed without looking at interference. They are the
1022/// regions formed by removing all the live-through blocks from the live range.
1023///
1024/// Returns false if the current live range is already compact, or if the
1025/// compact regions would form single block regions anyway.
1026bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1027 // Without any through blocks, the live range is already compact.
1028 if (!SA->getNumThroughBlocks())
1029 return false;
1030
1031 // Compact regions don't correspond to any physreg.
1032 Cand.reset(IntfCache, 0);
1033
1034 DEBUG(dbgs() << "Compact region bundles");
1035
1036 // Use the spill placer to determine the live bundles. GrowRegion pretends
1037 // that all the through blocks have interference when PhysReg is unset.
1038 SpillPlacer->prepare(Cand.LiveBundles);
1039
1040 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001041 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001042 if (!addSplitConstraints(Cand.Intf, Cost)) {
1043 DEBUG(dbgs() << ", none.\n");
1044 return false;
1045 }
1046
1047 growRegion(Cand);
1048 SpillPlacer->finish();
1049
1050 if (!Cand.LiveBundles.any()) {
1051 DEBUG(dbgs() << ", none.\n");
1052 return false;
1053 }
1054
1055 DEBUG({
1056 for (int i = Cand.LiveBundles.find_first(); i>=0;
1057 i = Cand.LiveBundles.find_next(i))
1058 dbgs() << " EB#" << i;
1059 dbgs() << ".\n";
1060 });
1061 return true;
1062}
1063
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001064/// calcSpillCost - Compute how expensive it would be to split the live range in
1065/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001066BlockFrequency RAGreedy::calcSpillCost() {
1067 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001068 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1069 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1070 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1071 unsigned Number = BI.MBB->getNumber();
1072 // We normally only need one spill instruction - a load or a store.
1073 Cost += SpillPlacer->getBlockFrequency(Number);
1074
1075 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +00001076 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1077 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001078 }
1079 return Cost;
1080}
1081
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001082/// calcGlobalSplitCost - Return the global split cost of following the split
1083/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001084/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001085///
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001086BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1087 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001088 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001089 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1090 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1091 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001092 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001093 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1094 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1095 unsigned Ins = 0;
1096
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001097 if (BI.LiveIn)
1098 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1099 if (BI.LiveOut)
1100 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001101 while (Ins--)
1102 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001103 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001104
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001105 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1106 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001107 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1108 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001109 if (!RegIn && !RegOut)
1110 continue;
1111 if (RegIn && RegOut) {
1112 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001113 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001114 if (Cand.Intf.hasInterference()) {
1115 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1116 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1117 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001118 continue;
1119 }
1120 // live-in / stack-out or stack-in live-out.
1121 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001122 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001123 return GlobalCost;
1124}
1125
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001126/// splitAroundRegion - Split the current live range around the regions
1127/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001128///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001129/// Before calling this function, GlobalCand and BundleCand must be initialized
1130/// so each bundle is assigned to a valid candidate, or NoCand for the
1131/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1132/// objects must be initialized for the current live range, and intervals
1133/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001134///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001135/// @param LREdit The LiveRangeEdit object handling the current split.
1136/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1137/// must appear in this list.
1138void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1139 ArrayRef<unsigned> UsedCands) {
1140 // These are the intervals created for new global ranges. We may create more
1141 // intervals for local ranges.
1142 const unsigned NumGlobalIntvs = LREdit.size();
1143 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1144 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001145
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001146 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001147 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001148 // is all copies.
1149 unsigned Reg = SA->getParent().reg;
1150 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1151
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001152 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001153 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1154 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1155 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001156 unsigned Number = BI.MBB->getNumber();
1157 unsigned IntvIn = 0, IntvOut = 0;
1158 SlotIndex IntfIn, IntfOut;
1159 if (BI.LiveIn) {
1160 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1161 if (CandIn != NoCand) {
1162 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1163 IntvIn = Cand.IntvIdx;
1164 Cand.Intf.moveToBlock(Number);
1165 IntfIn = Cand.Intf.first();
1166 }
1167 }
1168 if (BI.LiveOut) {
1169 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1170 if (CandOut != NoCand) {
1171 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1172 IntvOut = Cand.IntvIdx;
1173 Cand.Intf.moveToBlock(Number);
1174 IntfOut = Cand.Intf.last();
1175 }
1176 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001177
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001178 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001179 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001180 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001181 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001182 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001183 continue;
1184 }
1185
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001186 if (IntvIn && IntvOut)
1187 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1188 else if (IntvIn)
1189 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001190 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001191 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001192 }
1193
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001194 // Handle live-through blocks. The relevant live-through blocks are stored in
1195 // the ActiveBlocks list with each candidate. We need to filter out
1196 // duplicates.
1197 BitVector Todo = SA->getThroughBlocks();
1198 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1199 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1200 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1201 unsigned Number = Blocks[i];
1202 if (!Todo.test(Number))
1203 continue;
1204 Todo.reset(Number);
1205
1206 unsigned IntvIn = 0, IntvOut = 0;
1207 SlotIndex IntfIn, IntfOut;
1208
1209 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1210 if (CandIn != NoCand) {
1211 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1212 IntvIn = Cand.IntvIdx;
1213 Cand.Intf.moveToBlock(Number);
1214 IntfIn = Cand.Intf.first();
1215 }
1216
1217 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1218 if (CandOut != NoCand) {
1219 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1220 IntvOut = Cand.IntvIdx;
1221 Cand.Intf.moveToBlock(Number);
1222 IntfOut = Cand.Intf.last();
1223 }
1224 if (!IntvIn && !IntvOut)
1225 continue;
1226 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1227 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001228 }
1229
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001230 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001231
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001232 SmallVector<unsigned, 8> IntvMap;
1233 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001234 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001235
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001236 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001237 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001238
1239 // Sort out the new intervals created by splitting. We get four kinds:
1240 // - Remainder intervals should not be split again.
1241 // - Candidate intervals can be assigned to Cand.PhysReg.
1242 // - Block-local splits are candidates for local splitting.
1243 // - DCE leftovers should go back on the queue.
1244 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001245 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001246
1247 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001248 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001249 continue;
1250
1251 // Remainder interval. Don't try splitting again, spill if it doesn't
1252 // allocate.
1253 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001254 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001255 continue;
1256 }
1257
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001258 // Global intervals. Allow repeated splitting as long as the number of live
1259 // blocks is strictly decreasing.
1260 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001261 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001262 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1263 << " blocks as original.\n");
1264 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001265 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001266 }
1267 continue;
1268 }
1269
1270 // Other intervals are treated as new. This includes local intervals created
1271 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001272 }
1273
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001274 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001275 MF->verify(this, "After splitting live range around region");
1276}
1277
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001278unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001279 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001280 unsigned NumCands = 0;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001281 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001282
1283 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001284 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001285 if (HasCompact) {
1286 // Yes, keep GlobalCand[0] as the compact region candidate.
1287 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001288 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001289 } else {
1290 // No benefit from the compact region, our fallback will be per-block
1291 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001292 BestCost = calcSpillCost();
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001293 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1294 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001295 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001296
Manman Ren9db66b32014-03-24 23:23:42 +00001297 unsigned BestCand =
Manman Ren78cf02a2014-03-25 00:16:25 +00001298 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1299 false/*IgnoreCSR*/);
Manman Ren9db66b32014-03-24 23:23:42 +00001300
1301 // No solutions found, fall back to single block splitting.
1302 if (!HasCompact && BestCand == NoCand)
1303 return 0;
1304
1305 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1306}
1307
1308unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1309 AllocationOrder &Order,
1310 BlockFrequency &BestCost,
Manman Ren78cf02a2014-03-25 00:16:25 +00001311 unsigned &NumCands,
1312 bool IgnoreCSR) {
Manman Ren9db66b32014-03-24 23:23:42 +00001313 unsigned BestCand = NoCand;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001314 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001315 while (unsigned PhysReg = Order.next()) {
Manman Ren78cf02a2014-03-25 00:16:25 +00001316 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
1317 if (IgnoreCSR && !MRI->isPhysRegUsed(CSR))
1318 continue;
1319
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001320 // Discard bad candidates before we run out of interference cache cursors.
1321 // This will only affect register classes with a lot of registers (>32).
1322 if (NumCands == IntfCache.getMaxCursors()) {
1323 unsigned WorstCount = ~0u;
1324 unsigned Worst = 0;
1325 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001326 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001327 continue;
1328 unsigned Count = GlobalCand[i].LiveBundles.count();
1329 if (Count < WorstCount)
1330 Worst = i, WorstCount = Count;
1331 }
1332 --NumCands;
1333 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001334 if (BestCand == NumCands)
1335 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001336 }
1337
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001338 if (GlobalCand.size() <= NumCands)
1339 GlobalCand.resize(NumCands+1);
1340 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1341 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001342
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001343 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001344 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001345 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001346 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001347 continue;
1348 }
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001349 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1350 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001351 if (Cost >= BestCost) {
1352 DEBUG({
1353 if (BestCand == NoCand)
1354 dbgs() << " worse than no bundles\n";
1355 else
1356 dbgs() << " worse than "
1357 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1358 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001359 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001360 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001361 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001362
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001363 SpillPlacer->finish();
1364
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001365 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001366 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001367 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001368 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001369 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001370
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001371 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001372 DEBUG({
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001373 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1374 << " with bundles";
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001375 for (int i = Cand.LiveBundles.find_first(); i>=0;
1376 i = Cand.LiveBundles.find_next(i))
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001377 dbgs() << " EB#" << i;
1378 dbgs() << ".\n";
1379 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001380 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001381 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001382 BestCost = Cost;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001383 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001384 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001385 }
Manman Ren9db66b32014-03-24 23:23:42 +00001386 return BestCand;
1387}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001388
Manman Ren9db66b32014-03-24 23:23:42 +00001389unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1390 bool HasCompact,
1391 SmallVectorImpl<unsigned> &NewVRegs) {
1392 SmallVector<unsigned, 8> UsedCands;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001393 // Prepare split editor.
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001394 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001395 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001396
1397 // Assign all edge bundles to the preferred candidate, or NoCand.
1398 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1399
1400 // Assign bundles for the best candidate region.
1401 if (BestCand != NoCand) {
1402 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1403 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1404 UsedCands.push_back(BestCand);
1405 Cand.IntvIdx = SE->openIntv();
1406 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1407 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001408 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001409 }
1410 }
1411
1412 // Assign bundles for the compact region.
1413 if (HasCompact) {
1414 GlobalSplitCandidate &Cand = GlobalCand.front();
1415 assert(!Cand.PhysReg && "Compact region has no physreg");
1416 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1417 UsedCands.push_back(0);
1418 Cand.IntvIdx = SE->openIntv();
1419 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1420 << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001421 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001422 }
1423 }
1424
1425 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001426 return 0;
1427}
1428
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001429
1430//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001431// Per-Block Splitting
1432//===----------------------------------------------------------------------===//
1433
1434/// tryBlockSplit - Split a global live range around every block with uses. This
1435/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1436/// they don't allocate.
1437unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001438 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001439 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1440 unsigned Reg = VirtReg.reg;
1441 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001442 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001443 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001444 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1445 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1446 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1447 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1448 SE->splitSingleBlock(BI);
1449 }
1450 // No blocks were split.
1451 if (LREdit.empty())
1452 return 0;
1453
1454 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001455 SmallVector<unsigned, 8> IntvMap;
1456 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001457
1458 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00001459 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001460
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001461 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1462
1463 // Sort out the new intervals created by splitting. The remainder interval
1464 // goes straight to spilling, the new local ranges get to stay RS_New.
1465 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001466 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001467 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1468 setStage(LI, RS_Spill);
1469 }
1470
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001471 if (VerifyEnabled)
1472 MF->verify(this, "After splitting live range around basic blocks");
1473 return 0;
1474}
1475
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001476
1477//===----------------------------------------------------------------------===//
1478// Per-Instruction Splitting
1479//===----------------------------------------------------------------------===//
1480
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001481/// Get the number of allocatable registers that match the constraints of \p Reg
1482/// on \p MI and that are also in \p SuperRC.
1483static unsigned getNumAllocatableRegsForConstraints(
1484 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1485 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1486 const RegisterClassInfo &RCI) {
1487 assert(SuperRC && "Invalid register class");
1488
1489 const TargetRegisterClass *ConstrainedRC =
1490 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1491 /* ExploreBundle */ true);
1492 if (!ConstrainedRC)
1493 return 0;
1494 return RCI.getNumAllocatableRegs(ConstrainedRC);
1495}
1496
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001497/// tryInstructionSplit - Split a live range around individual instructions.
1498/// This is normally not worthwhile since the spiller is doing essentially the
1499/// same thing. However, when the live range is in a constrained register
1500/// class, it may help to insert copies such that parts of the live range can
1501/// be moved to a larger register class.
1502///
1503/// This is similar to spilling to a larger register class.
1504unsigned
1505RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001506 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001507 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001508 // There is no point to this if there are no larger sub-classes.
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001509 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001510 return 0;
1511
1512 // Always enable split spill mode, since we're effectively spilling to a
1513 // register.
1514 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1515 SE->reset(LREdit, SplitEditor::SM_Size);
1516
1517 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1518 if (Uses.size() <= 1)
1519 return 0;
1520
1521 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1522
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001523 const TargetRegisterClass *SuperRC = TRI->getLargestLegalSuperClass(CurRC);
1524 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1525 // Split around every non-copy instruction if this split will relax
1526 // the constraints on the virtual register.
1527 // Otherwise, splitting just inserts uncoalescable copies that do not help
1528 // the allocation.
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001529 for (unsigned i = 0; i != Uses.size(); ++i) {
1530 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001531 if (MI->isFullCopy() ||
1532 SuperRCNumAllocatableRegs ==
1533 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1534 TRI, RCI)) {
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001535 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1536 continue;
1537 }
1538 SE->openIntv();
1539 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1540 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1541 SE->useIntv(SegStart, SegStop);
1542 }
1543
1544 if (LREdit.empty()) {
1545 DEBUG(dbgs() << "All uses were copies.\n");
1546 return 0;
1547 }
1548
1549 SmallVector<unsigned, 8> IntvMap;
1550 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001551 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001552 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1553
1554 // Assign all new registers to RS_Spill. This was the last chance.
1555 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1556 return 0;
1557}
1558
1559
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001560//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001561// Local Splitting
1562//===----------------------------------------------------------------------===//
1563
1564
1565/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1566/// in order to use PhysReg between two entries in SA->UseSlots.
1567///
1568/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1569///
1570void RAGreedy::calcGapWeights(unsigned PhysReg,
1571 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001572 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1573 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001574 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001575 const unsigned NumGaps = Uses.size()-1;
1576
1577 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001578 SlotIndex StartIdx =
1579 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1580 SlotIndex StopIdx =
1581 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001582
1583 GapWeight.assign(NumGaps, 0.0f);
1584
1585 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001586 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1587 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1588 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001589 continue;
1590
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001591 // We know that VirtReg is a continuous interval from FirstInstr to
1592 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001593 //
1594 // Interference that overlaps an instruction is counted in both gaps
1595 // surrounding the instruction. The exception is interference before
1596 // StartIdx and after StopIdx.
1597 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001598 LiveIntervalUnion::SegmentIter IntI =
1599 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001600 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1601 // Skip the gaps before IntI.
1602 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1603 if (++Gap == NumGaps)
1604 break;
1605 if (Gap == NumGaps)
1606 break;
1607
1608 // Update the gaps covered by IntI.
1609 const float weight = IntI.value()->weight;
1610 for (; Gap != NumGaps; ++Gap) {
1611 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1612 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1613 break;
1614 }
1615 if (Gap == NumGaps)
1616 break;
1617 }
1618 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001619
1620 // Add fixed interference.
1621 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001622 const LiveRange &LR = LIS->getRegUnit(*Units);
1623 LiveRange::const_iterator I = LR.find(StartIdx);
1624 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001625
1626 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1627 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1628 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1629 if (++Gap == NumGaps)
1630 break;
1631 if (Gap == NumGaps)
1632 break;
1633
1634 for (; Gap != NumGaps; ++Gap) {
Aaron Ballman04999042013-11-13 00:15:44 +00001635 GapWeight[Gap] = llvm::huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001636 if (Uses[Gap+1].getBaseIndex() >= I->end)
1637 break;
1638 }
1639 if (Gap == NumGaps)
1640 break;
1641 }
1642 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001643}
1644
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001645/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1646/// basic block.
1647///
1648unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001649 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001650 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1651 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001652
1653 // Note that it is possible to have an interval that is live-in or live-out
1654 // while only covering a single block - A phi-def can use undef values from
1655 // predecessors, and the block could be a single-block loop.
1656 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001657 // that the interval is continuous from FirstInstr to LastInstr. We should
1658 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001659
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001660 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001661 if (Uses.size() <= 2)
1662 return 0;
1663 const unsigned NumGaps = Uses.size()-1;
1664
1665 DEBUG({
1666 dbgs() << "tryLocalSplit: ";
1667 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001668 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001669 dbgs() << '\n';
1670 });
1671
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001672 // If VirtReg is live across any register mask operands, compute a list of
1673 // gaps with register masks.
1674 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001675 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001676 // Get regmask slots for the whole block.
1677 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001678 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001679 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001680 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1681 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001682 unsigned re = RMS.size();
1683 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001684 // Look for Uses[i] <= RMS <= Uses[i+1].
1685 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1686 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001687 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001688 // Skip a regmask on the same instruction as the last use. It doesn't
1689 // overlap the live range.
1690 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1691 break;
1692 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001693 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001694 // Advance ri to the next gap. A regmask on one of the uses counts in
1695 // both gaps.
1696 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1697 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001698 }
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001699 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001700 }
1701
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001702 // Since we allow local split results to be split again, there is a risk of
1703 // creating infinite loops. It is tempting to require that the new live
1704 // ranges have less instructions than the original. That would guarantee
1705 // convergence, but it is too strict. A live range with 3 instructions can be
1706 // split 2+3 (including the COPY), and we want to allow that.
1707 //
1708 // Instead we use these rules:
1709 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001710 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001711 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001712 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001713 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001714 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001715 // smaller ranges are marked RS_New.
1716 //
1717 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1718 // excessive splitting and infinite loops.
1719 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001720 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001721
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001722 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001723 unsigned BestBefore = NumGaps;
1724 unsigned BestAfter = 0;
1725 float BestDiff = 0;
1726
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001727 const float blockFreq =
1728 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Michael Gottesman5e985ee2013-12-14 02:37:38 +00001729 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001730 SmallVector<float, 8> GapWeight;
1731
1732 Order.rewind();
1733 while (unsigned PhysReg = Order.next()) {
1734 // Keep track of the largest spill weight that would need to be evicted in
1735 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1736 calcGapWeights(PhysReg, GapWeight);
1737
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001738 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001739 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001740 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Aaron Ballman04999042013-11-13 00:15:44 +00001741 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001742
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001743 // Try to find the best sequence of gaps to close.
1744 // The new spill weight must be larger than any gap interference.
1745
1746 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001747 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001748
1749 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1750 // It is the spill weight that needs to be evicted.
1751 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001752
1753 for (;;) {
1754 // Live before/after split?
1755 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1756 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1757
1758 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1759 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1760 << " i=" << MaxGap);
1761
1762 // Stop before the interval gets so big we wouldn't be making progress.
1763 if (!LiveBefore && !LiveAfter) {
1764 DEBUG(dbgs() << " all\n");
1765 break;
1766 }
1767 // Should the interval be extended or shrunk?
1768 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001769
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001770 // How many gaps would the new range have?
1771 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1772
1773 // Legally, without causing looping?
1774 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1775
Aaron Ballman04999042013-11-13 00:15:44 +00001776 if (Legal && MaxGap < llvm::huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001777 // Estimate the new spill weight. Each instruction reads or writes the
1778 // register. Conservatively assume there are no read-modify-write
1779 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001780 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001781 // Try to guess the size of the new interval.
1782 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1783 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1784 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001785 // Would this split be possible to allocate?
1786 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001787 DEBUG(dbgs() << " w=" << EstWeight);
1788 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001789 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001790 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001791 if (Diff > BestDiff) {
1792 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001793 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001794 BestBefore = SplitBefore;
1795 BestAfter = SplitAfter;
1796 }
1797 }
1798 }
1799
1800 // Try to shrink.
1801 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001802 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001803 DEBUG(dbgs() << " shrink\n");
1804 // Recompute the max when necessary.
1805 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1806 MaxGap = GapWeight[SplitBefore];
1807 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1808 MaxGap = std::max(MaxGap, GapWeight[i]);
1809 }
1810 continue;
1811 }
1812 MaxGap = 0;
1813 }
1814
1815 // Try to extend the interval.
1816 if (SplitAfter >= NumGaps) {
1817 DEBUG(dbgs() << " end\n");
1818 break;
1819 }
1820
1821 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001822 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001823 }
1824 }
1825
1826 // Didn't find any candidates?
1827 if (BestBefore == NumGaps)
1828 return 0;
1829
1830 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1831 << '-' << Uses[BestAfter] << ", " << BestDiff
1832 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1833
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00001834 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001835 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001836
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001837 SE->openIntv();
1838 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1839 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1840 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001841 SmallVector<unsigned, 8> IntvMap;
1842 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001843 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001844
1845 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001846 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001847 // leave the new intervals as RS_New so they can compete.
1848 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1849 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1850 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1851 if (NewGaps >= NumGaps) {
1852 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1853 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001854 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1855 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001856 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1857 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001858 }
1859 DEBUG(dbgs() << '\n');
1860 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001861 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001862
1863 return 0;
1864}
1865
1866//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001867// Live Range Splitting
1868//===----------------------------------------------------------------------===//
1869
1870/// trySplit - Try to split VirtReg or one of its interferences, making it
1871/// assignable.
1872/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1873unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001874 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00001875 // Ranges must be Split2 or less.
1876 if (getStage(VirtReg) >= RS_Spill)
1877 return 0;
1878
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001879 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001880 if (LIS->intervalIsInOneMBB(VirtReg)) {
1881 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001882 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001883 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1884 if (PhysReg || !NewVRegs.empty())
1885 return PhysReg;
1886 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001887 }
1888
1889 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001890
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001891 SA->analyze(&VirtReg);
1892
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001893 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1894 // coalescer. That may cause the range to become allocatable which means that
1895 // tryRegionSplit won't be making progress. This check should be replaced with
1896 // an assertion when the coalescer is fixed.
1897 if (SA->didRepairRange()) {
1898 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001899 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00001900 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1901 return PhysReg;
1902 }
1903
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001904 // First try to split around a region spanning multiple blocks. RS_Split2
1905 // ranges already made dubious progress with region splitting, so they go
1906 // straight to single block splitting.
1907 if (getStage(VirtReg) < RS_Split2) {
1908 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1909 if (PhysReg || !NewVRegs.empty())
1910 return PhysReg;
1911 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001912
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001913 // Then isolate blocks.
1914 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001915}
1916
Quentin Colombet87769712014-02-05 22:13:59 +00001917//===----------------------------------------------------------------------===//
1918// Last Chance Recoloring
1919//===----------------------------------------------------------------------===//
1920
1921/// mayRecolorAllInterferences - Check if the virtual registers that
1922/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
1923/// recolored to free \p PhysReg.
1924/// When true is returned, \p RecoloringCandidates has been augmented with all
1925/// the live intervals that need to be recolored in order to free \p PhysReg
1926/// for \p VirtReg.
1927/// \p FixedRegisters contains all the virtual registers that cannot be
1928/// recolored.
1929bool
1930RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
1931 SmallLISet &RecoloringCandidates,
1932 const SmallVirtRegSet &FixedRegisters) {
1933 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1934
1935 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1936 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1937 // If there is LastChanceRecoloringMaxInterference or more interferences,
1938 // chances are one would not be recolorable.
1939 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
Quentin Colombet567e30b2014-04-11 21:39:44 +00001940 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00001941 DEBUG(dbgs() << "Early abort: too many interferences.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00001942 CutOffInfo |= CO_Interf;
Quentin Colombet87769712014-02-05 22:13:59 +00001943 return false;
1944 }
1945 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
1946 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
1947 // If Intf is done and sit on the same register class as VirtReg,
1948 // it would not be recolorable as it is in the same state as VirtReg.
1949 if ((getStage(*Intf) == RS_Done &&
1950 MRI->getRegClass(Intf->reg) == CurRC) ||
1951 FixedRegisters.count(Intf->reg)) {
1952 DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
1953 return false;
1954 }
1955 RecoloringCandidates.insert(Intf);
1956 }
1957 }
1958 return true;
1959}
1960
1961/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
1962/// its interferences.
1963/// Last chance recoloring chooses a color for \p VirtReg and recolors every
1964/// virtual register that was using it. The recoloring process may recursively
1965/// use the last chance recoloring. Therefore, when a virtual register has been
1966/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
1967/// be last-chance-recolored again during this recoloring "session".
1968/// E.g.,
1969/// Let
1970/// vA can use {R1, R2 }
1971/// vB can use { R2, R3}
1972/// vC can use {R1 }
1973/// Where vA, vB, and vC cannot be split anymore (they are reloads for
1974/// instance) and they all interfere.
1975///
1976/// vA is assigned R1
1977/// vB is assigned R2
1978/// vC tries to evict vA but vA is already done.
1979/// Regular register allocation fails.
1980///
1981/// Last chance recoloring kicks in:
1982/// vC does as if vA was evicted => vC uses R1.
1983/// vC is marked as fixed.
1984/// vA needs to find a color.
1985/// None are available.
1986/// vA cannot evict vC: vC is a fixed virtual register now.
1987/// vA does as if vB was evicted => vA uses R2.
1988/// vB needs to find a color.
1989/// R3 is available.
1990/// Recoloring => vC = R1, vA = R2, vB = R3
1991///
Alp Toker70b36992014-02-25 04:21:15 +00001992/// \p Order defines the preferred allocation order for \p VirtReg.
Quentin Colombet87769712014-02-05 22:13:59 +00001993/// \p NewRegs will contain any new virtual register that have been created
1994/// (split, spill) during the process and that must be assigned.
1995/// \p FixedRegisters contains all the virtual registers that cannot be
1996/// recolored.
1997/// \p Depth gives the current depth of the last chance recoloring.
1998/// \return a physical register that can be used for VirtReg or ~0u if none
1999/// exists.
2000unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2001 AllocationOrder &Order,
2002 SmallVectorImpl<unsigned> &NewVRegs,
2003 SmallVirtRegSet &FixedRegisters,
2004 unsigned Depth) {
2005 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2006 // Ranges must be Done.
Quentin Colombet0e3b5e02014-02-13 05:17:37 +00002007 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
Quentin Colombet87769712014-02-05 22:13:59 +00002008 "Last chance recoloring should really be last chance");
2009 // Set the max depth to LastChanceRecoloringMaxDepth.
2010 // We may want to reconsider that if we end up with a too large search space
2011 // for target with hundreds of registers.
2012 // Indeed, in that case we may want to cut the search space earlier.
Quentin Colombet567e30b2014-04-11 21:39:44 +00002013 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00002014 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002015 CutOffInfo |= CO_Depth;
Quentin Colombet87769712014-02-05 22:13:59 +00002016 return ~0u;
2017 }
2018
2019 // Set of Live intervals that will need to be recolored.
2020 SmallLISet RecoloringCandidates;
2021 // Record the original mapping virtual register to physical register in case
2022 // the recoloring fails.
2023 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2024 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2025 // this recoloring "session".
2026 FixedRegisters.insert(VirtReg.reg);
2027
2028 Order.rewind();
2029 while (unsigned PhysReg = Order.next()) {
2030 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2031 << PrintReg(PhysReg, TRI) << '\n');
2032 RecoloringCandidates.clear();
2033 VirtRegToPhysReg.clear();
2034
2035 // It is only possible to recolor virtual register interference.
2036 if (Matrix->checkInterference(VirtReg, PhysReg) >
2037 LiveRegMatrix::IK_VirtReg) {
2038 DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2039
2040 continue;
2041 }
2042
2043 // Early give up on this PhysReg if it is obvious we cannot recolor all
2044 // the interferences.
2045 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2046 FixedRegisters)) {
2047 DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2048 continue;
2049 }
2050
2051 // RecoloringCandidates contains all the virtual registers that interfer
2052 // with VirtReg on PhysReg (or one of its aliases).
2053 // Enqueue them for recoloring and perform the actual recoloring.
2054 PQueue RecoloringQueue;
2055 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2056 EndIt = RecoloringCandidates.end();
2057 It != EndIt; ++It) {
2058 unsigned ItVirtReg = (*It)->reg;
2059 enqueue(RecoloringQueue, *It);
2060 assert(VRM->hasPhys(ItVirtReg) &&
2061 "Interferences are supposed to be with allocated vairables");
2062
2063 // Record the current allocation.
2064 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2065 // unset the related struct.
2066 Matrix->unassign(**It);
2067 }
2068
2069 // Do as if VirtReg was assigned to PhysReg so that the underlying
2070 // recoloring has the right information about the interferes and
2071 // available colors.
2072 Matrix->assign(VirtReg, PhysReg);
2073
2074 // Save the current recoloring state.
2075 // If we cannot recolor all the interferences, we will have to start again
2076 // at this point for the next physical register.
2077 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2078 if (tryRecoloringCandidates(RecoloringQueue, NewVRegs, FixedRegisters,
2079 Depth)) {
2080 // Do not mess up with the global assignment process.
2081 // I.e., VirtReg must be unassigned.
2082 Matrix->unassign(VirtReg);
2083 return PhysReg;
2084 }
2085
2086 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2087 << PrintReg(PhysReg, TRI) << '\n');
2088
2089 // The recoloring attempt failed, undo the changes.
2090 FixedRegisters = SaveFixedRegisters;
2091 Matrix->unassign(VirtReg);
2092
2093 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2094 EndIt = RecoloringCandidates.end();
2095 It != EndIt; ++It) {
2096 unsigned ItVirtReg = (*It)->reg;
2097 if (VRM->hasPhys(ItVirtReg))
2098 Matrix->unassign(**It);
2099 Matrix->assign(**It, VirtRegToPhysReg[ItVirtReg]);
2100 }
2101 }
2102
2103 // Last chance recoloring did not worked either, give up.
2104 return ~0u;
2105}
2106
2107/// tryRecoloringCandidates - Try to assign a new color to every register
2108/// in \RecoloringQueue.
2109/// \p NewRegs will contain any new virtual register created during the
2110/// recoloring process.
2111/// \p FixedRegisters[in/out] contains all the registers that have been
2112/// recolored.
2113/// \return true if all virtual registers in RecoloringQueue were successfully
2114/// recolored, false otherwise.
2115bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2116 SmallVectorImpl<unsigned> &NewVRegs,
2117 SmallVirtRegSet &FixedRegisters,
2118 unsigned Depth) {
2119 while (!RecoloringQueue.empty()) {
2120 LiveInterval *LI = dequeue(RecoloringQueue);
2121 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2122 unsigned PhysReg;
2123 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2124 if (PhysReg == ~0u || !PhysReg)
2125 return false;
2126 DEBUG(dbgs() << "Recoloring of " << *LI
2127 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
2128 Matrix->assign(*LI, PhysReg);
2129 FixedRegisters.insert(LI->reg);
2130 }
2131 return true;
2132}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002133
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002134//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002135// Main Entry Point
2136//===----------------------------------------------------------------------===//
2137
2138unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002139 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002140 CutOffInfo = CO_None;
2141 LLVMContext &Ctx = MF->getFunction()->getContext();
Quentin Colombet87769712014-02-05 22:13:59 +00002142 SmallVirtRegSet FixedRegisters;
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002143 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2144 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2145 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2146 if (CutOffEncountered == CO_Depth)
Quentin Colombet567e30b2014-04-11 21:39:44 +00002147 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2148 "reached. Use -fexhaustive-register-search to skip "
2149 "cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002150 else if (CutOffEncountered == CO_Interf)
2151 Ctx.emitError("register allocation failed: maximum interference for "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002152 "recoloring reached. Use -fexhaustive-register-search "
2153 "to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002154 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2155 Ctx.emitError("register allocation failed: maximum interference and "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002156 "depth for recoloring reached. Use "
2157 "-fexhaustive-register-search to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002158 }
2159 return Reg;
Quentin Colombet87769712014-02-05 22:13:59 +00002160}
2161
Manman Ren9dee4492014-03-27 21:21:57 +00002162/// Using a CSR for the first time has a cost because it causes push|pop
2163/// to be added to prologue|epilogue. Splitting a cold section of the live
2164/// range can have lower cost than using the CSR for the first time;
2165/// Spilling a live range in the cold path can have lower cost than using
2166/// the CSR for the first time. Returns the physical register if we decide
2167/// to use the CSR; otherwise return 0.
2168unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2169 AllocationOrder &Order,
2170 unsigned PhysReg,
2171 unsigned &CostPerUseLimit,
2172 SmallVectorImpl<unsigned> &NewVRegs) {
Manman Ren9dee4492014-03-27 21:21:57 +00002173 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2174 // We choose spill over using the CSR for the first time if the spill cost
2175 // is lower than CSRCost.
2176 SA->analyze(&VirtReg);
2177 if (calcSpillCost() >= CSRCost)
2178 return PhysReg;
2179
2180 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2181 // we will not use a callee-saved register in tryEvict.
2182 CostPerUseLimit = 1;
2183 return 0;
2184 }
2185 if (getStage(VirtReg) < RS_Split) {
2186 // We choose pre-splitting over using the CSR for the first time if
2187 // the cost of splitting is lower than CSRCost.
2188 SA->analyze(&VirtReg);
2189 unsigned NumCands = 0;
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002190 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2191 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2192 NumCands, true /*IgnoreCSR*/);
Manman Ren9dee4492014-03-27 21:21:57 +00002193 if (BestCand == NoCand)
2194 // Use the CSR if we can't find a region split below CSRCost.
2195 return PhysReg;
2196
2197 // Perform the actual pre-splitting.
2198 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2199 return 0;
2200 }
2201 return PhysReg;
2202}
2203
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002204void RAGreedy::initializeCSRCost() {
2205 // We use the larger one out of the command-line option and the value report
2206 // by TRI.
2207 CSRCost = BlockFrequency(
2208 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2209 if (!CSRCost.getFrequency())
2210 return;
2211
2212 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2213 uint64_t ActualEntry = MBFI->getEntryFreq();
2214 if (!ActualEntry) {
2215 CSRCost = 0;
2216 return;
2217 }
2218 uint64_t FixedEntry = 1 << 14;
2219 if (ActualEntry < FixedEntry)
2220 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2221 else if (ActualEntry <= UINT32_MAX)
2222 // Invert the fraction and divide.
2223 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2224 else
2225 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2226 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2227}
2228
Quentin Colombet87769712014-02-05 22:13:59 +00002229unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2230 SmallVectorImpl<unsigned> &NewVRegs,
2231 SmallVirtRegSet &FixedRegisters,
2232 unsigned Depth) {
Manman Ren78cf02a2014-03-25 00:16:25 +00002233 unsigned CostPerUseLimit = ~0u;
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002234 // First try assigning a free register.
Jakob Stoklund Olesenb8bf3c02011-06-03 20:34:53 +00002235 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
Manman Ren78cf02a2014-03-25 00:16:25 +00002236 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
2237 // We check other options if we are using a CSR for the first time.
2238 bool CSRFirstUse = false;
2239 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
2240 if (!MRI->isPhysRegUsed(CSR))
2241 CSRFirstUse = true;
2242
Manman Ren9dee4492014-03-27 21:21:57 +00002243 // When NewVRegs is not empty, we may have made decisions such as evicting
2244 // a virtual register, go with the earlier decisions and use the physical
2245 // register.
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002246 if (CSRCost.getFrequency() && CSRFirstUse && NewVRegs.empty()) {
Manman Ren9dee4492014-03-27 21:21:57 +00002247 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2248 CostPerUseLimit, NewVRegs);
2249 if (CSRReg || !NewVRegs.empty())
2250 // Return now if we decide to use a CSR or create new vregs due to
2251 // pre-splitting.
2252 return CSRReg;
Manman Ren78cf02a2014-03-25 00:16:25 +00002253 } else
2254 return PhysReg;
2255 }
Andrew Trickccef0982010-12-09 18:15:21 +00002256
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002257 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002258 DEBUG(dbgs() << StageName[Stage]
2259 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002260
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002261 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002262 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002263 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002264 if (Stage != RS_Split)
Manman Ren78cf02a2014-03-25 00:16:25 +00002265 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit))
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002266 return PhysReg;
Andrew Trickccef0982010-12-09 18:15:21 +00002267
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002268 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
2269
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002270 // The first time we see a live range, don't try to split or spill.
2271 // Wait until the second time, when all smaller ranges have been allocated.
2272 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002273 if (Stage < RS_Split) {
2274 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +00002275 DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00002276 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002277 return 0;
2278 }
2279
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00002280 // If we couldn't allocate a register from spilling, there is probably some
2281 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002282 if (Stage >= RS_Done || !VirtReg.isSpillable())
Quentin Colombet87769712014-02-05 22:13:59 +00002283 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2284 Depth);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002285
Jakob Stoklund Olesen903b6d32010-12-14 00:37:49 +00002286 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002287 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2288 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +00002289 return PhysReg;
2290
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002291 // Finally spill VirtReg itself.
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +00002292 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesene5bbe372012-05-19 05:25:46 +00002293 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
Jakob Stoklund Olesen4d6eafa2011-03-10 01:51:42 +00002294 spiller().spill(LRE);
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002295 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002296
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00002297 if (VerifyEnabled)
2298 MF->verify(this, "After spilling");
2299
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002300 // The live virtual register requesting allocation was spilled, so tell
2301 // the caller not to allocate anything during this round.
2302 return 0;
2303}
2304
2305bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2306 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +00002307 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002308
2309 MF = &mf;
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002310 TRI = MF->getTarget().getRegisterInfo();
2311 TII = MF->getTarget().getInstrInfo();
2312 RCI.runOnMachineFunction(mf);
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00002313 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00002314 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00002315
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00002316 RegAllocBase::init(getAnalysis<VirtRegMap>(),
2317 getAnalysis<LiveIntervals>(),
2318 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002319 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00002320 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00002321 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00002322 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00002323 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002324 Bundles = &getAnalysis<EdgeBundles>();
2325 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00002326 DebugVars = &getAnalysis<LiveDebugVariables>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002327
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002328 initializeCSRCost();
2329
Arnaud A. de Grandmaisonea3ac162013-11-11 19:04:45 +00002330 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00002331
Andrew Trick97064962013-07-25 07:26:26 +00002332 DEBUG(LIS->dump());
2333
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00002334 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Benjamin Kramere2a1d892013-06-17 19:00:36 +00002335 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002336 ExtraRegInfo.clear();
2337 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2338 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002339 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00002340 GlobalCand.resize(32); // This will grow as needed.
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00002341
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002342 allocatePhysRegs();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002343 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002344 return true;
2345}