blob: 47d726f6da7aa88257fefb36c1d5f86796a30c30 [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
Jakob Stoklund Olesen4d7432e2010-12-10 22:21:05 +000015#include "AllocationOrder.h"
Jakob Stoklund Olesen91cbcaf2011-04-02 06:03:35 +000016#include "InterferenceCache.h"
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +000017#include "LiveDebugVariables.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000018#include "RegAllocBase.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000019#include "SpillPlacement.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "Spiller.h"
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +000021#include "SplitKit.h"
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000022#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000023#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000024#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000025#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000026#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000027#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000028#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000029#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000030#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000031#include "llvm/CodeGen/MachineDominators.h"
Adam Nemeta9640662017-01-25 23:20:33 +000032#include "llvm/CodeGen/MachineFrameInfo.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineLoopInfo.h"
Adam Nemeta9640662017-01-25 23:20:33 +000035#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
Wei Mi9a16d652016-04-13 03:08:27 +000037#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000038#include "llvm/CodeGen/RegAllocRegistry.h"
Quentin Colombet1fb3362a2014-01-02 22:47:22 +000039#include "llvm/CodeGen/RegisterClassInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/CodeGen/VirtRegMap.h"
Quentin Colombet96bd2a12014-04-04 02:05:21 +000041#include "llvm/IR/LLVMContext.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/PassAnalysisSupport.h"
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +000043#include "llvm/Support/BranchProbability.h"
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +000044#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000045#include "llvm/Support/Debug.h"
46#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +000047#include "llvm/Support/Timer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000048#include "llvm/Support/raw_ostream.h"
Wei Mi9a16d652016-04-13 03:08:27 +000049#include "llvm/Target/TargetInstrInfo.h"
Quentin Colombet5caa6a22014-07-02 18:32:04 +000050#include "llvm/Target/TargetSubtargetInfo.h"
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000051#include <queue>
52
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000053using namespace llvm;
54
Chandler Carruth1b9dde02014-04-22 02:02:50 +000055#define DEBUG_TYPE "regalloc"
56
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000057STATISTIC(NumGlobalSplits, "Number of split global live ranges");
58STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000059STATISTIC(NumEvicted, "Number of interferences evicted");
60
Wei Mi9a16d652016-04-13 03:08:27 +000061static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
62 "split-spill-mode", cl::Hidden,
63 cl::desc("Spill mode for splitting live ranges"),
64 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
65 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
Mehdi Amini732afdd2016-10-08 19:41:06 +000066 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
Wei Mi9a16d652016-04-13 03:08:27 +000067 cl::init(SplitEditor::SM_Speed));
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +000068
Quentin Colombet87769712014-02-05 22:13:59 +000069static cl::opt<unsigned>
70LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
71 cl::desc("Last chance recoloring max depth"),
72 cl::init(5));
73
74static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
75 "lcr-max-interf", cl::Hidden,
76 cl::desc("Last chance recoloring maximum number of considered"
77 " interference at a time"),
78 cl::init(8));
79
Quentin Colombet567e30b2014-04-11 21:39:44 +000080static cl::opt<bool>
Quentin Colombet4344da12014-04-11 21:51:09 +000081ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
Quentin Colombet567e30b2014-04-11 21:39:44 +000082 cl::desc("Exhaustive Search for registers bypassing the depth "
83 "and interference cutoffs of last chance recoloring"));
84
Quentin Colombete1a36632014-07-01 14:08:37 +000085static cl::opt<bool> EnableLocalReassignment(
86 "enable-local-reassign", cl::Hidden,
87 cl::desc("Local reassignment can yield better allocation decisions, but "
88 "may be compile time intensive"),
Quentin Colombet5caa6a22014-07-02 18:32:04 +000089 cl::init(false));
Quentin Colombete1a36632014-07-01 14:08:37 +000090
Quentin Colombet11922942015-07-17 23:04:06 +000091static cl::opt<bool> EnableDeferredSpilling(
92 "enable-deferred-spilling", cl::Hidden,
93 cl::desc("Instead of spilling a variable right away, defer the actual "
94 "code insertion to the end of the allocation. That way the "
95 "allocator might still find a suitable coloring for this "
96 "variable because of other evicted variables."),
97 cl::init(false));
98
Manman Ren78cf02a2014-03-25 00:16:25 +000099// FIXME: Find a good default for this flag and remove the flag.
100static cl::opt<unsigned>
101CSRFirstTimeCost("regalloc-csr-first-time-cost",
102 cl::desc("Cost for first time use of callee-saved register."),
103 cl::init(0), cl::Hidden);
104
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000105static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
106 createGreedyRegisterAllocator);
107
108namespace {
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000109class RAGreedy : public MachineFunctionPass,
110 public RegAllocBase,
111 private LiveRangeEdit::Delegate {
Quentin Colombet87769712014-02-05 22:13:59 +0000112 // Convenient shortcuts.
113 typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
114 typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
115 typedef SmallSet<unsigned, 16> SmallVirtRegSet;
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000116
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000117 // context
118 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000119
Quentin Colombet1fb3362a2014-01-02 22:47:22 +0000120 // Shortcuts to some useful interface.
121 const TargetInstrInfo *TII;
122 const TargetRegisterInfo *TRI;
123 RegisterClassInfo RCI;
124
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000125 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000126 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000127 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000128 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +0000129 MachineLoopInfo *Loops;
Adam Nemeta9640662017-01-25 23:20:33 +0000130 MachineOptimizationRemarkEmitter *ORE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000131 EdgeBundles *Bundles;
132 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000133 LiveDebugVariables *DebugVars;
Wei Mic0223702016-07-08 21:08:09 +0000134 AliasAnalysis *AA;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000135
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000136 // state
Ahmed Charles56440fd2014-03-06 05:51:42 +0000137 std::unique_ptr<Spiller> SpillerInstance;
Quentin Colombet87769712014-02-05 22:13:59 +0000138 PQueue Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000139 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000140
141 // Live ranges pass through a number of stages as we try to allocate them.
142 // Some of the stages may also create new live ranges:
143 //
144 // - Region splitting.
145 // - Per-block splitting.
146 // - Local splitting.
147 // - Spilling.
148 //
149 // Ranges produced by one of the stages skip the previous stages when they are
150 // dequeued. This improves performance because we can skip interference checks
151 // that are unlikely to give any results. It also guarantees that the live
152 // range splitting algorithm terminates, something that is otherwise hard to
153 // ensure.
154 enum LiveRangeStage {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000155 /// Newly created live range that has never been queued.
156 RS_New,
157
158 /// Only attempt assignment and eviction. Then requeue as RS_Split.
159 RS_Assign,
160
161 /// Attempt live range splitting if assignment is impossible.
162 RS_Split,
163
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000164 /// Attempt more aggressive live range splitting that is guaranteed to make
165 /// progress. This is used for split products that may not be making
166 /// progress.
167 RS_Split2,
168
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000169 /// Live range will be spilled. No more splitting will be attempted.
170 RS_Spill,
171
Quentin Colombet11922942015-07-17 23:04:06 +0000172
173 /// Live range is in memory. Because of other evictions, it might get moved
174 /// in a register in the end.
175 RS_Memory,
176
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000177 /// There is nothing more we can do to this live range. Abort compilation
178 /// if it can't be assigned.
179 RS_Done
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000180 };
181
Quentin Colombet96bd2a12014-04-04 02:05:21 +0000182 // Enum CutOffStage to keep a track whether the register allocation failed
183 // because of the cutoffs encountered in last chance recoloring.
184 // Note: This is used as bitmask. New value should be next power of 2.
185 enum CutOffStage {
186 // No cutoffs encountered
187 CO_None = 0,
188
189 // lcr-max-depth cutoff encountered
190 CO_Depth = 1,
191
192 // lcr-max-interf cutoff encountered
193 CO_Interf = 2
194 };
195
196 uint8_t CutOffInfo;
197
Eli Friedman78bffa52013-09-10 23:18:14 +0000198#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000199 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000200#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000201
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000202 // RegInfo - Keep additional information about each live range.
203 struct RegInfo {
204 LiveRangeStage Stage;
205
206 // Cascade - Eviction loop prevention. See canEvictInterference().
207 unsigned Cascade;
208
209 RegInfo() : Stage(RS_New), Cascade(0) {}
210 };
211
212 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000213
214 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000215 return ExtraRegInfo[VirtReg.reg].Stage;
216 }
217
218 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
219 ExtraRegInfo.resize(MRI->getNumVirtRegs());
220 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000221 }
222
223 template<typename Iterator>
224 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000225 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000226 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000227 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000228 if (ExtraRegInfo[Reg].Stage == RS_New)
229 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000230 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000231 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000232
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000233 /// Cost of evicting interference.
234 struct EvictionCost {
235 unsigned BrokenHints; ///< Total number of broken hints.
236 float MaxWeight; ///< Maximum spill weight evicted.
237
Andrew Trick3621b8a2013-11-22 19:07:38 +0000238 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000239
Andrew Trick84852572013-07-25 18:35:14 +0000240 bool isMax() const { return BrokenHints == ~0u; }
241
Andrew Trick3621b8a2013-11-22 19:07:38 +0000242 void setMax() { BrokenHints = ~0u; }
243
244 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
245
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000246 bool operator<(const EvictionCost &O) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +0000247 return std::tie(BrokenHints, MaxWeight) <
248 std::tie(O.BrokenHints, O.MaxWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000249 }
250 };
251
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000252 // splitting state.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000253 std::unique_ptr<SplitAnalysis> SA;
254 std::unique_ptr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000255
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000256 /// Cached per-block interference maps
257 InterferenceCache IntfCache;
258
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000259 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000260 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000261
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000262 /// Global live range splitting candidate info.
263 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000264 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000265 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000266
267 // SplitKit interval index for this candidate.
268 unsigned IntvIdx;
269
270 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000271 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000272
273 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000274 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000275 SmallVector<unsigned, 8> ActiveBlocks;
276
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000277 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000278 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000279 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000280 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000281 LiveBundles.clear();
282 ActiveBlocks.clear();
283 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000284
285 // Set B[i] = C for every live bundle where B[i] was NoCand.
286 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
287 unsigned Count = 0;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +0000288 for (unsigned i : LiveBundles.set_bits())
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000289 if (B[i] == NoCand) {
290 B[i] = C;
291 Count++;
292 }
293 return Count;
294 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000295 };
296
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000297 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000298 /// This vector never shrinks, but grows to the size of the largest register
299 /// class.
300 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
301
Alp Toker61007d82014-03-02 03:20:38 +0000302 enum : unsigned { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000303
304 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
305 /// NoCand which indicates the stack interval.
306 SmallVector<unsigned, 32> BundleCand;
307
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000308 /// Callee-save register cost, calculated once per machine function.
309 BlockFrequency CSRCost;
310
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000311 /// Run or not the local reassignment heuristic. This information is
312 /// obtained from the TargetSubtargetInfo.
313 bool EnableLocalReassign;
314
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000315 /// Set of broken hints that may be reconciled later because of eviction.
316 SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
317
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000318public:
319 RAGreedy();
320
321 /// Return the pass name.
Mehdi Amini117296c2016-10-01 02:56:57 +0000322 StringRef getPassName() const override { return "Greedy Register Allocator"; }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000323
324 /// RAGreedy analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000325 void getAnalysisUsage(AnalysisUsage &AU) const override;
326 void releaseMemory() override;
327 Spiller &spiller() override { return *SpillerInstance; }
328 void enqueue(LiveInterval *LI) override;
329 LiveInterval *dequeue() override;
330 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000331 void aboutToRemoveInterval(LiveInterval &) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000332
333 /// Perform register allocation.
Craig Topper4584cd52014-03-07 09:26:03 +0000334 bool runOnMachineFunction(MachineFunction &mf) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000335
Matthias Braun90799ce2016-08-23 21:19:49 +0000336 MachineFunctionProperties getRequiredProperties() const override {
337 return MachineFunctionProperties().set(
338 MachineFunctionProperties::Property::NoPHIs);
339 }
340
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000341 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000342
343private:
Quentin Colombet87769712014-02-05 22:13:59 +0000344 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
345 SmallVirtRegSet &, unsigned = 0);
346
Craig Topper4584cd52014-03-07 09:26:03 +0000347 bool LRE_CanEraseVirtReg(unsigned) override;
348 void LRE_WillShrinkVirtReg(unsigned) override;
349 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
Quentin Colombet87769712014-02-05 22:13:59 +0000350 void enqueue(PQueue &CurQueue, LiveInterval *LI);
351 LiveInterval *dequeue(PQueue &CurQueue);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000352
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000353 BlockFrequency calcSpillCost();
354 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000355 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000356 void growRegion(GlobalSplitCandidate &Cand);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000357 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000358 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000359 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000360 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000361 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000362 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
363 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
364 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000365 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000366 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
367 SmallLISet &RecoloringCandidates,
368 const SmallVirtRegSet &FixedRegisters);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000369
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000370 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000371 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000372 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000373 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000374 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000375 SmallVectorImpl<unsigned>&);
Manman Ren9db66b32014-03-24 23:23:42 +0000376 /// Calculate cost of region splitting.
377 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
378 AllocationOrder &Order,
379 BlockFrequency &BestCost,
Manman Ren78cf02a2014-03-25 00:16:25 +0000380 unsigned &NumCands, bool IgnoreCSR);
Manman Ren9db66b32014-03-24 23:23:42 +0000381 /// Perform region splitting.
382 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
383 bool HasCompact,
384 SmallVectorImpl<unsigned> &NewVRegs);
Manman Ren9dee4492014-03-27 21:21:57 +0000385 /// Check other options before using a callee-saved register for the first
386 /// time.
387 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
388 unsigned PhysReg, unsigned &CostPerUseLimit,
389 SmallVectorImpl<unsigned> &NewVRegs);
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000390 void initializeCSRCost();
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000391 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000392 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000393 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000394 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000395 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000396 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000397 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000398 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000399 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
400 SmallVectorImpl<unsigned> &,
401 SmallVirtRegSet &, unsigned);
402 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
403 SmallVirtRegSet &, unsigned);
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000404 void tryHintRecoloring(LiveInterval &);
405 void tryHintsRecoloring();
406
407 /// Model the information carried by one end of a copy.
408 struct HintInfo {
409 /// The frequency of the copy.
410 BlockFrequency Freq;
411 /// The virtual register or physical register.
412 unsigned Reg;
413 /// Its currently assigned register.
414 /// In case of a physical register Reg == PhysReg.
415 unsigned PhysReg;
416 HintInfo(BlockFrequency Freq, unsigned Reg, unsigned PhysReg)
417 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
418 };
419 typedef SmallVector<HintInfo, 4> HintsInfo;
420 BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
421 void collectHintInfo(unsigned, HintsInfo &);
Matthias Braun953393a2015-07-14 17:38:17 +0000422
423 bool isUnusedCalleeSavedReg(unsigned PhysReg) const;
Adam Nemeta9640662017-01-25 23:20:33 +0000424
425 /// Compute and report the number of spills and reloads for a loop.
426 void reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
427 unsigned &FoldedReloads, unsigned &Spills,
428 unsigned &FoldedSpills);
429
430 /// Report the number of spills and reloads for each loop.
431 void reportNumberOfSplillsReloads() {
432 for (MachineLoop *L : *Loops) {
433 unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
434 reportNumberOfSplillsReloads(L, Reloads, FoldedReloads, Spills,
435 FoldedSpills);
436 }
437 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000438};
439} // end anonymous namespace
440
441char RAGreedy::ID = 0;
Tom Stellard11e60ff2016-11-14 21:50:13 +0000442char &llvm::RAGreedyID = RAGreedy::ID;
443
444INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
445 "Greedy Register Allocator", false, false)
446INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
447INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
448INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
449INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
450INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
451INITIALIZE_PASS_DEPENDENCY(LiveStacks)
452INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
453INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
454INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
455INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
456INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
457INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
Adam Nemeta9640662017-01-25 23:20:33 +0000458INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
Tom Stellard11e60ff2016-11-14 21:50:13 +0000459INITIALIZE_PASS_END(RAGreedy, "greedy",
460 "Greedy Register Allocator", false, false)
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000461
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000462#ifndef NDEBUG
463const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000464 "RS_New",
465 "RS_Assign",
466 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000467 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000468 "RS_Spill",
Quentin Colombet11922942015-07-17 23:04:06 +0000469 "RS_Memory",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000470 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000471};
472#endif
473
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000474// Hysteresis to use when comparing floats.
475// This helps stabilize decisions based on float comparisons.
NAKAMURA Takumia71003a2014-02-04 06:29:38 +0000476const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000477
478
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000479FunctionPass* llvm::createGreedyRegisterAllocator() {
480 return new RAGreedy();
481}
482
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000483RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000484}
485
486void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
487 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000488 AU.addRequired<MachineBlockFrequencyInfo>();
489 AU.addPreserved<MachineBlockFrequencyInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000490 AU.addRequired<AAResultsWrapperPass>();
491 AU.addPreserved<AAResultsWrapperPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000492 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000493 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000494 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000495 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000496 AU.addRequired<LiveDebugVariables>();
497 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000498 AU.addRequired<LiveStacks>();
499 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000500 AU.addRequired<MachineDominatorTree>();
501 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000502 AU.addRequired<MachineLoopInfo>();
503 AU.addPreserved<MachineLoopInfo>();
504 AU.addRequired<VirtRegMap>();
505 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000506 AU.addRequired<LiveRegMatrix>();
507 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000508 AU.addRequired<EdgeBundles>();
509 AU.addRequired<SpillPlacement>();
Adam Nemeta9640662017-01-25 23:20:33 +0000510 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000511 MachineFunctionPass::getAnalysisUsage(AU);
512}
513
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000514
515//===----------------------------------------------------------------------===//
516// LiveRangeEdit delegate methods
517//===----------------------------------------------------------------------===//
518
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000519bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000520 if (VRM->hasPhys(VirtReg)) {
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000521 LiveInterval &LI = LIS->getInterval(VirtReg);
522 Matrix->unassign(LI);
523 aboutToRemoveInterval(LI);
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000524 return true;
525 }
526 // Unassigned virtreg is probably in the priority queue.
527 // RegAllocBase will erase it after dequeueing.
528 return false;
529}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000530
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000531void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000532 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000533 return;
534
535 // Register is assigned, put it back on the queue for reassignment.
536 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000537 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000538 enqueue(&LI);
539}
540
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000541void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000542 // Cloning a register we haven't even heard about yet? Just ignore it.
543 if (!ExtraRegInfo.inBounds(Old))
544 return;
545
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000546 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000547 // be split into connected components. The new components are much smaller
548 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000549 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000550 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000551 ExtraRegInfo.grow(New);
552 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000553}
554
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000555void RAGreedy::releaseMemory() {
David Blaikieb61064e2014-07-19 01:05:11 +0000556 SpillerInstance.reset();
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000557 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000558 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000559}
560
Quentin Colombet87769712014-02-05 22:13:59 +0000561void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
562
563void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000564 // Prioritize live ranges by size, assigning larger ranges first.
565 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000566 const unsigned Size = LI->getSize();
567 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000568 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
569 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000570 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000571
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000572 ExtraRegInfo.grow(Reg);
573 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000574 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000575
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000576 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000577 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000578 // everything else has been allocated.
579 Prio = Size;
Quentin Colombet11922942015-07-17 23:04:06 +0000580 } else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
581 // Memory operand should be considered last.
582 // Change the priority such that Memory operand are assigned in
583 // the reverse order that they came in.
584 // TODO: Make this a member variable and probably do something about hints.
585 static unsigned MemOp = 0;
586 Prio = MemOp++;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000587 } else {
Andrew Trick52a00932014-02-26 22:07:26 +0000588 // Giant live ranges fall back to the global assignment heuristic, which
589 // prevents excessive spilling in pathological cases.
590 bool ReverseLocal = TRI->reverseLocalAssignment();
Matthias Brauna354cdd2015-03-31 19:57:53 +0000591 const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
Renato Golin4e31ae12014-10-03 12:20:53 +0000592 bool ForceGlobal = !ReverseLocal &&
Matthias Brauna354cdd2015-03-31 19:57:53 +0000593 (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
Andrew Trick52a00932014-02-26 22:07:26 +0000594
595 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
Andrew Trick84852572013-07-25 18:35:14 +0000596 LIS->intervalIsInOneMBB(*LI)) {
597 // Allocate original local ranges in linear instruction order. Since they
598 // are singly defined, this produces optimal coloring in the absence of
599 // global interference and other constraints.
Andrew Trick52a00932014-02-26 22:07:26 +0000600 if (!ReverseLocal)
Andrew Trick2d8826a2013-12-11 03:40:15 +0000601 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
602 else {
603 // Allocating bottom up may allow many short LRGs to be assigned first
604 // to one of the cheap registers. This could be much faster for very
605 // large blocks on targets with many physical registers.
Matthias Braunf5f89b92015-03-31 19:57:49 +0000606 Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
Andrew Trick2d8826a2013-12-11 03:40:15 +0000607 }
Matthias Brauna354cdd2015-03-31 19:57:53 +0000608 Prio |= RC.AllocationPriority << 24;
609 } else {
Andrew Trick84852572013-07-25 18:35:14 +0000610 // Allocate global and split ranges in long->short order. Long ranges that
611 // don't fit should be spilled (or split) ASAP so they don't create
612 // interference. Mark a bit to prioritize global above local ranges.
613 Prio = (1u << 29) + Size;
614 }
615 // Mark a higher bit to prioritize global and local above RS_Split.
616 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000617
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000618 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000619 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000620 Prio |= (1u << 30);
621 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000622 // The virtual register number is a tie breaker for same-sized ranges.
623 // Give lower vreg numbers higher priority to assign them first.
Quentin Colombet87769712014-02-05 22:13:59 +0000624 CurQueue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000625}
626
Quentin Colombet87769712014-02-05 22:13:59 +0000627LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
628
629LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
630 if (CurQueue.empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000631 return nullptr;
Quentin Colombet87769712014-02-05 22:13:59 +0000632 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
633 CurQueue.pop();
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000634 return LI;
635}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000636
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000637
638//===----------------------------------------------------------------------===//
639// Direct Assignment
640//===----------------------------------------------------------------------===//
641
642/// tryAssign - Try to assign VirtReg to an available register.
643unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
644 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000645 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000646 Order.rewind();
647 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000648 while ((PhysReg = Order.next()))
649 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000650 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000651 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000652 return PhysReg;
653
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000654 // PhysReg is available, but there may be a better choice.
655
656 // If we missed a simple hint, try to cheaply evict interference from the
657 // preferred register.
658 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000659 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000660 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000661 EvictionCost MaxCost;
662 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000663 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
664 evictInterference(VirtReg, Hint, NewVRegs);
665 return Hint;
666 }
Quentin Colombetfb9b0cd2016-11-16 01:07:12 +0000667 // Record the missed hint, we may be able to recover
668 // at the end if the surrounding allocation changed.
669 SetOfBrokenHints.insert(&VirtReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000670 }
671
672 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000673 unsigned Cost = TRI->getCostPerUse(PhysReg);
674
675 // Most registers have 0 additional cost.
676 if (!Cost)
677 return PhysReg;
678
679 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
680 << '\n');
681 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
682 return CheapReg ? CheapReg : PhysReg;
683}
684
685
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000686//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000687// Interference eviction
688//===----------------------------------------------------------------------===//
689
Andrew Trick8bb0a252013-07-25 18:35:19 +0000690unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
Matthias Braun5d1f12d2015-07-15 22:16:00 +0000691 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000692 unsigned PhysReg;
693 while ((PhysReg = Order.next())) {
694 if (PhysReg == PrevReg)
695 continue;
696
697 MCRegUnitIterator Units(PhysReg, TRI);
698 for (; Units.isValid(); ++Units) {
699 // Instantiate a "subquery", not to be confused with the Queries array.
Matthias Braun173e1142017-03-01 21:48:12 +0000700 LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000701 if (subQ.checkInterference())
702 break;
703 }
704 // If no units have interference, break out with the current PhysReg.
705 if (!Units.isValid())
706 break;
707 }
708 if (PhysReg)
709 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
710 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
711 << '\n');
712 return PhysReg;
713}
714
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000715/// shouldEvict - determine if A should evict the assigned live range B. The
716/// eviction policy defined by this function together with the allocation order
717/// defined by enqueue() decides which registers ultimately end up being split
718/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000719///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000720/// Cascade numbers are used to prevent infinite loops if this function is a
721/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000722///
723/// @param A The live range to be assigned.
724/// @param IsHint True when A is about to be assigned to its preferred
725/// register.
726/// @param B The live range to be evicted.
727/// @param BreaksHint True when B is already assigned to its preferred register.
728bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
729 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000730 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000731
732 // Be fairly aggressive about following hints as long as the evictee can be
733 // split.
734 if (CanSplit && IsHint && !BreaksHint)
735 return true;
736
Andrew Trick059e8002013-11-22 19:07:42 +0000737 if (A.weight > B.weight) {
738 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
739 return true;
740 }
741 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000742}
743
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000744/// canEvictInterference - Return true if all interferences between VirtReg and
Manman Renfa32ca12014-02-25 19:47:15 +0000745/// PhysReg can be evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000746///
747/// @param VirtReg Live range that is about to be assigned.
748/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000749/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000750/// @param MaxCost Only look for cheaper candidates and update with new cost
751/// when returning true.
752/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000753bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000754 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000755 // It is only possible to evict virtual register interference.
756 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
757 return false;
758
Andrew Trick84852572013-07-25 18:35:14 +0000759 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
760
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000761 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
762 // involved in an eviction before. If a cascade number was assigned, deny
763 // evicting anything with the same or a newer cascade number. This prevents
764 // infinite eviction loops.
765 //
766 // This works out so a register without a cascade number is allowed to evict
767 // anything, and it can be evicted by anything.
768 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
769 if (!Cascade)
770 Cascade = NextCascade;
771
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000772 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000773 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
774 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000775 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000776 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000777 return false;
778
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000779 // Check if any interfering live range is heavier than MaxWeight.
780 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
781 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000782 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
783 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000784 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000785 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000786 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000787 // Once a live range becomes small enough, it is urgent that we find a
788 // register for it. This is indicated by an infinite spill weight. These
789 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000790 //
791 // Also allow urgent evictions of unspillable ranges from a strictly
792 // larger allocation order.
793 bool Urgent = !VirtReg.isSpillable() &&
794 (Intf->isSpillable() ||
795 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
796 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000797 // Only evict older cascades or live ranges without a cascade.
798 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
799 if (Cascade <= IntfCascade) {
800 if (!Urgent)
801 return false;
802 // We permit breaking cascades for urgent evictions. It should be the
803 // last resort, though, so make it really expensive.
804 Cost.BrokenHints += 10;
805 }
806 // Would this break a satisfied hint?
807 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
808 // Update eviction cost.
809 Cost.BrokenHints += BreaksHint;
810 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
811 // Abort if this would be too expensive.
812 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000813 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000814 if (Urgent)
815 continue;
Andrew Trickc2ab53a2013-11-29 23:49:38 +0000816 // Apply the eviction policy for non-urgent evictions.
817 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
818 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000819 // If !MaxCost.isMax(), then we're just looking for a cheap register.
820 // Evicting another local live range in this case could lead to suboptimal
821 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000822 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000823 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
Andrew Trick84852572013-07-25 18:35:14 +0000824 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000825 }
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000826 }
827 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000828 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000829 return true;
830}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000831
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000832/// evictInterference - Evict any interferring registers that prevent VirtReg
833/// from being assigned to Physreg. This assumes that canEvictInterference
834/// returned true.
835void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000836 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000837 // Make sure that VirtReg has a cascade number, and assign that cascade
838 // number to every evicted register. These live ranges than then only be
839 // evicted by a newer cascade, preventing infinite loops.
840 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
841 if (!Cascade)
842 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
843
844 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
845 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000846
847 // Collect all interfering virtregs first.
848 SmallVector<LiveInterval*, 8> Intfs;
849 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
850 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Matthias Braunffe40dd2017-03-03 23:27:20 +0000851 // We usually have the interfering VRegs cached so collectInterferingVRegs()
852 // should be fast, we may need to recalculate if when different physregs
853 // overlap the same register unit so we had different SubRanges queried
854 // against it.
855 Q.collectInterferingVRegs();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000856 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
857 Intfs.append(IVR.begin(), IVR.end());
858 }
859
860 // Evict them second. This will invalidate the queries.
861 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
862 LiveInterval *Intf = Intfs[i];
863 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
864 if (!VRM->hasPhys(Intf->reg))
865 continue;
866 Matrix->unassign(*Intf);
867 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
868 VirtReg.isSpillable() < Intf->isSpillable()) &&
869 "Cannot decrease cascade number, illegal eviction");
870 ExtraRegInfo[Intf->reg].Cascade = Cascade;
871 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +0000872 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000873 }
874}
875
Matthias Braun953393a2015-07-14 17:38:17 +0000876/// Returns true if the given \p PhysReg is a callee saved register and has not
877/// been used for allocation yet.
878bool RAGreedy::isUnusedCalleeSavedReg(unsigned PhysReg) const {
879 unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
880 if (CSR == 0)
881 return false;
882
883 return !Matrix->isPhysRegUsed(PhysReg);
884}
885
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000886/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +0000887/// @param VirtReg Currently unassigned virtual register.
888/// @param Order Physregs to try.
889/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000890unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
891 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000892 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000893 unsigned CostPerUseLimit) {
Matthias Braun9f15a792016-11-18 19:43:18 +0000894 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
895 TimePassesIsEnabled);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000896
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000897 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +0000898 EvictionCost BestCost;
899 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000900 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000901 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000902
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000903 // When we are just looking for a reduced cost per use, don't break any
904 // hints, and only evict smaller spill weights.
905 if (CostPerUseLimit < ~0u) {
906 BestCost.BrokenHints = 0;
907 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000908
909 // Check of any registers in RC are below CostPerUseLimit.
910 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
911 unsigned MinCost = RegClassInfo.getMinCost(RC);
912 if (MinCost >= CostPerUseLimit) {
Craig Toppercf0444b2014-11-17 05:50:14 +0000913 DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = " << MinCost
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +0000914 << ", no cheaper registers to be found.\n");
915 return 0;
916 }
917
918 // It is normal for register classes to have a long tail of registers with
919 // the same cost. We don't need to look at them if they're too expensive.
920 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
921 OrderLimit = RegClassInfo.getLastCostChange(RC);
922 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
923 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000924 }
925
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000926 Order.rewind();
Aditya Nandakumar73f3d332013-12-05 21:18:40 +0000927 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000928 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
929 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000930 // The first use of a callee-saved register in a function has cost 1.
931 // Don't start using a CSR when the CostPerUseLimit is low.
Matthias Braun953393a2015-07-14 17:38:17 +0000932 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
933 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
934 << PrintReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
935 << '\n');
936 continue;
937 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000938
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000939 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000940 continue;
941
942 // Best so far.
943 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000944
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000945 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000946 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +0000947 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000948 }
949
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000950 if (!BestPhys)
951 return 0;
952
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000953 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000954 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +0000955}
956
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000957
958//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000959// Region Splitting
960//===----------------------------------------------------------------------===//
961
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +0000962/// addSplitConstraints - Fill out the SplitConstraints vector based on the
963/// interference pattern in Physreg and its aliases. Add the constraints to
964/// SpillPlacement and return the static cost of this split in Cost, assuming
965/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000966/// Return false if there are no bundles with positive bias.
967bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000968 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000969 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000970
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000971 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000972 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000973 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000974 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
975 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000976 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000977
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +0000978 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000979 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +0000980 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
981 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +0000982 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000983
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000984 if (!Intf.hasInterference())
985 continue;
986
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000987 // Number of spill code instructions to insert.
988 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000989
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000990 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000991 if (BI.LiveIn) {
Richard Trieu7a083812016-02-18 22:09:30 +0000992 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
993 BC.Entry = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000994 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +0000995 } else if (Intf.first() < BI.FirstInstr) {
996 BC.Entry = SpillPlacement::PrefSpill;
997 ++Ins;
998 } else if (Intf.first() < BI.LastInstr) {
999 ++Ins;
1000 }
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +00001001 }
1002
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001003 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001004 if (BI.LiveOut) {
Richard Trieu7a083812016-02-18 22:09:30 +00001005 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
1006 BC.Exit = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001007 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +00001008 } else if (Intf.last() > BI.LastInstr) {
1009 BC.Exit = SpillPlacement::PrefSpill;
1010 ++Ins;
1011 } else if (Intf.last() > BI.FirstInstr) {
1012 ++Ins;
1013 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001014 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001015
1016 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001017 while (Ins--)
1018 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001019 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001020 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001021
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001022 // Add constraints for use-blocks. Note that these are the only constraints
1023 // that may add a positive bias, it is downhill from here.
1024 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001025 return SpillPlacer->scanActiveBundles();
1026}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001027
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001028
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001029/// addThroughConstraints - Add constraints and links to SpillPlacer from the
1030/// live-through blocks in Blocks.
1031void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
1032 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001033 const unsigned GroupSize = 8;
1034 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001035 unsigned TBS[GroupSize];
1036 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001037
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001038 for (unsigned i = 0; i != Blocks.size(); ++i) {
1039 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001040 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001041
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001042 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001043 assert(T < GroupSize && "Array overflow");
1044 TBS[T] = Number;
1045 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001046 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001047 T = 0;
1048 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001049 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001050 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001051
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001052 assert(B < GroupSize && "Array overflow");
1053 BCS[B].Number = Number;
1054
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001055 // Interference for the live-in value.
1056 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
1057 BCS[B].Entry = SpillPlacement::MustSpill;
1058 else
1059 BCS[B].Entry = SpillPlacement::PrefSpill;
1060
1061 // Interference for the live-out value.
1062 if (Intf.last() >= SA->getLastSplitPoint(Number))
1063 BCS[B].Exit = SpillPlacement::MustSpill;
1064 else
1065 BCS[B].Exit = SpillPlacement::PrefSpill;
1066
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001067 if (++B == GroupSize) {
Craig Toppere1d12942014-08-27 05:25:25 +00001068 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001069 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001070 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001071 }
1072
Craig Toppere1d12942014-08-27 05:25:25 +00001073 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001074 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001075}
1076
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001077void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001078 // Keep track of through blocks that have not been added to SpillPlacer.
1079 BitVector Todo = SA->getThroughBlocks();
1080 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
1081 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001082#ifndef NDEBUG
1083 unsigned Visited = 0;
1084#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001085
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001086 for (;;) {
1087 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001088 // Find new through blocks in the periphery of PrefRegBundles.
1089 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
1090 unsigned Bundle = NewBundles[i];
1091 // Look at all blocks connected to Bundle in the full graph.
1092 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
1093 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
1094 I != E; ++I) {
1095 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001096 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001097 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001098 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001099 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001100 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001101#ifndef NDEBUG
1102 ++Visited;
1103#endif
1104 }
1105 }
1106 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001107 if (ActiveBlocks.size() == AddedTo)
1108 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001109
1110 // Compute through constraints from the interference, or assume that all
1111 // through blocks prefer spilling when forming compact regions.
Craig Toppere1d12942014-08-27 05:25:25 +00001112 auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001113 if (Cand.PhysReg)
1114 addThroughConstraints(Cand.Intf, NewBlocks);
1115 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +00001116 // Provide a strong negative bias on through blocks to prevent unwanted
1117 // liveness on loop backedges.
1118 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001119 AddedTo = ActiveBlocks.size();
1120
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001121 // Perhaps iterating can enable more bundles?
1122 SpillPlacer->iterate();
1123 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001124 DEBUG(dbgs() << ", v=" << Visited);
1125}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001126
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001127/// calcCompactRegion - Compute the set of edge bundles that should be live
1128/// when splitting the current live range into compact regions. Compact
1129/// regions can be computed without looking at interference. They are the
1130/// regions formed by removing all the live-through blocks from the live range.
1131///
1132/// Returns false if the current live range is already compact, or if the
1133/// compact regions would form single block regions anyway.
1134bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1135 // Without any through blocks, the live range is already compact.
1136 if (!SA->getNumThroughBlocks())
1137 return false;
1138
1139 // Compact regions don't correspond to any physreg.
1140 Cand.reset(IntfCache, 0);
1141
1142 DEBUG(dbgs() << "Compact region bundles");
1143
1144 // Use the spill placer to determine the live bundles. GrowRegion pretends
1145 // that all the through blocks have interference when PhysReg is unset.
1146 SpillPlacer->prepare(Cand.LiveBundles);
1147
1148 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001149 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001150 if (!addSplitConstraints(Cand.Intf, Cost)) {
1151 DEBUG(dbgs() << ", none.\n");
1152 return false;
1153 }
1154
1155 growRegion(Cand);
1156 SpillPlacer->finish();
1157
1158 if (!Cand.LiveBundles.any()) {
1159 DEBUG(dbgs() << ", none.\n");
1160 return false;
1161 }
1162
1163 DEBUG({
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001164 for (int i : Cand.LiveBundles.set_bits())
1165 dbgs() << " EB#" << i;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001166 dbgs() << ".\n";
1167 });
1168 return true;
1169}
1170
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001171/// calcSpillCost - Compute how expensive it would be to split the live range in
1172/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001173BlockFrequency RAGreedy::calcSpillCost() {
1174 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001175 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1176 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1177 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1178 unsigned Number = BI.MBB->getNumber();
1179 // We normally only need one spill instruction - a load or a store.
1180 Cost += SpillPlacer->getBlockFrequency(Number);
1181
1182 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +00001183 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1184 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001185 }
1186 return Cost;
1187}
1188
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001189/// calcGlobalSplitCost - Return the global split cost of following the split
1190/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001191/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001192///
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001193BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1194 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001195 const BitVector &LiveBundles = Cand.LiveBundles;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001196 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1197 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1198 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001199 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001200 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1201 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1202 unsigned Ins = 0;
1203
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001204 if (BI.LiveIn)
1205 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1206 if (BI.LiveOut)
1207 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001208 while (Ins--)
1209 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001210 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001211
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001212 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1213 unsigned Number = Cand.ActiveBlocks[i];
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001214 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1215 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001216 if (!RegIn && !RegOut)
1217 continue;
1218 if (RegIn && RegOut) {
1219 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001220 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001221 if (Cand.Intf.hasInterference()) {
1222 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1223 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1224 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001225 continue;
1226 }
1227 // live-in / stack-out or stack-in live-out.
1228 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001229 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001230 return GlobalCost;
1231}
1232
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001233/// splitAroundRegion - Split the current live range around the regions
1234/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001235///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001236/// Before calling this function, GlobalCand and BundleCand must be initialized
1237/// so each bundle is assigned to a valid candidate, or NoCand for the
1238/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1239/// objects must be initialized for the current live range, and intervals
1240/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001241///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001242/// @param LREdit The LiveRangeEdit object handling the current split.
1243/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1244/// must appear in this list.
1245void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1246 ArrayRef<unsigned> UsedCands) {
1247 // These are the intervals created for new global ranges. We may create more
1248 // intervals for local ranges.
1249 const unsigned NumGlobalIntvs = LREdit.size();
1250 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1251 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001252
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001253 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001254 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001255 // is all copies.
1256 unsigned Reg = SA->getParent().reg;
1257 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1258
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001259 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001260 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1261 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1262 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001263 unsigned Number = BI.MBB->getNumber();
1264 unsigned IntvIn = 0, IntvOut = 0;
1265 SlotIndex IntfIn, IntfOut;
1266 if (BI.LiveIn) {
1267 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1268 if (CandIn != NoCand) {
1269 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1270 IntvIn = Cand.IntvIdx;
1271 Cand.Intf.moveToBlock(Number);
1272 IntfIn = Cand.Intf.first();
1273 }
1274 }
1275 if (BI.LiveOut) {
1276 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1277 if (CandOut != NoCand) {
1278 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1279 IntvOut = Cand.IntvIdx;
1280 Cand.Intf.moveToBlock(Number);
1281 IntfOut = Cand.Intf.last();
1282 }
1283 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001284
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001285 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001286 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001287 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001288 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001289 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001290 continue;
1291 }
1292
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001293 if (IntvIn && IntvOut)
1294 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1295 else if (IntvIn)
1296 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001297 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001298 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001299 }
1300
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001301 // Handle live-through blocks. The relevant live-through blocks are stored in
1302 // the ActiveBlocks list with each candidate. We need to filter out
1303 // duplicates.
1304 BitVector Todo = SA->getThroughBlocks();
1305 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1306 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1307 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1308 unsigned Number = Blocks[i];
1309 if (!Todo.test(Number))
1310 continue;
1311 Todo.reset(Number);
1312
1313 unsigned IntvIn = 0, IntvOut = 0;
1314 SlotIndex IntfIn, IntfOut;
1315
1316 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1317 if (CandIn != NoCand) {
1318 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1319 IntvIn = Cand.IntvIdx;
1320 Cand.Intf.moveToBlock(Number);
1321 IntfIn = Cand.Intf.first();
1322 }
1323
1324 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1325 if (CandOut != NoCand) {
1326 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1327 IntvOut = Cand.IntvIdx;
1328 Cand.Intf.moveToBlock(Number);
1329 IntfOut = Cand.Intf.last();
1330 }
1331 if (!IntvIn && !IntvOut)
1332 continue;
1333 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1334 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001335 }
1336
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001337 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001338
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001339 SmallVector<unsigned, 8> IntvMap;
1340 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001341 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001342
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001343 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001344 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001345
1346 // Sort out the new intervals created by splitting. We get four kinds:
1347 // - Remainder intervals should not be split again.
1348 // - Candidate intervals can be assigned to Cand.PhysReg.
1349 // - Block-local splits are candidates for local splitting.
1350 // - DCE leftovers should go back on the queue.
1351 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001352 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001353
1354 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001355 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001356 continue;
1357
1358 // Remainder interval. Don't try splitting again, spill if it doesn't
1359 // allocate.
1360 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001361 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001362 continue;
1363 }
1364
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001365 // Global intervals. Allow repeated splitting as long as the number of live
1366 // blocks is strictly decreasing.
1367 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001368 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001369 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1370 << " blocks as original.\n");
1371 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001372 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001373 }
1374 continue;
1375 }
1376
1377 // Other intervals are treated as new. This includes local intervals created
1378 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001379 }
1380
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001381 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001382 MF->verify(this, "After splitting live range around region");
1383}
1384
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001385unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001386 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001387 unsigned NumCands = 0;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001388 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001389
1390 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001391 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001392 if (HasCompact) {
1393 // Yes, keep GlobalCand[0] as the compact region candidate.
1394 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001395 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001396 } else {
1397 // No benefit from the compact region, our fallback will be per-block
1398 // splitting. Make sure we find a solution that is cheaper than spilling.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001399 BestCost = calcSpillCost();
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001400 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1401 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001402 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001403
Manman Ren9db66b32014-03-24 23:23:42 +00001404 unsigned BestCand =
Manman Ren78cf02a2014-03-25 00:16:25 +00001405 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1406 false/*IgnoreCSR*/);
Manman Ren9db66b32014-03-24 23:23:42 +00001407
1408 // No solutions found, fall back to single block splitting.
1409 if (!HasCompact && BestCand == NoCand)
1410 return 0;
1411
1412 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1413}
1414
1415unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1416 AllocationOrder &Order,
1417 BlockFrequency &BestCost,
Manman Ren78cf02a2014-03-25 00:16:25 +00001418 unsigned &NumCands,
1419 bool IgnoreCSR) {
Manman Ren9db66b32014-03-24 23:23:42 +00001420 unsigned BestCand = NoCand;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001421 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001422 while (unsigned PhysReg = Order.next()) {
Matthias Braun953393a2015-07-14 17:38:17 +00001423 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1424 continue;
Manman Ren78cf02a2014-03-25 00:16:25 +00001425
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001426 // Discard bad candidates before we run out of interference cache cursors.
1427 // This will only affect register classes with a lot of registers (>32).
1428 if (NumCands == IntfCache.getMaxCursors()) {
1429 unsigned WorstCount = ~0u;
1430 unsigned Worst = 0;
1431 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001432 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001433 continue;
1434 unsigned Count = GlobalCand[i].LiveBundles.count();
Richard Trieu7a083812016-02-18 22:09:30 +00001435 if (Count < WorstCount) {
1436 Worst = i;
1437 WorstCount = Count;
1438 }
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001439 }
1440 --NumCands;
1441 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001442 if (BestCand == NumCands)
1443 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001444 }
1445
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001446 if (GlobalCand.size() <= NumCands)
1447 GlobalCand.resize(NumCands+1);
1448 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1449 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001450
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001451 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001452 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001453 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001454 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001455 continue;
1456 }
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001457 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1458 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001459 if (Cost >= BestCost) {
1460 DEBUG({
1461 if (BestCand == NoCand)
1462 dbgs() << " worse than no bundles\n";
1463 else
1464 dbgs() << " worse than "
1465 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1466 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001467 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001468 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001469 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001470
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001471 SpillPlacer->finish();
1472
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001473 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001474 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001475 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001476 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001477 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001478
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001479 Cost += calcGlobalSplitCost(Cand);
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001480 DEBUG({
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001481 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1482 << " with bundles";
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001483 for (int i : Cand.LiveBundles.set_bits())
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001484 dbgs() << " EB#" << i;
1485 dbgs() << ".\n";
1486 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001487 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001488 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001489 BestCost = Cost;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001490 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001491 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001492 }
Manman Ren9db66b32014-03-24 23:23:42 +00001493 return BestCand;
1494}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001495
Manman Ren9db66b32014-03-24 23:23:42 +00001496unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1497 bool HasCompact,
1498 SmallVectorImpl<unsigned> &NewVRegs) {
1499 SmallVector<unsigned, 8> UsedCands;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001500 // Prepare split editor.
Wei Mi9a16d652016-04-13 03:08:27 +00001501 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001502 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001503
1504 // Assign all edge bundles to the preferred candidate, or NoCand.
1505 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1506
1507 // Assign bundles for the best candidate region.
1508 if (BestCand != NoCand) {
1509 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1510 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1511 UsedCands.push_back(BestCand);
1512 Cand.IntvIdx = SE->openIntv();
1513 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1514 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001515 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001516 }
1517 }
1518
1519 // Assign bundles for the compact region.
1520 if (HasCompact) {
1521 GlobalSplitCandidate &Cand = GlobalCand.front();
1522 assert(!Cand.PhysReg && "Compact region has no physreg");
1523 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1524 UsedCands.push_back(0);
1525 Cand.IntvIdx = SE->openIntv();
1526 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1527 << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001528 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001529 }
1530 }
1531
1532 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001533 return 0;
1534}
1535
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001536
1537//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001538// Per-Block Splitting
1539//===----------------------------------------------------------------------===//
1540
1541/// tryBlockSplit - Split a global live range around every block with uses. This
1542/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1543/// they don't allocate.
1544unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001545 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001546 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1547 unsigned Reg = VirtReg.reg;
1548 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Wei Mi9a16d652016-04-13 03:08:27 +00001549 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001550 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001551 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1552 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1553 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1554 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1555 SE->splitSingleBlock(BI);
1556 }
1557 // No blocks were split.
1558 if (LREdit.empty())
1559 return 0;
1560
1561 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001562 SmallVector<unsigned, 8> IntvMap;
1563 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001564
1565 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00001566 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001567
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001568 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1569
1570 // Sort out the new intervals created by splitting. The remainder interval
1571 // goes straight to spilling, the new local ranges get to stay RS_New.
1572 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001573 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001574 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1575 setStage(LI, RS_Spill);
1576 }
1577
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001578 if (VerifyEnabled)
1579 MF->verify(this, "After splitting live range around basic blocks");
1580 return 0;
1581}
1582
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001583
1584//===----------------------------------------------------------------------===//
1585// Per-Instruction Splitting
1586//===----------------------------------------------------------------------===//
1587
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001588/// Get the number of allocatable registers that match the constraints of \p Reg
1589/// on \p MI and that are also in \p SuperRC.
1590static unsigned getNumAllocatableRegsForConstraints(
1591 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1592 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1593 const RegisterClassInfo &RCI) {
1594 assert(SuperRC && "Invalid register class");
1595
1596 const TargetRegisterClass *ConstrainedRC =
1597 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1598 /* ExploreBundle */ true);
1599 if (!ConstrainedRC)
1600 return 0;
1601 return RCI.getNumAllocatableRegs(ConstrainedRC);
1602}
1603
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001604/// tryInstructionSplit - Split a live range around individual instructions.
1605/// This is normally not worthwhile since the spiller is doing essentially the
1606/// same thing. However, when the live range is in a constrained register
1607/// class, it may help to insert copies such that parts of the live range can
1608/// be moved to a larger register class.
1609///
1610/// This is similar to spilling to a larger register class.
1611unsigned
1612RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001613 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001614 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001615 // There is no point to this if there are no larger sub-classes.
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001616 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001617 return 0;
1618
1619 // Always enable split spill mode, since we're effectively spilling to a
1620 // register.
Wei Mi9a16d652016-04-13 03:08:27 +00001621 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001622 SE->reset(LREdit, SplitEditor::SM_Size);
1623
1624 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1625 if (Uses.size() <= 1)
1626 return 0;
1627
1628 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1629
Eric Christopher433c4322015-03-10 23:46:01 +00001630 const TargetRegisterClass *SuperRC =
1631 TRI->getLargestLegalSuperClass(CurRC, *MF);
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001632 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1633 // Split around every non-copy instruction if this split will relax
1634 // the constraints on the virtual register.
1635 // Otherwise, splitting just inserts uncoalescable copies that do not help
1636 // the allocation.
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001637 for (unsigned i = 0; i != Uses.size(); ++i) {
1638 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001639 if (MI->isFullCopy() ||
1640 SuperRCNumAllocatableRegs ==
1641 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1642 TRI, RCI)) {
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001643 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1644 continue;
1645 }
1646 SE->openIntv();
1647 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1648 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1649 SE->useIntv(SegStart, SegStop);
1650 }
1651
1652 if (LREdit.empty()) {
1653 DEBUG(dbgs() << "All uses were copies.\n");
1654 return 0;
1655 }
1656
1657 SmallVector<unsigned, 8> IntvMap;
1658 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001659 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001660 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1661
1662 // Assign all new registers to RS_Spill. This was the last chance.
1663 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1664 return 0;
1665}
1666
1667
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001668//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001669// Local Splitting
1670//===----------------------------------------------------------------------===//
1671
1672
1673/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1674/// in order to use PhysReg between two entries in SA->UseSlots.
1675///
1676/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1677///
1678void RAGreedy::calcGapWeights(unsigned PhysReg,
1679 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001680 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1681 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001682 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001683 const unsigned NumGaps = Uses.size()-1;
1684
1685 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001686 SlotIndex StartIdx =
1687 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1688 SlotIndex StopIdx =
1689 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001690
1691 GapWeight.assign(NumGaps, 0.0f);
1692
1693 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001694 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1695 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1696 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001697 continue;
1698
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001699 // We know that VirtReg is a continuous interval from FirstInstr to
1700 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001701 //
1702 // Interference that overlaps an instruction is counted in both gaps
1703 // surrounding the instruction. The exception is interference before
1704 // StartIdx and after StopIdx.
1705 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001706 LiveIntervalUnion::SegmentIter IntI =
1707 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001708 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1709 // Skip the gaps before IntI.
1710 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1711 if (++Gap == NumGaps)
1712 break;
1713 if (Gap == NumGaps)
1714 break;
1715
1716 // Update the gaps covered by IntI.
1717 const float weight = IntI.value()->weight;
1718 for (; Gap != NumGaps; ++Gap) {
1719 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1720 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1721 break;
1722 }
1723 if (Gap == NumGaps)
1724 break;
1725 }
1726 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001727
1728 // Add fixed interference.
1729 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001730 const LiveRange &LR = LIS->getRegUnit(*Units);
1731 LiveRange::const_iterator I = LR.find(StartIdx);
1732 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001733
1734 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1735 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1736 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1737 if (++Gap == NumGaps)
1738 break;
1739 if (Gap == NumGaps)
1740 break;
1741
1742 for (; Gap != NumGaps; ++Gap) {
Aaron Ballman04999042013-11-13 00:15:44 +00001743 GapWeight[Gap] = llvm::huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001744 if (Uses[Gap+1].getBaseIndex() >= I->end)
1745 break;
1746 }
1747 if (Gap == NumGaps)
1748 break;
1749 }
1750 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001751}
1752
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001753/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1754/// basic block.
1755///
1756unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001757 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001758 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1759 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001760
1761 // Note that it is possible to have an interval that is live-in or live-out
1762 // while only covering a single block - A phi-def can use undef values from
1763 // predecessors, and the block could be a single-block loop.
1764 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00001765 // that the interval is continuous from FirstInstr to LastInstr. We should
1766 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001767
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001768 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001769 if (Uses.size() <= 2)
1770 return 0;
1771 const unsigned NumGaps = Uses.size()-1;
1772
1773 DEBUG({
1774 dbgs() << "tryLocalSplit: ";
1775 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00001776 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001777 dbgs() << '\n';
1778 });
1779
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001780 // If VirtReg is live across any register mask operands, compute a list of
1781 // gaps with register masks.
1782 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001783 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001784 // Get regmask slots for the whole block.
1785 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001786 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001787 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001788 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1789 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001790 unsigned re = RMS.size();
1791 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001792 // Look for Uses[i] <= RMS <= Uses[i+1].
1793 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1794 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001795 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001796 // Skip a regmask on the same instruction as the last use. It doesn't
1797 // overlap the live range.
1798 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1799 break;
1800 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001801 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001802 // Advance ri to the next gap. A regmask on one of the uses counts in
1803 // both gaps.
1804 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1805 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001806 }
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00001807 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001808 }
1809
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001810 // Since we allow local split results to be split again, there is a risk of
1811 // creating infinite loops. It is tempting to require that the new live
1812 // ranges have less instructions than the original. That would guarantee
1813 // convergence, but it is too strict. A live range with 3 instructions can be
1814 // split 2+3 (including the COPY), and we want to allow that.
1815 //
1816 // Instead we use these rules:
1817 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001818 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001819 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001820 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001821 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001822 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001823 // smaller ranges are marked RS_New.
1824 //
1825 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1826 // excessive splitting and infinite loops.
1827 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001828 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001829
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001830 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001831 unsigned BestBefore = NumGaps;
1832 unsigned BestAfter = 0;
1833 float BestDiff = 0;
1834
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001835 const float blockFreq =
1836 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Michael Gottesman5e985ee2013-12-14 02:37:38 +00001837 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001838 SmallVector<float, 8> GapWeight;
1839
1840 Order.rewind();
1841 while (unsigned PhysReg = Order.next()) {
1842 // Keep track of the largest spill weight that would need to be evicted in
1843 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1844 calcGapWeights(PhysReg, GapWeight);
1845
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001846 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001847 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001848 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Aaron Ballman04999042013-11-13 00:15:44 +00001849 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00001850
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001851 // Try to find the best sequence of gaps to close.
1852 // The new spill weight must be larger than any gap interference.
1853
1854 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001855 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001856
1857 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1858 // It is the spill weight that needs to be evicted.
1859 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001860
1861 for (;;) {
1862 // Live before/after split?
1863 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1864 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1865
1866 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1867 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1868 << " i=" << MaxGap);
1869
1870 // Stop before the interval gets so big we wouldn't be making progress.
1871 if (!LiveBefore && !LiveAfter) {
1872 DEBUG(dbgs() << " all\n");
1873 break;
1874 }
1875 // Should the interval be extended or shrunk?
1876 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001877
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001878 // How many gaps would the new range have?
1879 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1880
1881 // Legally, without causing looping?
1882 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1883
Aaron Ballman04999042013-11-13 00:15:44 +00001884 if (Legal && MaxGap < llvm::huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001885 // Estimate the new spill weight. Each instruction reads or writes the
1886 // register. Conservatively assume there are no read-modify-write
1887 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001888 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001889 // Try to guess the size of the new interval.
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +00001890 const float EstWeight = normalizeSpillWeight(
1891 blockFreq * (NewGaps + 1),
1892 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1893 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
1894 1);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001895 // Would this split be possible to allocate?
1896 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001897 DEBUG(dbgs() << " w=" << EstWeight);
1898 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001899 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001900 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001901 if (Diff > BestDiff) {
1902 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00001903 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001904 BestBefore = SplitBefore;
1905 BestAfter = SplitAfter;
1906 }
1907 }
1908 }
1909
1910 // Try to shrink.
1911 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001912 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001913 DEBUG(dbgs() << " shrink\n");
1914 // Recompute the max when necessary.
1915 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1916 MaxGap = GapWeight[SplitBefore];
1917 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1918 MaxGap = std::max(MaxGap, GapWeight[i]);
1919 }
1920 continue;
1921 }
1922 MaxGap = 0;
1923 }
1924
1925 // Try to extend the interval.
1926 if (SplitAfter >= NumGaps) {
1927 DEBUG(dbgs() << " end\n");
1928 break;
1929 }
1930
1931 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001932 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001933 }
1934 }
1935
1936 // Didn't find any candidates?
1937 if (BestBefore == NumGaps)
1938 return 0;
1939
1940 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1941 << '-' << Uses[BestAfter] << ", " << BestDiff
1942 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1943
Wei Mi9a16d652016-04-13 03:08:27 +00001944 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001945 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001946
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00001947 SE->openIntv();
1948 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1949 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1950 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001951 SmallVector<unsigned, 8> IntvMap;
1952 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001953 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001954
1955 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001956 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001957 // leave the new intervals as RS_New so they can compete.
1958 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1959 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1960 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1961 if (NewGaps >= NumGaps) {
1962 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1963 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001964 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1965 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001966 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1967 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00001968 }
1969 DEBUG(dbgs() << '\n');
1970 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001971 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001972
1973 return 0;
1974}
1975
1976//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001977// Live Range Splitting
1978//===----------------------------------------------------------------------===//
1979
1980/// trySplit - Try to split VirtReg or one of its interferences, making it
1981/// assignable.
1982/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1983unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001984 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00001985 // Ranges must be Split2 or less.
1986 if (getStage(VirtReg) >= RS_Spill)
1987 return 0;
1988
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00001989 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001990 if (LIS->intervalIsInOneMBB(VirtReg)) {
Matthias Braun9f15a792016-11-18 19:43:18 +00001991 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
1992 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00001993 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001994 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1995 if (PhysReg || !NewVRegs.empty())
1996 return PhysReg;
1997 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00001998 }
1999
Matthias Braun9f15a792016-11-18 19:43:18 +00002000 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
2001 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002002
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002003 SA->analyze(&VirtReg);
2004
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002005 // FIXME: SplitAnalysis may repair broken live ranges coming from the
2006 // coalescer. That may cause the range to become allocatable which means that
2007 // tryRegionSplit won't be making progress. This check should be replaced with
2008 // an assertion when the coalescer is fixed.
2009 if (SA->didRepairRange()) {
2010 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002011 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002012 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
2013 return PhysReg;
2014 }
2015
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002016 // First try to split around a region spanning multiple blocks. RS_Split2
2017 // ranges already made dubious progress with region splitting, so they go
2018 // straight to single block splitting.
2019 if (getStage(VirtReg) < RS_Split2) {
2020 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2021 if (PhysReg || !NewVRegs.empty())
2022 return PhysReg;
2023 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002024
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00002025 // Then isolate blocks.
2026 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002027}
2028
Quentin Colombet87769712014-02-05 22:13:59 +00002029//===----------------------------------------------------------------------===//
2030// Last Chance Recoloring
2031//===----------------------------------------------------------------------===//
2032
2033/// mayRecolorAllInterferences - Check if the virtual registers that
2034/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2035/// recolored to free \p PhysReg.
2036/// When true is returned, \p RecoloringCandidates has been augmented with all
2037/// the live intervals that need to be recolored in order to free \p PhysReg
2038/// for \p VirtReg.
2039/// \p FixedRegisters contains all the virtual registers that cannot be
2040/// recolored.
2041bool
2042RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
2043 SmallLISet &RecoloringCandidates,
2044 const SmallVirtRegSet &FixedRegisters) {
2045 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
2046
2047 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2048 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
2049 // If there is LastChanceRecoloringMaxInterference or more interferences,
2050 // chances are one would not be recolorable.
2051 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
Quentin Colombet567e30b2014-04-11 21:39:44 +00002052 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00002053 DEBUG(dbgs() << "Early abort: too many interferences.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002054 CutOffInfo |= CO_Interf;
Quentin Colombet87769712014-02-05 22:13:59 +00002055 return false;
2056 }
2057 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
2058 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
2059 // If Intf is done and sit on the same register class as VirtReg,
2060 // it would not be recolorable as it is in the same state as VirtReg.
2061 if ((getStage(*Intf) == RS_Done &&
2062 MRI->getRegClass(Intf->reg) == CurRC) ||
2063 FixedRegisters.count(Intf->reg)) {
2064 DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
2065 return false;
2066 }
2067 RecoloringCandidates.insert(Intf);
2068 }
2069 }
2070 return true;
2071}
2072
2073/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2074/// its interferences.
2075/// Last chance recoloring chooses a color for \p VirtReg and recolors every
2076/// virtual register that was using it. The recoloring process may recursively
2077/// use the last chance recoloring. Therefore, when a virtual register has been
2078/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2079/// be last-chance-recolored again during this recoloring "session".
2080/// E.g.,
2081/// Let
2082/// vA can use {R1, R2 }
2083/// vB can use { R2, R3}
2084/// vC can use {R1 }
2085/// Where vA, vB, and vC cannot be split anymore (they are reloads for
2086/// instance) and they all interfere.
2087///
2088/// vA is assigned R1
2089/// vB is assigned R2
2090/// vC tries to evict vA but vA is already done.
2091/// Regular register allocation fails.
2092///
2093/// Last chance recoloring kicks in:
2094/// vC does as if vA was evicted => vC uses R1.
2095/// vC is marked as fixed.
2096/// vA needs to find a color.
2097/// None are available.
2098/// vA cannot evict vC: vC is a fixed virtual register now.
2099/// vA does as if vB was evicted => vA uses R2.
2100/// vB needs to find a color.
2101/// R3 is available.
2102/// Recoloring => vC = R1, vA = R2, vB = R3
2103///
Alp Toker70b36992014-02-25 04:21:15 +00002104/// \p Order defines the preferred allocation order for \p VirtReg.
Quentin Colombet87769712014-02-05 22:13:59 +00002105/// \p NewRegs will contain any new virtual register that have been created
2106/// (split, spill) during the process and that must be assigned.
2107/// \p FixedRegisters contains all the virtual registers that cannot be
2108/// recolored.
2109/// \p Depth gives the current depth of the last chance recoloring.
2110/// \return a physical register that can be used for VirtReg or ~0u if none
2111/// exists.
2112unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2113 AllocationOrder &Order,
2114 SmallVectorImpl<unsigned> &NewVRegs,
2115 SmallVirtRegSet &FixedRegisters,
2116 unsigned Depth) {
2117 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2118 // Ranges must be Done.
Quentin Colombet0e3b5e02014-02-13 05:17:37 +00002119 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
Quentin Colombet87769712014-02-05 22:13:59 +00002120 "Last chance recoloring should really be last chance");
2121 // Set the max depth to LastChanceRecoloringMaxDepth.
2122 // We may want to reconsider that if we end up with a too large search space
2123 // for target with hundreds of registers.
2124 // Indeed, in that case we may want to cut the search space earlier.
Quentin Colombet567e30b2014-04-11 21:39:44 +00002125 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00002126 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002127 CutOffInfo |= CO_Depth;
Quentin Colombet87769712014-02-05 22:13:59 +00002128 return ~0u;
2129 }
2130
2131 // Set of Live intervals that will need to be recolored.
2132 SmallLISet RecoloringCandidates;
2133 // Record the original mapping virtual register to physical register in case
2134 // the recoloring fails.
2135 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2136 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2137 // this recoloring "session".
2138 FixedRegisters.insert(VirtReg.reg);
Quentin Colombet318582f2016-09-16 22:00:50 +00002139 SmallVector<unsigned, 4> CurrentNewVRegs;
Quentin Colombet87769712014-02-05 22:13:59 +00002140
2141 Order.rewind();
2142 while (unsigned PhysReg = Order.next()) {
2143 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2144 << PrintReg(PhysReg, TRI) << '\n');
2145 RecoloringCandidates.clear();
2146 VirtRegToPhysReg.clear();
Quentin Colombet318582f2016-09-16 22:00:50 +00002147 CurrentNewVRegs.clear();
Quentin Colombet87769712014-02-05 22:13:59 +00002148
2149 // It is only possible to recolor virtual register interference.
2150 if (Matrix->checkInterference(VirtReg, PhysReg) >
2151 LiveRegMatrix::IK_VirtReg) {
2152 DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2153
2154 continue;
2155 }
2156
2157 // Early give up on this PhysReg if it is obvious we cannot recolor all
2158 // the interferences.
2159 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2160 FixedRegisters)) {
2161 DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2162 continue;
2163 }
2164
2165 // RecoloringCandidates contains all the virtual registers that interfer
2166 // with VirtReg on PhysReg (or one of its aliases).
2167 // Enqueue them for recoloring and perform the actual recoloring.
2168 PQueue RecoloringQueue;
2169 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2170 EndIt = RecoloringCandidates.end();
2171 It != EndIt; ++It) {
2172 unsigned ItVirtReg = (*It)->reg;
2173 enqueue(RecoloringQueue, *It);
2174 assert(VRM->hasPhys(ItVirtReg) &&
2175 "Interferences are supposed to be with allocated vairables");
2176
2177 // Record the current allocation.
2178 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2179 // unset the related struct.
2180 Matrix->unassign(**It);
2181 }
2182
2183 // Do as if VirtReg was assigned to PhysReg so that the underlying
2184 // recoloring has the right information about the interferes and
2185 // available colors.
2186 Matrix->assign(VirtReg, PhysReg);
2187
2188 // Save the current recoloring state.
2189 // If we cannot recolor all the interferences, we will have to start again
2190 // at this point for the next physical register.
2191 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
Quentin Colombet318582f2016-09-16 22:00:50 +00002192 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2193 FixedRegisters, Depth)) {
2194 // Push the queued vregs into the main queue.
2195 for (unsigned NewVReg : CurrentNewVRegs)
2196 NewVRegs.push_back(NewVReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002197 // Do not mess up with the global assignment process.
2198 // I.e., VirtReg must be unassigned.
2199 Matrix->unassign(VirtReg);
2200 return PhysReg;
2201 }
2202
2203 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2204 << PrintReg(PhysReg, TRI) << '\n');
2205
2206 // The recoloring attempt failed, undo the changes.
2207 FixedRegisters = SaveFixedRegisters;
2208 Matrix->unassign(VirtReg);
2209
Wei Mib5cf9e52016-11-08 18:19:36 +00002210 // For a newly created vreg which is also in RecoloringCandidates,
2211 // don't add it to NewVRegs because its physical register will be restored
2212 // below. Other vregs in CurrentNewVRegs are created by calling
2213 // selectOrSplit and should be added into NewVRegs.
Quentin Colombet318582f2016-09-16 22:00:50 +00002214 for (SmallVectorImpl<unsigned>::iterator Next = CurrentNewVRegs.begin(),
2215 End = CurrentNewVRegs.end();
2216 Next != End; ++Next) {
Wei Mib5cf9e52016-11-08 18:19:36 +00002217 if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
Quentin Colombet318582f2016-09-16 22:00:50 +00002218 continue;
2219 NewVRegs.push_back(*Next);
2220 }
2221
Quentin Colombet87769712014-02-05 22:13:59 +00002222 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2223 EndIt = RecoloringCandidates.end();
2224 It != EndIt; ++It) {
2225 unsigned ItVirtReg = (*It)->reg;
2226 if (VRM->hasPhys(ItVirtReg))
2227 Matrix->unassign(**It);
Matthias Braun953393a2015-07-14 17:38:17 +00002228 unsigned ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2229 Matrix->assign(**It, ItPhysReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002230 }
2231 }
2232
2233 // Last chance recoloring did not worked either, give up.
2234 return ~0u;
2235}
2236
2237/// tryRecoloringCandidates - Try to assign a new color to every register
2238/// in \RecoloringQueue.
2239/// \p NewRegs will contain any new virtual register created during the
2240/// recoloring process.
2241/// \p FixedRegisters[in/out] contains all the registers that have been
2242/// recolored.
2243/// \return true if all virtual registers in RecoloringQueue were successfully
2244/// recolored, false otherwise.
2245bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2246 SmallVectorImpl<unsigned> &NewVRegs,
2247 SmallVirtRegSet &FixedRegisters,
2248 unsigned Depth) {
2249 while (!RecoloringQueue.empty()) {
2250 LiveInterval *LI = dequeue(RecoloringQueue);
2251 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2252 unsigned PhysReg;
2253 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
Quentin Colombet52ffa672016-10-13 19:27:48 +00002254 // When splitting happens, the live-range may actually be empty.
2255 // In that case, this is okay to continue the recoloring even
2256 // if we did not find an alternative color for it. Indeed,
2257 // there will not be anything to color for LI in the end.
2258 if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
Quentin Colombet87769712014-02-05 22:13:59 +00002259 return false;
Quentin Colombet52ffa672016-10-13 19:27:48 +00002260
2261 if (!PhysReg) {
2262 assert(LI->empty() && "Only empty live-range do not require a register");
2263 DEBUG(dbgs() << "Recoloring of " << *LI << " succeeded. Empty LI.\n");
2264 continue;
2265 }
Quentin Colombet87769712014-02-05 22:13:59 +00002266 DEBUG(dbgs() << "Recoloring of " << *LI
2267 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
Quentin Colombet52ffa672016-10-13 19:27:48 +00002268
Quentin Colombet87769712014-02-05 22:13:59 +00002269 Matrix->assign(*LI, PhysReg);
2270 FixedRegisters.insert(LI->reg);
2271 }
2272 return true;
2273}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002274
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002275//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002276// Main Entry Point
2277//===----------------------------------------------------------------------===//
2278
2279unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002280 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002281 CutOffInfo = CO_None;
2282 LLVMContext &Ctx = MF->getFunction()->getContext();
Quentin Colombet87769712014-02-05 22:13:59 +00002283 SmallVirtRegSet FixedRegisters;
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002284 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2285 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2286 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2287 if (CutOffEncountered == CO_Depth)
Quentin Colombet567e30b2014-04-11 21:39:44 +00002288 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2289 "reached. Use -fexhaustive-register-search to skip "
2290 "cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002291 else if (CutOffEncountered == CO_Interf)
2292 Ctx.emitError("register allocation failed: maximum interference for "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002293 "recoloring reached. Use -fexhaustive-register-search "
2294 "to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002295 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2296 Ctx.emitError("register allocation failed: maximum interference and "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002297 "depth for recoloring reached. Use "
2298 "-fexhaustive-register-search to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002299 }
2300 return Reg;
Quentin Colombet87769712014-02-05 22:13:59 +00002301}
2302
Manman Ren9dee4492014-03-27 21:21:57 +00002303/// Using a CSR for the first time has a cost because it causes push|pop
2304/// to be added to prologue|epilogue. Splitting a cold section of the live
2305/// range can have lower cost than using the CSR for the first time;
2306/// Spilling a live range in the cold path can have lower cost than using
2307/// the CSR for the first time. Returns the physical register if we decide
2308/// to use the CSR; otherwise return 0.
2309unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2310 AllocationOrder &Order,
2311 unsigned PhysReg,
2312 unsigned &CostPerUseLimit,
2313 SmallVectorImpl<unsigned> &NewVRegs) {
Manman Ren9dee4492014-03-27 21:21:57 +00002314 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2315 // We choose spill over using the CSR for the first time if the spill cost
2316 // is lower than CSRCost.
2317 SA->analyze(&VirtReg);
2318 if (calcSpillCost() >= CSRCost)
2319 return PhysReg;
2320
2321 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2322 // we will not use a callee-saved register in tryEvict.
2323 CostPerUseLimit = 1;
2324 return 0;
2325 }
2326 if (getStage(VirtReg) < RS_Split) {
2327 // We choose pre-splitting over using the CSR for the first time if
2328 // the cost of splitting is lower than CSRCost.
2329 SA->analyze(&VirtReg);
2330 unsigned NumCands = 0;
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002331 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2332 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2333 NumCands, true /*IgnoreCSR*/);
Manman Ren9dee4492014-03-27 21:21:57 +00002334 if (BestCand == NoCand)
2335 // Use the CSR if we can't find a region split below CSRCost.
2336 return PhysReg;
2337
2338 // Perform the actual pre-splitting.
2339 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2340 return 0;
2341 }
2342 return PhysReg;
2343}
2344
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002345void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
2346 // Do not keep invalid information around.
2347 SetOfBrokenHints.remove(&LI);
2348}
2349
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002350void RAGreedy::initializeCSRCost() {
2351 // We use the larger one out of the command-line option and the value report
2352 // by TRI.
2353 CSRCost = BlockFrequency(
2354 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2355 if (!CSRCost.getFrequency())
2356 return;
2357
2358 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2359 uint64_t ActualEntry = MBFI->getEntryFreq();
2360 if (!ActualEntry) {
2361 CSRCost = 0;
2362 return;
2363 }
2364 uint64_t FixedEntry = 1 << 14;
2365 if (ActualEntry < FixedEntry)
2366 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2367 else if (ActualEntry <= UINT32_MAX)
2368 // Invert the fraction and divide.
2369 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2370 else
2371 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2372 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2373}
2374
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002375/// \brief Collect the hint info for \p Reg.
2376/// The results are stored into \p Out.
2377/// \p Out is not cleared before being populated.
2378void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
2379 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2380 if (!Instr.isFullCopy())
2381 continue;
2382 // Look for the other end of the copy.
2383 unsigned OtherReg = Instr.getOperand(0).getReg();
2384 if (OtherReg == Reg) {
2385 OtherReg = Instr.getOperand(1).getReg();
2386 if (OtherReg == Reg)
2387 continue;
2388 }
2389 // Get the current assignment.
2390 unsigned OtherPhysReg = TargetRegisterInfo::isPhysicalRegister(OtherReg)
2391 ? OtherReg
2392 : VRM->getPhys(OtherReg);
2393 // Push the collected information.
2394 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2395 OtherPhysReg));
2396 }
2397}
2398
2399/// \brief Using the given \p List, compute the cost of the broken hints if
2400/// \p PhysReg was used.
2401/// \return The cost of \p List for \p PhysReg.
2402BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2403 unsigned PhysReg) {
2404 BlockFrequency Cost = 0;
2405 for (const HintInfo &Info : List) {
2406 if (Info.PhysReg != PhysReg)
2407 Cost += Info.Freq;
2408 }
2409 return Cost;
2410}
2411
2412/// \brief Using the register assigned to \p VirtReg, try to recolor
2413/// all the live ranges that are copy-related with \p VirtReg.
2414/// The recoloring is then propagated to all the live-ranges that have
2415/// been recolored and so on, until no more copies can be coalesced or
2416/// it is not profitable.
2417/// For a given live range, profitability is determined by the sum of the
2418/// frequencies of the non-identity copies it would introduce with the old
2419/// and new register.
2420void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
2421 // We have a broken hint, check if it is possible to fix it by
2422 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2423 // some register and PhysReg may be available for the other live-ranges.
2424 SmallSet<unsigned, 4> Visited;
2425 SmallVector<unsigned, 2> RecoloringCandidates;
2426 HintsInfo Info;
2427 unsigned Reg = VirtReg.reg;
2428 unsigned PhysReg = VRM->getPhys(Reg);
2429 // Start the recoloring algorithm from the input live-interval, then
2430 // it will propagate to the ones that are copy-related with it.
2431 Visited.insert(Reg);
2432 RecoloringCandidates.push_back(Reg);
2433
2434 DEBUG(dbgs() << "Trying to reconcile hints for: " << PrintReg(Reg, TRI) << '('
2435 << PrintReg(PhysReg, TRI) << ")\n");
2436
2437 do {
2438 Reg = RecoloringCandidates.pop_back_val();
2439
2440 // We cannot recolor physcal register.
2441 if (TargetRegisterInfo::isPhysicalRegister(Reg))
2442 continue;
2443
2444 assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
2445
2446 // Get the live interval mapped with this virtual register to be able
2447 // to check for the interference with the new color.
2448 LiveInterval &LI = LIS->getInterval(Reg);
2449 unsigned CurrPhys = VRM->getPhys(Reg);
2450 // Check that the new color matches the register class constraints and
2451 // that it is free for this live range.
2452 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2453 Matrix->checkInterference(LI, PhysReg)))
2454 continue;
2455
2456 DEBUG(dbgs() << PrintReg(Reg, TRI) << '(' << PrintReg(CurrPhys, TRI)
2457 << ") is recolorable.\n");
2458
2459 // Gather the hint info.
2460 Info.clear();
2461 collectHintInfo(Reg, Info);
2462 // Check if recoloring the live-range will increase the cost of the
2463 // non-identity copies.
2464 if (CurrPhys != PhysReg) {
2465 DEBUG(dbgs() << "Checking profitability:\n");
2466 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2467 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2468 DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2469 << "\nNew Cost: " << NewCopiesCost.getFrequency() << '\n');
2470 if (OldCopiesCost < NewCopiesCost) {
2471 DEBUG(dbgs() << "=> Not profitable.\n");
2472 continue;
2473 }
2474 // At this point, the cost is either cheaper or equal. If it is
2475 // equal, we consider this is profitable because it may expose
2476 // more recoloring opportunities.
2477 DEBUG(dbgs() << "=> Profitable.\n");
2478 // Recolor the live-range.
2479 Matrix->unassign(LI);
2480 Matrix->assign(LI, PhysReg);
2481 }
2482 // Push all copy-related live-ranges to keep reconciling the broken
2483 // hints.
2484 for (const HintInfo &HI : Info) {
2485 if (Visited.insert(HI.Reg).second)
2486 RecoloringCandidates.push_back(HI.Reg);
2487 }
2488 } while (!RecoloringCandidates.empty());
2489}
2490
2491/// \brief Try to recolor broken hints.
2492/// Broken hints may be repaired by recoloring when an evicted variable
2493/// freed up a register for a larger live-range.
2494/// Consider the following example:
2495/// BB1:
2496/// a =
2497/// b =
2498/// BB2:
2499/// ...
2500/// = b
2501/// = a
2502/// Let us assume b gets split:
2503/// BB1:
2504/// a =
2505/// b =
2506/// BB2:
2507/// c = b
2508/// ...
2509/// d = c
2510/// = d
2511/// = a
2512/// Because of how the allocation work, b, c, and d may be assigned different
2513/// colors. Now, if a gets evicted later:
2514/// BB1:
2515/// a =
2516/// st a, SpillSlot
2517/// b =
2518/// BB2:
2519/// c = b
2520/// ...
2521/// d = c
2522/// = d
2523/// e = ld SpillSlot
2524/// = e
2525/// This is likely that we can assign the same register for b, c, and d,
2526/// getting rid of 2 copies.
2527void RAGreedy::tryHintsRecoloring() {
2528 for (LiveInterval *LI : SetOfBrokenHints) {
2529 assert(TargetRegisterInfo::isVirtualRegister(LI->reg) &&
2530 "Recoloring is possible only for virtual registers");
2531 // Some dead defs may be around (e.g., because of debug uses).
2532 // Ignore those.
2533 if (!VRM->hasPhys(LI->reg))
2534 continue;
2535 tryHintRecoloring(*LI);
2536 }
2537}
2538
Quentin Colombet87769712014-02-05 22:13:59 +00002539unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2540 SmallVectorImpl<unsigned> &NewVRegs,
2541 SmallVirtRegSet &FixedRegisters,
2542 unsigned Depth) {
Manman Ren78cf02a2014-03-25 00:16:25 +00002543 unsigned CostPerUseLimit = ~0u;
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002544 // First try assigning a free register.
Matthias Braun5d1f12d2015-07-15 22:16:00 +00002545 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Manman Ren78cf02a2014-03-25 00:16:25 +00002546 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
Manman Ren9dee4492014-03-27 21:21:57 +00002547 // When NewVRegs is not empty, we may have made decisions such as evicting
2548 // a virtual register, go with the earlier decisions and use the physical
2549 // register.
Matthias Braun953393a2015-07-14 17:38:17 +00002550 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
2551 NewVRegs.empty()) {
Manman Ren9dee4492014-03-27 21:21:57 +00002552 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2553 CostPerUseLimit, NewVRegs);
2554 if (CSRReg || !NewVRegs.empty())
2555 // Return now if we decide to use a CSR or create new vregs due to
2556 // pre-splitting.
2557 return CSRReg;
Manman Ren78cf02a2014-03-25 00:16:25 +00002558 } else
2559 return PhysReg;
2560 }
Andrew Trickccef0982010-12-09 18:15:21 +00002561
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002562 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002563 DEBUG(dbgs() << StageName[Stage]
2564 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002565
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002566 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002567 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002568 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002569 if (Stage != RS_Split)
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002570 if (unsigned PhysReg =
2571 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit)) {
2572 unsigned Hint = MRI->getSimpleHint(VirtReg.reg);
2573 // If VirtReg has a hint and that hint is broken record this
2574 // virtual register as a recoloring candidate for broken hint.
2575 // Indeed, since we evicted a variable in its neighborhood it is
2576 // likely we can at least partially recolor some of the
2577 // copy-related live-ranges.
2578 if (Hint && Hint != PhysReg)
2579 SetOfBrokenHints.insert(&VirtReg);
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002580 return PhysReg;
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002581 }
Andrew Trickccef0982010-12-09 18:15:21 +00002582
Quentin Colombet63176862016-09-16 22:00:42 +00002583 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002584
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002585 // The first time we see a live range, don't try to split or spill.
2586 // Wait until the second time, when all smaller ranges have been allocated.
2587 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002588 if (Stage < RS_Split) {
2589 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +00002590 DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00002591 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002592 return 0;
2593 }
2594
Dylan McKayc328fe52016-10-11 01:04:36 +00002595 if (Stage < RS_Spill) {
2596 // Try splitting VirtReg or interferences.
2597 unsigned NewVRegSizeBefore = NewVRegs.size();
2598 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2599 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore))
2600 return PhysReg;
2601 }
2602
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00002603 // If we couldn't allocate a register from spilling, there is probably some
2604 // invalid inline assembly. The base class wil report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002605 if (Stage >= RS_Done || !VirtReg.isSpillable())
Quentin Colombet87769712014-02-05 22:13:59 +00002606 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2607 Depth);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002608
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002609 // Finally spill VirtReg itself.
Quentin Colombet11922942015-07-17 23:04:06 +00002610 if (EnableDeferredSpilling && getStage(VirtReg) < RS_Memory) {
2611 // TODO: This is experimental and in particular, we do not model
2612 // the live range splitting done by spilling correctly.
2613 // We would need a deep integration with the spiller to do the
2614 // right thing here. Anyway, that is still good for early testing.
2615 setStage(VirtReg, RS_Memory);
2616 DEBUG(dbgs() << "Do as if this register is in memory\n");
2617 NewVRegs.push_back(VirtReg.reg);
2618 } else {
Matthias Braun9f15a792016-11-18 19:43:18 +00002619 NamedRegionTimer T("spill", "Spiller", TimerGroupName,
2620 TimerGroupDescription, TimePassesIsEnabled);
Wei Mi9a16d652016-04-13 03:08:27 +00002621 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Quentin Colombet11922942015-07-17 23:04:06 +00002622 spiller().spill(LRE);
2623 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002624
Quentin Colombet11922942015-07-17 23:04:06 +00002625 if (VerifyEnabled)
2626 MF->verify(this, "After spilling");
2627 }
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00002628
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002629 // The live virtual register requesting allocation was spilled, so tell
2630 // the caller not to allocate anything during this round.
2631 return 0;
2632}
2633
Adam Nemeta9640662017-01-25 23:20:33 +00002634void RAGreedy::reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
2635 unsigned &FoldedReloads,
2636 unsigned &Spills,
2637 unsigned &FoldedSpills) {
2638 Reloads = 0;
2639 FoldedReloads = 0;
2640 Spills = 0;
2641 FoldedSpills = 0;
2642
2643 // Sum up the spill and reloads in subloops.
2644 for (MachineLoop *SubLoop : *L) {
2645 unsigned SubReloads;
2646 unsigned SubFoldedReloads;
2647 unsigned SubSpills;
2648 unsigned SubFoldedSpills;
2649
2650 reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
2651 SubSpills, SubFoldedSpills);
2652 Reloads += SubReloads;
2653 FoldedReloads += SubFoldedReloads;
2654 Spills += SubSpills;
2655 FoldedSpills += SubFoldedSpills;
2656 }
2657
2658 const MachineFrameInfo &MFI = MF->getFrameInfo();
2659 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2660 int FI;
2661
2662 for (MachineBasicBlock *MBB : L->getBlocks())
2663 // Handle blocks that were not included in subloops.
2664 if (Loops->getLoopFor(MBB) == L)
2665 for (MachineInstr &MI : *MBB) {
2666 const MachineMemOperand *MMO;
2667
2668 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI))
2669 ++Reloads;
2670 else if (TII->hasLoadFromStackSlot(MI, MMO, FI) &&
2671 MFI.isSpillSlotObjectIndex(FI))
2672 ++FoldedReloads;
2673 else if (TII->isStoreToStackSlot(MI, FI) &&
2674 MFI.isSpillSlotObjectIndex(FI))
2675 ++Spills;
2676 else if (TII->hasStoreToStackSlot(MI, MMO, FI) &&
2677 MFI.isSpillSlotObjectIndex(FI))
2678 ++FoldedSpills;
2679 }
2680
2681 if (Reloads || FoldedReloads || Spills || FoldedSpills) {
2682 using namespace ore;
2683 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReload",
2684 L->getStartLoc(), L->getHeader());
2685 if (Spills)
2686 R << NV("NumSpills", Spills) << " spills ";
2687 if (FoldedSpills)
2688 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
2689 if (Reloads)
2690 R << NV("NumReloads", Reloads) << " reloads ";
2691 if (FoldedReloads)
2692 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
2693 ORE->emit(R << "generated in loop");
2694 }
2695}
2696
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002697bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2698 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +00002699 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002700
2701 MF = &mf;
Eric Christopher60621802014-10-14 07:22:00 +00002702 TRI = MF->getSubtarget().getRegisterInfo();
2703 TII = MF->getSubtarget().getInstrInfo();
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00002704 RCI.runOnMachineFunction(mf);
Quentin Colombet5caa6a22014-07-02 18:32:04 +00002705
2706 EnableLocalReassign = EnableLocalReassignment ||
Eric Christopher60621802014-10-14 07:22:00 +00002707 MF->getSubtarget().enableRALocalReassignment(
2708 MF->getTarget().getOptLevel());
Quentin Colombet5caa6a22014-07-02 18:32:04 +00002709
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00002710 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00002711 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00002712
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00002713 RegAllocBase::init(getAnalysis<VirtRegMap>(),
2714 getAnalysis<LiveIntervals>(),
2715 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002716 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00002717 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00002718 DomTree = &getAnalysis<MachineDominatorTree>();
Adam Nemeta9640662017-01-25 23:20:33 +00002719 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00002720 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00002721 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002722 Bundles = &getAnalysis<EdgeBundles>();
2723 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00002724 DebugVars = &getAnalysis<LiveDebugVariables>();
Wei Mic0223702016-07-08 21:08:09 +00002725 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002726
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002727 initializeCSRCost();
2728
Robert Lougher11a44b72015-08-10 11:59:44 +00002729 calculateSpillWeightsAndHints(*LIS, mf, VRM, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00002730
Andrew Trick97064962013-07-25 07:26:26 +00002731 DEBUG(LIS->dump());
2732
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00002733 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Wei Mic0223702016-07-08 21:08:09 +00002734 SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002735 ExtraRegInfo.clear();
2736 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2737 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002738 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00002739 GlobalCand.resize(32); // This will grow as needed.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002740 SetOfBrokenHints.clear();
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00002741
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002742 allocatePhysRegs();
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002743 tryHintsRecoloring();
Wei Mi9a16d652016-04-13 03:08:27 +00002744 postOptimization();
Adam Nemeta9640662017-01-25 23:20:33 +00002745 reportNumberOfSplillsReloads();
Wei Mi9a16d652016-04-13 03:08:27 +00002746
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002747 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002748 return true;
2749}