blob: e74ac79f0010e330f3b939112efcc45a3ab1aa3c [file] [log] [blame]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001//===- RegAllocGreedy.cpp - greedy register allocator ---------------------===//
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002//
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"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000022#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/IndexedMap.h"
Marina Yatsinaf9371d82017-10-22 17:59:38 +000026#include "llvm/ADT/MapVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000027#include "llvm/ADT/SetVector.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SmallVector.h"
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000031#include "llvm/ADT/Statistic.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000032#include "llvm/ADT/StringRef.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000033#include "llvm/Analysis/AliasAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000034#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000035#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +000036#include "llvm/CodeGen/EdgeBundles.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000037#include "llvm/CodeGen/LiveInterval.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000038#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000039#include "llvm/CodeGen/LiveIntervalUnion.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000040#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000041#include "llvm/CodeGen/LiveRegMatrix.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000042#include "llvm/CodeGen/LiveStackAnalysis.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000043#include "llvm/CodeGen/MachineBasicBlock.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000044#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +000045#include "llvm/CodeGen/MachineDominators.h"
Adam Nemeta9640662017-01-25 23:20:33 +000046#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000047#include "llvm/CodeGen/MachineFunction.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000048#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000049#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000050#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000051#include "llvm/CodeGen/MachineOperand.h"
Adam Nemeta9640662017-01-25 23:20:33 +000052#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000053#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000054#include "llvm/CodeGen/RegAllocRegistry.h"
Quentin Colombet1fb3362a2014-01-02 22:47:22 +000055#include "llvm/CodeGen/RegisterClassInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000056#include "llvm/CodeGen/SlotIndexes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include "llvm/CodeGen/VirtRegMap.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000058#include "llvm/IR/Function.h"
Quentin Colombet96bd2a12014-04-04 02:05:21 +000059#include "llvm/IR/LLVMContext.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000060#include "llvm/MC/MCRegisterInfo.h"
61#include "llvm/Pass.h"
62#include "llvm/Support/BlockFrequency.h"
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +000063#include "llvm/Support/BranchProbability.h"
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +000064#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000065#include "llvm/Support/Debug.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000066#include "llvm/Support/MathExtras.h"
Jakob Stoklund Olesen92da7052010-12-11 00:19:56 +000067#include "llvm/Support/Timer.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000068#include "llvm/Support/raw_ostream.h"
Wei Mi9a16d652016-04-13 03:08:27 +000069#include "llvm/Target/TargetInstrInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000070#include "llvm/Target/TargetMachine.h"
71#include "llvm/Target/TargetRegisterInfo.h"
Quentin Colombet5caa6a22014-07-02 18:32:04 +000072#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000073#include <algorithm>
74#include <cassert>
75#include <cstdint>
76#include <memory>
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000077#include <queue>
Eugene Zelenkofb69e662017-06-06 22:22:41 +000078#include <tuple>
79#include <utility>
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +000080
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +000081using namespace llvm;
82
Chandler Carruth1b9dde02014-04-22 02:02:50 +000083#define DEBUG_TYPE "regalloc"
84
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000085STATISTIC(NumGlobalSplits, "Number of split global live ranges");
86STATISTIC(NumLocalSplits, "Number of split local live ranges");
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +000087STATISTIC(NumEvicted, "Number of interferences evicted");
88
Wei Mi9a16d652016-04-13 03:08:27 +000089static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
90 "split-spill-mode", cl::Hidden,
91 cl::desc("Spill mode for splitting live ranges"),
92 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
93 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
Mehdi Amini732afdd2016-10-08 19:41:06 +000094 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
Wei Mi9a16d652016-04-13 03:08:27 +000095 cl::init(SplitEditor::SM_Speed));
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +000096
Quentin Colombet87769712014-02-05 22:13:59 +000097static cl::opt<unsigned>
98LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
99 cl::desc("Last chance recoloring max depth"),
100 cl::init(5));
101
102static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
103 "lcr-max-interf", cl::Hidden,
104 cl::desc("Last chance recoloring maximum number of considered"
105 " interference at a time"),
106 cl::init(8));
107
Quentin Colombet567e30b2014-04-11 21:39:44 +0000108static cl::opt<bool>
Quentin Colombet4344da12014-04-11 21:51:09 +0000109ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
Quentin Colombet567e30b2014-04-11 21:39:44 +0000110 cl::desc("Exhaustive Search for registers bypassing the depth "
111 "and interference cutoffs of last chance recoloring"));
112
Quentin Colombete1a36632014-07-01 14:08:37 +0000113static cl::opt<bool> EnableLocalReassignment(
114 "enable-local-reassign", cl::Hidden,
115 cl::desc("Local reassignment can yield better allocation decisions, but "
116 "may be compile time intensive"),
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000117 cl::init(false));
Quentin Colombete1a36632014-07-01 14:08:37 +0000118
Quentin Colombet11922942015-07-17 23:04:06 +0000119static cl::opt<bool> EnableDeferredSpilling(
120 "enable-deferred-spilling", cl::Hidden,
121 cl::desc("Instead of spilling a variable right away, defer the actual "
122 "code insertion to the end of the allocation. That way the "
123 "allocator might still find a suitable coloring for this "
124 "variable because of other evicted variables."),
125 cl::init(false));
126
Manman Ren78cf02a2014-03-25 00:16:25 +0000127// FIXME: Find a good default for this flag and remove the flag.
128static cl::opt<unsigned>
129CSRFirstTimeCost("regalloc-csr-first-time-cost",
130 cl::desc("Cost for first time use of callee-saved register."),
131 cl::init(0), cl::Hidden);
132
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000133static cl::opt<bool> ConsiderLocalIntervalCost(
134 "condsider-local-interval-cost", cl::Hidden,
135 cl::desc("Consider the cost of local intervals created by a split "
136 "candidate when choosing the best split candidate."),
137 cl::init(false));
138
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000139static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
140 createGreedyRegisterAllocator);
141
142namespace {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000143
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000144class RAGreedy : public MachineFunctionPass,
145 public RegAllocBase,
146 private LiveRangeEdit::Delegate {
Quentin Colombet87769712014-02-05 22:13:59 +0000147 // Convenient shortcuts.
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000148 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
149 using SmallLISet = SmallPtrSet<LiveInterval *, 4>;
150 using SmallVirtRegSet = SmallSet<unsigned, 16>;
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000151
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000152 // context
153 MachineFunction *MF;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000154
Quentin Colombet1fb3362a2014-01-02 22:47:22 +0000155 // Shortcuts to some useful interface.
156 const TargetInstrInfo *TII;
157 const TargetRegisterInfo *TRI;
158 RegisterClassInfo RCI;
159
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000160 // analyses
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000161 SlotIndexes *Indexes;
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000162 MachineBlockFrequencyInfo *MBFI;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000163 MachineDominatorTree *DomTree;
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +0000164 MachineLoopInfo *Loops;
Adam Nemeta9640662017-01-25 23:20:33 +0000165 MachineOptimizationRemarkEmitter *ORE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000166 EdgeBundles *Bundles;
167 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +0000168 LiveDebugVariables *DebugVars;
Wei Mic0223702016-07-08 21:08:09 +0000169 AliasAnalysis *AA;
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000170
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000171 // state
Ahmed Charles56440fd2014-03-06 05:51:42 +0000172 std::unique_ptr<Spiller> SpillerInstance;
Quentin Colombet87769712014-02-05 22:13:59 +0000173 PQueue Queue;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000174 unsigned NextCascade;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000175
176 // Live ranges pass through a number of stages as we try to allocate them.
177 // Some of the stages may also create new live ranges:
178 //
179 // - Region splitting.
180 // - Per-block splitting.
181 // - Local splitting.
182 // - Spilling.
183 //
184 // Ranges produced by one of the stages skip the previous stages when they are
185 // dequeued. This improves performance because we can skip interference checks
186 // that are unlikely to give any results. It also guarantees that the live
187 // range splitting algorithm terminates, something that is otherwise hard to
188 // ensure.
189 enum LiveRangeStage {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000190 /// Newly created live range that has never been queued.
191 RS_New,
192
193 /// Only attempt assignment and eviction. Then requeue as RS_Split.
194 RS_Assign,
195
196 /// Attempt live range splitting if assignment is impossible.
197 RS_Split,
198
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000199 /// Attempt more aggressive live range splitting that is guaranteed to make
200 /// progress. This is used for split products that may not be making
201 /// progress.
202 RS_Split2,
203
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000204 /// Live range will be spilled. No more splitting will be attempted.
205 RS_Spill,
206
Quentin Colombet11922942015-07-17 23:04:06 +0000207
208 /// Live range is in memory. Because of other evictions, it might get moved
209 /// in a register in the end.
210 RS_Memory,
211
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000212 /// There is nothing more we can do to this live range. Abort compilation
213 /// if it can't be assigned.
214 RS_Done
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000215 };
216
Quentin Colombet96bd2a12014-04-04 02:05:21 +0000217 // Enum CutOffStage to keep a track whether the register allocation failed
218 // because of the cutoffs encountered in last chance recoloring.
219 // Note: This is used as bitmask. New value should be next power of 2.
220 enum CutOffStage {
221 // No cutoffs encountered
222 CO_None = 0,
223
224 // lcr-max-depth cutoff encountered
225 CO_Depth = 1,
226
227 // lcr-max-interf cutoff encountered
228 CO_Interf = 2
229 };
230
231 uint8_t CutOffInfo;
232
Eli Friedman78bffa52013-09-10 23:18:14 +0000233#ifndef NDEBUG
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000234 static const char *const StageName[];
Eli Friedman78bffa52013-09-10 23:18:14 +0000235#endif
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000236
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000237 // RegInfo - Keep additional information about each live range.
238 struct RegInfo {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000239 LiveRangeStage Stage = RS_New;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000240
241 // Cascade - Eviction loop prevention. See canEvictInterference().
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000242 unsigned Cascade = 0;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000243
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000244 RegInfo() = default;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000245 };
246
247 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000248
249 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000250 return ExtraRegInfo[VirtReg.reg].Stage;
251 }
252
253 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
254 ExtraRegInfo.resize(MRI->getNumVirtRegs());
255 ExtraRegInfo[VirtReg.reg].Stage = Stage;
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000256 }
257
258 template<typename Iterator>
259 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000260 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000261 for (;Begin != End; ++Begin) {
Mark Laceyf9ea8852013-08-14 23:50:04 +0000262 unsigned Reg = *Begin;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000263 if (ExtraRegInfo[Reg].Stage == RS_New)
264 ExtraRegInfo[Reg].Stage = NewStage;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000265 }
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +0000266 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000267
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000268 /// Cost of evicting interference.
269 struct EvictionCost {
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000270 unsigned BrokenHints = 0; ///< Total number of broken hints.
271 float MaxWeight = 0; ///< Maximum spill weight evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000272
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000273 EvictionCost() = default;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000274
Andrew Trick84852572013-07-25 18:35:14 +0000275 bool isMax() const { return BrokenHints == ~0u; }
276
Andrew Trick3621b8a2013-11-22 19:07:38 +0000277 void setMax() { BrokenHints = ~0u; }
278
279 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
280
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000281 bool operator<(const EvictionCost &O) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +0000282 return std::tie(BrokenHints, MaxWeight) <
283 std::tie(O.BrokenHints, O.MaxWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000284 }
285 };
286
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000287 /// EvictionTrack - Keeps track of past evictions in order to optimize region
288 /// split decision.
289 class EvictionTrack {
290
291 public:
292 using EvictorInfo =
293 std::pair<unsigned /* evictor */, unsigned /* physreg */>;
294 using EvicteeInfo = llvm::MapVector<unsigned /* evictee */, EvictorInfo>;
295
296 private:
297 /// Each Vreg that has been evicted in the last stage of selectOrSplit will
298 /// be mapped to the evictor Vreg and the PhysReg it was evicted from.
299 EvicteeInfo Evictees;
300
301 public:
302 /// \brief Clear all eviction information.
303 void clear() { Evictees.clear(); }
304
305 /// \brief Clear eviction information for the given evictee Vreg.
306 /// E.g. when Vreg get's a new allocation, the old eviction info is no
307 /// longer relevant.
308 /// \param Evictee The evictee Vreg for whom we want to clear collected
309 /// eviction info.
310 void clearEvicteeInfo(unsigned Evictee) { Evictees.erase(Evictee); }
311
312 /// \brief Track new eviction.
313 /// The Evictor vreg has evicted the Evictee vreg from Physreg.
314 /// \praram PhysReg The phisical register Evictee was evicted from.
315 /// \praram Evictor The evictor Vreg that evicted Evictee.
316 /// \praram Evictee The evictee Vreg.
317 void addEviction(unsigned PhysReg, unsigned Evictor, unsigned Evictee) {
318 Evictees[Evictee].first = Evictor;
319 Evictees[Evictee].second = PhysReg;
320 }
321
322 /// Return the Evictor Vreg which evicted Evictee Vreg from PhysReg.
323 /// \praram Evictee The evictee vreg.
324 /// \return The Evictor vreg which evicted Evictee vreg from PhysReg. 0 if
325 /// nobody has evicted Evictee from PhysReg.
326 EvictorInfo getEvictor(unsigned Evictee) {
327 if (Evictees.count(Evictee)) {
328 return Evictees[Evictee];
329 }
330
331 return EvictorInfo(0, 0);
332 }
333 };
334
335 // Keeps track of past evictions in order to optimize region split decision.
336 EvictionTrack LastEvicted;
337
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000338 // splitting state.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000339 std::unique_ptr<SplitAnalysis> SA;
340 std::unique_ptr<SplitEditor> SE;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000341
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +0000342 /// Cached per-block interference maps
343 InterferenceCache IntfCache;
344
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +0000345 /// All basic blocks where the current register has uses.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000346 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000347
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000348 /// Global live range splitting candidate info.
349 struct GlobalSplitCandidate {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000350 // Register intended for assignment, or 0.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000351 unsigned PhysReg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000352
353 // SplitKit interval index for this candidate.
354 unsigned IntvIdx;
355
356 // Interference for PhysReg.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000357 InterferenceCache::Cursor Intf;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000358
359 // Bundles where this candidate should be live.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000360 BitVector LiveBundles;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000361 SmallVector<unsigned, 8> ActiveBlocks;
362
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000363 void reset(InterferenceCache &Cache, unsigned Reg) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000364 PhysReg = Reg;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000365 IntvIdx = 0;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000366 Intf.setPhysReg(Cache, Reg);
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000367 LiveBundles.clear();
368 ActiveBlocks.clear();
369 }
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000370
371 // Set B[i] = C for every live bundle where B[i] was NoCand.
372 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
373 unsigned Count = 0;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +0000374 for (unsigned i : LiveBundles.set_bits())
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000375 if (B[i] == NoCand) {
376 B[i] = C;
377 Count++;
378 }
379 return Count;
380 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000381 };
382
Aditya Nandakumarc1fd0dd2013-11-19 23:51:32 +0000383 /// Candidate info for each PhysReg in AllocationOrder.
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +0000384 /// This vector never shrinks, but grows to the size of the largest register
385 /// class.
386 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
387
Alp Toker61007d82014-03-02 03:20:38 +0000388 enum : unsigned { NoCand = ~0u };
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000389
390 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
391 /// NoCand which indicates the stack interval.
392 SmallVector<unsigned, 32> BundleCand;
393
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000394 /// Callee-save register cost, calculated once per machine function.
395 BlockFrequency CSRCost;
396
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000397 /// Run or not the local reassignment heuristic. This information is
398 /// obtained from the TargetSubtargetInfo.
399 bool EnableLocalReassign;
400
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000401 /// Enable or not the the consideration of the cost of local intervals created
402 /// by a split candidate when choosing the best split candidate.
403 bool EnableAdvancedRASplitCost;
404
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000405 /// Set of broken hints that may be reconciled later because of eviction.
406 SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
407
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000408public:
409 RAGreedy();
410
411 /// Return the pass name.
Mehdi Amini117296c2016-10-01 02:56:57 +0000412 StringRef getPassName() const override { return "Greedy Register Allocator"; }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000413
414 /// RAGreedy analysis usage.
Craig Topper4584cd52014-03-07 09:26:03 +0000415 void getAnalysisUsage(AnalysisUsage &AU) const override;
416 void releaseMemory() override;
417 Spiller &spiller() override { return *SpillerInstance; }
418 void enqueue(LiveInterval *LI) override;
419 LiveInterval *dequeue() override;
420 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000421 void aboutToRemoveInterval(LiveInterval &) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000422
423 /// Perform register allocation.
Craig Topper4584cd52014-03-07 09:26:03 +0000424 bool runOnMachineFunction(MachineFunction &mf) override;
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000425
Matthias Braun90799ce2016-08-23 21:19:49 +0000426 MachineFunctionProperties getRequiredProperties() const override {
427 return MachineFunctionProperties().set(
428 MachineFunctionProperties::Property::NoPHIs);
429 }
430
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000431 static char ID;
Andrew Trickccef0982010-12-09 18:15:21 +0000432
433private:
Quentin Colombet87769712014-02-05 22:13:59 +0000434 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
435 SmallVirtRegSet &, unsigned = 0);
436
Craig Topper4584cd52014-03-07 09:26:03 +0000437 bool LRE_CanEraseVirtReg(unsigned) override;
438 void LRE_WillShrinkVirtReg(unsigned) override;
439 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
Quentin Colombet87769712014-02-05 22:13:59 +0000440 void enqueue(PQueue &CurQueue, LiveInterval *LI);
441 LiveInterval *dequeue(PQueue &CurQueue);
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000442
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +0000443 BlockFrequency calcSpillCost();
444 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +0000445 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +0000446 void growRegion(GlobalSplitCandidate &Cand);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000447 bool splitCanCauseEvictionChain(unsigned Evictee, GlobalSplitCandidate &Cand,
448 unsigned BBNumber,
449 const AllocationOrder &Order);
450 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate &,
451 const AllocationOrder &Order,
452 bool *CanCauseEvictionChain);
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +0000453 bool calcCompactRegion(GlobalSplitCandidate&);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +0000454 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000455 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000456 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000457 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
458 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000459 bool canEvictInterferenceInRange(LiveInterval &VirtReg, unsigned PhysReg,
460 SlotIndex Start, SlotIndex End,
461 EvictionCost &MaxCost);
462 unsigned getCheapestEvicteeWeight(const AllocationOrder &Order,
463 LiveInterval &VirtReg, SlotIndex Start,
464 SlotIndex End, float *BestEvictWeight);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000465 void evictInterference(LiveInterval&, unsigned,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000466 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000467 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
468 SmallLISet &RecoloringCandidates,
469 const SmallVirtRegSet &FixedRegisters);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000470
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000471 unsigned tryAssign(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000472 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000473 unsigned tryEvict(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000474 SmallVectorImpl<unsigned>&, unsigned = ~0u);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000475 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000476 SmallVectorImpl<unsigned>&);
Manman Ren9db66b32014-03-24 23:23:42 +0000477 /// Calculate cost of region splitting.
478 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
479 AllocationOrder &Order,
480 BlockFrequency &BestCost,
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000481 unsigned &NumCands, bool IgnoreCSR,
482 bool *CanCauseEvictionChain = nullptr);
Manman Ren9db66b32014-03-24 23:23:42 +0000483 /// Perform region splitting.
484 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
485 bool HasCompact,
486 SmallVectorImpl<unsigned> &NewVRegs);
Manman Ren9dee4492014-03-27 21:21:57 +0000487 /// Check other options before using a callee-saved register for the first
488 /// time.
489 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
490 unsigned PhysReg, unsigned &CostPerUseLimit,
491 SmallVectorImpl<unsigned> &NewVRegs);
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +0000492 void initializeCSRCost();
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +0000493 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000494 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +0000495 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000496 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +0000497 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000498 SmallVectorImpl<unsigned>&);
Jakob Stoklund Olesen3d7b8062010-12-14 00:37:44 +0000499 unsigned trySplit(LiveInterval&, AllocationOrder&,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000500 SmallVectorImpl<unsigned>&);
Quentin Colombet87769712014-02-05 22:13:59 +0000501 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
502 SmallVectorImpl<unsigned> &,
503 SmallVirtRegSet &, unsigned);
504 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
505 SmallVirtRegSet &, unsigned);
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000506 void tryHintRecoloring(LiveInterval &);
507 void tryHintsRecoloring();
508
509 /// Model the information carried by one end of a copy.
510 struct HintInfo {
511 /// The frequency of the copy.
512 BlockFrequency Freq;
513 /// The virtual register or physical register.
514 unsigned Reg;
515 /// Its currently assigned register.
516 /// In case of a physical register Reg == PhysReg.
517 unsigned PhysReg;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000518
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000519 HintInfo(BlockFrequency Freq, unsigned Reg, unsigned PhysReg)
520 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
521 };
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000522 using HintsInfo = SmallVector<HintInfo, 4>;
523
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000524 BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
525 void collectHintInfo(unsigned, HintsInfo &);
Matthias Braun953393a2015-07-14 17:38:17 +0000526
527 bool isUnusedCalleeSavedReg(unsigned PhysReg) const;
Adam Nemeta9640662017-01-25 23:20:33 +0000528
529 /// Compute and report the number of spills and reloads for a loop.
530 void reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
531 unsigned &FoldedReloads, unsigned &Spills,
532 unsigned &FoldedSpills);
533
534 /// Report the number of spills and reloads for each loop.
535 void reportNumberOfSplillsReloads() {
536 for (MachineLoop *L : *Loops) {
537 unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
538 reportNumberOfSplillsReloads(L, Reloads, FoldedReloads, Spills,
539 FoldedSpills);
540 }
541 }
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000542};
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000543
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000544} // end anonymous namespace
545
546char RAGreedy::ID = 0;
Tom Stellard11e60ff2016-11-14 21:50:13 +0000547char &llvm::RAGreedyID = RAGreedy::ID;
548
549INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
550 "Greedy Register Allocator", false, false)
551INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
552INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
553INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
554INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
555INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
556INITIALIZE_PASS_DEPENDENCY(LiveStacks)
557INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
558INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
559INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
560INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
561INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
562INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
Adam Nemeta9640662017-01-25 23:20:33 +0000563INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
Tom Stellard11e60ff2016-11-14 21:50:13 +0000564INITIALIZE_PASS_END(RAGreedy, "greedy",
565 "Greedy Register Allocator", false, false)
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000566
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000567#ifndef NDEBUG
568const char *const RAGreedy::StageName[] = {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000569 "RS_New",
570 "RS_Assign",
571 "RS_Split",
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000572 "RS_Split2",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000573 "RS_Spill",
Quentin Colombet11922942015-07-17 23:04:06 +0000574 "RS_Memory",
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000575 "RS_Done"
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000576};
577#endif
578
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000579// Hysteresis to use when comparing floats.
580// This helps stabilize decisions based on float comparisons.
NAKAMURA Takumia71003a2014-02-04 06:29:38 +0000581const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +0000582
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000583FunctionPass* llvm::createGreedyRegisterAllocator() {
584 return new RAGreedy();
585}
586
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000587RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000588}
589
590void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
591 AU.setPreservesCFG();
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000592 AU.addRequired<MachineBlockFrequencyInfo>();
593 AU.addPreserved<MachineBlockFrequencyInfo>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000594 AU.addRequired<AAResultsWrapperPass>();
595 AU.addPreserved<AAResultsWrapperPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000596 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesen12243122012-06-08 23:44:45 +0000597 AU.addPreserved<LiveIntervals>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000598 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000599 AU.addPreserved<SlotIndexes>();
Jakob Stoklund Olesen6aa0fbf2011-04-05 21:40:37 +0000600 AU.addRequired<LiveDebugVariables>();
601 AU.addPreserved<LiveDebugVariables>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000602 AU.addRequired<LiveStacks>();
603 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +0000604 AU.addRequired<MachineDominatorTree>();
605 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000606 AU.addRequired<MachineLoopInfo>();
607 AU.addPreserved<MachineLoopInfo>();
608 AU.addRequired<VirtRegMap>();
609 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000610 AU.addRequired<LiveRegMatrix>();
611 AU.addPreserved<LiveRegMatrix>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +0000612 AU.addRequired<EdgeBundles>();
613 AU.addRequired<SpillPlacement>();
Adam Nemeta9640662017-01-25 23:20:33 +0000614 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000615 MachineFunctionPass::getAnalysisUsage(AU);
616}
617
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000618//===----------------------------------------------------------------------===//
619// LiveRangeEdit delegate methods
620//===----------------------------------------------------------------------===//
621
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000622bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
Jonas Paulsson6188f322017-09-15 07:47:38 +0000623 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000624 if (VRM->hasPhys(VirtReg)) {
Quentin Colombeta799e2e2015-01-08 01:16:39 +0000625 Matrix->unassign(LI);
626 aboutToRemoveInterval(LI);
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000627 return true;
628 }
629 // Unassigned virtreg is probably in the priority queue.
630 // RegAllocBase will erase it after dequeueing.
Jonas Paulsson6188f322017-09-15 07:47:38 +0000631 // Nonetheless, clear the live-range so that the debug
632 // dump will show the right state for that VirtReg.
633 LI.clear();
Jakob Stoklund Olesen43a87502011-03-13 01:23:11 +0000634 return false;
635}
Jakob Stoklund Olesen8e089642011-03-09 00:57:29 +0000636
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000637void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000638 if (!VRM->hasPhys(VirtReg))
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000639 return;
640
641 // Register is assigned, put it back on the queue for reassignment.
642 LiveInterval &LI = LIS->getInterval(VirtReg);
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000643 Matrix->unassign(LI);
Jakob Stoklund Olesene14b2b22011-03-16 22:56:16 +0000644 enqueue(&LI);
645}
646
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000647void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
Jakob Stoklund Olesen811b9c42011-09-14 17:34:37 +0000648 // Cloning a register we haven't even heard about yet? Just ignore it.
649 if (!ExtraRegInfo.inBounds(Old))
650 return;
651
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000652 // LRE may clone a virtual register because dead code elimination causes it to
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000653 // be split into connected components. The new components are much smaller
654 // than the original, so they should get a new chance at being assigned.
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000655 // same stage as the parent.
Jakob Stoklund Olesen5387bd32011-07-26 00:54:56 +0000656 ExtraRegInfo[Old].Stage = RS_Assign;
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000657 ExtraRegInfo.grow(New);
658 ExtraRegInfo[New] = ExtraRegInfo[Old];
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000659}
660
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000661void RAGreedy::releaseMemory() {
David Blaikieb61064e2014-07-19 01:05:11 +0000662 SpillerInstance.reset();
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000663 ExtraRegInfo.clear();
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +0000664 GlobalCand.clear();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +0000665}
666
Quentin Colombet87769712014-02-05 22:13:59 +0000667void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
668
669void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000670 // Prioritize live ranges by size, assigning larger ranges first.
671 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000672 const unsigned Size = LI->getSize();
673 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000674 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
675 "Can only enqueue virtual registers");
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +0000676 unsigned Prio;
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000677
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000678 ExtraRegInfo.grow(Reg);
679 if (ExtraRegInfo[Reg].Stage == RS_New)
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000680 ExtraRegInfo[Reg].Stage = RS_Assign;
Jakob Stoklund Olesendd9a2ec2011-03-30 02:52:39 +0000681
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000682 if (ExtraRegInfo[Reg].Stage == RS_Split) {
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000683 // Unsplit ranges that couldn't be allocated immediately are deferred until
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +0000684 // everything else has been allocated.
685 Prio = Size;
Quentin Colombet11922942015-07-17 23:04:06 +0000686 } else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
687 // Memory operand should be considered last.
688 // Change the priority such that Memory operand are assigned in
689 // the reverse order that they came in.
690 // TODO: Make this a member variable and probably do something about hints.
691 static unsigned MemOp = 0;
692 Prio = MemOp++;
Jakob Stoklund Olesencad845f2011-07-28 20:48:23 +0000693 } else {
Andrew Trick52a00932014-02-26 22:07:26 +0000694 // Giant live ranges fall back to the global assignment heuristic, which
695 // prevents excessive spilling in pathological cases.
696 bool ReverseLocal = TRI->reverseLocalAssignment();
Matthias Brauna354cdd2015-03-31 19:57:53 +0000697 const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
Renato Golin4e31ae12014-10-03 12:20:53 +0000698 bool ForceGlobal = !ReverseLocal &&
Matthias Brauna354cdd2015-03-31 19:57:53 +0000699 (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
Andrew Trick52a00932014-02-26 22:07:26 +0000700
701 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
Andrew Trick84852572013-07-25 18:35:14 +0000702 LIS->intervalIsInOneMBB(*LI)) {
703 // Allocate original local ranges in linear instruction order. Since they
704 // are singly defined, this produces optimal coloring in the absence of
705 // global interference and other constraints.
Andrew Trick52a00932014-02-26 22:07:26 +0000706 if (!ReverseLocal)
Andrew Trick2d8826a2013-12-11 03:40:15 +0000707 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
708 else {
709 // Allocating bottom up may allow many short LRGs to be assigned first
710 // to one of the cheap registers. This could be much faster for very
711 // large blocks on targets with many physical registers.
Matthias Braunf5f89b92015-03-31 19:57:49 +0000712 Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
Andrew Trick2d8826a2013-12-11 03:40:15 +0000713 }
Matthias Brauna354cdd2015-03-31 19:57:53 +0000714 Prio |= RC.AllocationPriority << 24;
715 } else {
Andrew Trick84852572013-07-25 18:35:14 +0000716 // Allocate global and split ranges in long->short order. Long ranges that
717 // don't fit should be spilled (or split) ASAP so they don't create
718 // interference. Mark a bit to prioritize global above local ranges.
719 Prio = (1u << 29) + Size;
720 }
721 // Mark a higher bit to prioritize global and local above RS_Split.
722 Prio |= (1u << 31);
Jakob Stoklund Olesenb51f65c2011-02-23 00:56:56 +0000723
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000724 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen74052b02012-12-03 23:23:50 +0000725 if (VRM->hasKnownPreference(Reg))
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +0000726 Prio |= (1u << 30);
727 }
Andrew Trickf4b1ee32013-07-25 18:35:22 +0000728 // The virtual register number is a tie breaker for same-sized ranges.
729 // Give lower vreg numbers higher priority to assign them first.
Quentin Colombet87769712014-02-05 22:13:59 +0000730 CurQueue.push(std::make_pair(Prio, ~Reg));
Jakob Stoklund Oleseneaa650a2010-12-08 22:57:16 +0000731}
732
Quentin Colombet87769712014-02-05 22:13:59 +0000733LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
734
735LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
736 if (CurQueue.empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000737 return nullptr;
Quentin Colombet87769712014-02-05 22:13:59 +0000738 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
739 CurQueue.pop();
Jakob Stoklund Olesen2329c542011-02-22 23:01:52 +0000740 return LI;
741}
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000742
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000743//===----------------------------------------------------------------------===//
744// Direct Assignment
745//===----------------------------------------------------------------------===//
746
747/// tryAssign - Try to assign VirtReg to an available register.
748unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
749 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +0000750 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000751 Order.rewind();
752 unsigned PhysReg;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000753 while ((PhysReg = Order.next()))
754 if (!Matrix->checkInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000755 break;
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +0000756 if (!PhysReg || Order.isHint())
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000757 return PhysReg;
758
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000759 // PhysReg is available, but there may be a better choice.
760
761 // If we missed a simple hint, try to cheaply evict interference from the
762 // preferred register.
763 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000764 if (Order.isHint(Hint)) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000765 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
Andrew Trick3621b8a2013-11-22 19:07:38 +0000766 EvictionCost MaxCost;
767 MaxCost.setBrokenHints(1);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000768 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
769 evictInterference(VirtReg, Hint, NewVRegs);
770 return Hint;
771 }
Quentin Colombetfb9b0cd2016-11-16 01:07:12 +0000772 // Record the missed hint, we may be able to recover
773 // at the end if the surrounding allocation changed.
774 SetOfBrokenHints.insert(&VirtReg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000775 }
776
777 // Try to evict interference from a cheaper alternative.
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +0000778 unsigned Cost = TRI->getCostPerUse(PhysReg);
779
780 // Most registers have 0 additional cost.
781 if (!Cost)
782 return PhysReg;
783
784 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
785 << '\n');
786 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
787 return CheapReg ? CheapReg : PhysReg;
788}
789
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +0000790//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000791// Interference eviction
792//===----------------------------------------------------------------------===//
793
Andrew Trick8bb0a252013-07-25 18:35:19 +0000794unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
Matthias Braun5d1f12d2015-07-15 22:16:00 +0000795 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000796 unsigned PhysReg;
797 while ((PhysReg = Order.next())) {
798 if (PhysReg == PrevReg)
799 continue;
800
801 MCRegUnitIterator Units(PhysReg, TRI);
802 for (; Units.isValid(); ++Units) {
803 // Instantiate a "subquery", not to be confused with the Queries array.
Matthias Braun173e1142017-03-01 21:48:12 +0000804 LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
Andrew Trick8bb0a252013-07-25 18:35:19 +0000805 if (subQ.checkInterference())
806 break;
807 }
808 // If no units have interference, break out with the current PhysReg.
809 if (!Units.isValid())
810 break;
811 }
812 if (PhysReg)
813 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
814 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
815 << '\n');
816 return PhysReg;
817}
818
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000819/// shouldEvict - determine if A should evict the assigned live range B. The
820/// eviction policy defined by this function together with the allocation order
821/// defined by enqueue() decides which registers ultimately end up being split
822/// and spilled.
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000823///
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000824/// Cascade numbers are used to prevent infinite loops if this function is a
825/// cyclic relation.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000826///
827/// @param A The live range to be assigned.
828/// @param IsHint True when A is about to be assigned to its preferred
829/// register.
830/// @param B The live range to be evicted.
831/// @param BreaksHint True when B is already assigned to its preferred register.
832bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
833 LiveInterval &B, bool BreaksHint) {
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +0000834 bool CanSplit = getStage(B) < RS_Spill;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000835
836 // Be fairly aggressive about following hints as long as the evictee can be
837 // split.
838 if (CanSplit && IsHint && !BreaksHint)
839 return true;
840
Andrew Trick059e8002013-11-22 19:07:42 +0000841 if (A.weight > B.weight) {
842 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
843 return true;
844 }
845 return false;
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +0000846}
847
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000848/// canEvictInterference - Return true if all interferences between VirtReg and
Manman Renfa32ca12014-02-25 19:47:15 +0000849/// PhysReg can be evicted.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000850///
851/// @param VirtReg Live range that is about to be assigned.
852/// @param PhysReg Desired register for assignment.
Dmitri Gribenko881929c2012-09-12 16:59:47 +0000853/// @param IsHint True when PhysReg is VirtReg's preferred register.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000854/// @param MaxCost Only look for cheaper candidates and update with new cost
855/// when returning true.
856/// @returns True when interference can be evicted cheaper than MaxCost.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000857bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000858 bool IsHint, EvictionCost &MaxCost) {
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000859 // It is only possible to evict virtual register interference.
860 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
861 return false;
862
Andrew Trick84852572013-07-25 18:35:14 +0000863 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
864
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000865 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
866 // involved in an eviction before. If a cascade number was assigned, deny
867 // evicting anything with the same or a newer cascade number. This prevents
868 // infinite eviction loops.
869 //
870 // This works out so a register without a cascade number is allowed to evict
871 // anything, and it can be evicted by anything.
872 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
873 if (!Cascade)
874 Cascade = NextCascade;
875
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000876 EvictionCost Cost;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000877 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
878 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000879 // If there is 10 or more interferences, chances are one is heavier.
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000880 if (Q.collectInterferingVRegs(10) >= 10)
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000881 return false;
882
Jakob Stoklund Olesen0f175eb2011-04-11 21:47:01 +0000883 // Check if any interfering live range is heavier than MaxWeight.
884 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
885 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +0000886 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
887 "Only expecting virtual register interference from query");
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000888 // Never evict spill products. They cannot split or spill.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +0000889 if (getStage(*Intf) == RS_Done)
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +0000890 return false;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000891 // Once a live range becomes small enough, it is urgent that we find a
892 // register for it. This is indicated by an infinite spill weight. These
893 // urgent live ranges get to evict almost anything.
Jakob Stoklund Olesen05e22452012-05-30 21:46:58 +0000894 //
895 // Also allow urgent evictions of unspillable ranges from a strictly
896 // larger allocation order.
897 bool Urgent = !VirtReg.isSpillable() &&
898 (Intf->isSpillable() ||
899 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
900 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000901 // Only evict older cascades or live ranges without a cascade.
902 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
903 if (Cascade <= IntfCascade) {
904 if (!Urgent)
905 return false;
906 // We permit breaking cascades for urgent evictions. It should be the
907 // last resort, though, so make it really expensive.
908 Cost.BrokenHints += 10;
909 }
910 // Would this break a satisfied hint?
911 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
912 // Update eviction cost.
913 Cost.BrokenHints += BreaksHint;
914 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
915 // Abort if this would be too expensive.
916 if (!(Cost < MaxCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000917 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000918 if (Urgent)
919 continue;
Andrew Trickc2ab53a2013-11-29 23:49:38 +0000920 // Apply the eviction policy for non-urgent evictions.
921 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
922 return false;
Andrew Trick84852572013-07-25 18:35:14 +0000923 // If !MaxCost.isMax(), then we're just looking for a cheap register.
924 // Evicting another local live range in this case could lead to suboptimal
925 // coloring.
Andrew Trick8bb0a252013-07-25 18:35:19 +0000926 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
Quentin Colombet5caa6a22014-07-02 18:32:04 +0000927 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
Andrew Trick84852572013-07-25 18:35:14 +0000928 return false;
Andrew Trick8bb0a252013-07-25 18:35:19 +0000929 }
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000930 }
931 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +0000932 MaxCost = Cost;
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +0000933 return true;
934}
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +0000935
Marina Yatsinaf9371d82017-10-22 17:59:38 +0000936/// \brief Return true if all interferences between VirtReg and PhysReg between
937/// Start and End can be evicted.
938///
939/// \param VirtReg Live range that is about to be assigned.
940/// \param PhysReg Desired register for assignment.
941/// \param Start Start of range to look for interferences.
942/// \param End End of range to look for interferences.
943/// \param MaxCost Only look for cheaper candidates and update with new cost
944/// when returning true.
945/// \return True when interference can be evicted cheaper than MaxCost.
946bool RAGreedy::canEvictInterferenceInRange(LiveInterval &VirtReg,
947 unsigned PhysReg, SlotIndex Start,
948 SlotIndex End,
949 EvictionCost &MaxCost) {
950 EvictionCost Cost;
951
952 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
953 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
954
955 // Check if any interfering live range is heavier than MaxWeight.
956 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
957 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
958
959 // Check if interference overlast the segment in interest.
960 if (!Intf->overlaps(Start, End))
961 continue;
962
963 // Cannot evict non virtual reg interference.
964 if (!TargetRegisterInfo::isVirtualRegister(Intf->reg))
965 return false;
966 // Never evict spill products. They cannot split or spill.
967 if (getStage(*Intf) == RS_Done)
968 return false;
969
970 // Would this break a satisfied hint?
971 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
972 // Update eviction cost.
973 Cost.BrokenHints += BreaksHint;
974 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
975 // Abort if this would be too expensive.
976 if (!(Cost < MaxCost))
977 return false;
978 }
979 }
980
981 if (Cost.MaxWeight == 0)
982 return false;
983
984 MaxCost = Cost;
985 return true;
986}
987
988/// \brief Return tthe physical register that will be best
989/// candidate for eviction by a local split interval that will be created
990/// between Start and End.
991///
992/// \param Order The allocation order
993/// \param VirtReg Live range that is about to be assigned.
994/// \param Start Start of range to look for interferences
995/// \param End End of range to look for interferences
996/// \param BestEvictweight The eviction cost of that eviction
997/// \return The PhysReg which is the best candidate for eviction and the
998/// eviction cost in BestEvictweight
999unsigned RAGreedy::getCheapestEvicteeWeight(const AllocationOrder &Order,
1000 LiveInterval &VirtReg,
1001 SlotIndex Start, SlotIndex End,
1002 float *BestEvictweight) {
1003 EvictionCost BestEvictCost;
1004 BestEvictCost.setMax();
1005 BestEvictCost.MaxWeight = VirtReg.weight;
1006 unsigned BestEvicteePhys = 0;
1007
1008 // Go over all physical registers and find the best candidate for eviction
1009 for (auto PhysReg : Order.getOrder()) {
1010
1011 if (!canEvictInterferenceInRange(VirtReg, PhysReg, Start, End,
1012 BestEvictCost))
1013 continue;
1014
1015 // Best so far.
1016 BestEvicteePhys = PhysReg;
1017 }
1018 *BestEvictweight = BestEvictCost.MaxWeight;
1019 return BestEvicteePhys;
1020}
1021
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001022/// evictInterference - Evict any interferring registers that prevent VirtReg
1023/// from being assigned to Physreg. This assumes that canEvictInterference
1024/// returned true.
1025void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001026 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001027 // Make sure that VirtReg has a cascade number, and assign that cascade
1028 // number to every evicted register. These live ranges than then only be
1029 // evicted by a newer cascade, preventing infinite loops.
1030 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
1031 if (!Cascade)
1032 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
1033
1034 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
1035 << " interference: Cascade " << Cascade << '\n');
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001036
1037 // Collect all interfering virtregs first.
1038 SmallVector<LiveInterval*, 8> Intfs;
1039 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1040 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
Matthias Braunffe40dd2017-03-03 23:27:20 +00001041 // We usually have the interfering VRegs cached so collectInterferingVRegs()
1042 // should be fast, we may need to recalculate if when different physregs
1043 // overlap the same register unit so we had different SubRanges queried
1044 // against it.
1045 Q.collectInterferingVRegs();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001046 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
1047 Intfs.append(IVR.begin(), IVR.end());
1048 }
1049
1050 // Evict them second. This will invalidate the queries.
1051 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
1052 LiveInterval *Intf = Intfs[i];
1053 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
1054 if (!VRM->hasPhys(Intf->reg))
1055 continue;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001056
1057 LastEvicted.addEviction(PhysReg, VirtReg.reg, Intf->reg);
1058
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00001059 Matrix->unassign(*Intf);
1060 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
1061 VirtReg.isSpillable() < Intf->isSpillable()) &&
1062 "Cannot decrease cascade number, illegal eviction");
1063 ExtraRegInfo[Intf->reg].Cascade = Cascade;
1064 ++NumEvicted;
Mark Laceyf9ea8852013-08-14 23:50:04 +00001065 NewVRegs.push_back(Intf->reg);
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001066 }
1067}
1068
Matthias Braun953393a2015-07-14 17:38:17 +00001069/// Returns true if the given \p PhysReg is a callee saved register and has not
1070/// been used for allocation yet.
1071bool RAGreedy::isUnusedCalleeSavedReg(unsigned PhysReg) const {
1072 unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
1073 if (CSR == 0)
1074 return false;
1075
1076 return !Matrix->isPhysRegUsed(PhysReg);
1077}
1078
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001079/// tryEvict - Try to evict all interferences for a physreg.
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00001080/// @param VirtReg Currently unassigned virtual register.
1081/// @param Order Physregs to try.
1082/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001083unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
1084 AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001085 SmallVectorImpl<unsigned> &NewVRegs,
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001086 unsigned CostPerUseLimit) {
Matthias Braun9f15a792016-11-18 19:43:18 +00001087 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
1088 TimePassesIsEnabled);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001089
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001090 // Keep track of the cheapest interference seen so far.
Andrew Trick3621b8a2013-11-22 19:07:38 +00001091 EvictionCost BestCost;
1092 BestCost.setMax();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001093 unsigned BestPhys = 0;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001094 unsigned OrderLimit = Order.getOrder().size();
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001095
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001096 // When we are just looking for a reduced cost per use, don't break any
1097 // hints, and only evict smaller spill weights.
1098 if (CostPerUseLimit < ~0u) {
1099 BestCost.BrokenHints = 0;
1100 BestCost.MaxWeight = VirtReg.weight;
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001101
1102 // Check of any registers in RC are below CostPerUseLimit.
1103 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
1104 unsigned MinCost = RegClassInfo.getMinCost(RC);
1105 if (MinCost >= CostPerUseLimit) {
Craig Toppercf0444b2014-11-17 05:50:14 +00001106 DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = " << MinCost
Jakob Stoklund Olesen3dd236c2013-01-12 00:57:44 +00001107 << ", no cheaper registers to be found.\n");
1108 return 0;
1109 }
1110
1111 // It is normal for register classes to have a long tail of registers with
1112 // the same cost. We don't need to look at them if they're too expensive.
1113 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
1114 OrderLimit = RegClassInfo.getLastCostChange(RC);
1115 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
1116 }
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001117 }
1118
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001119 Order.rewind();
Aditya Nandakumar73f3d332013-12-05 21:18:40 +00001120 while (unsigned PhysReg = Order.next(OrderLimit)) {
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001121 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
1122 continue;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001123 // The first use of a callee-saved register in a function has cost 1.
1124 // Don't start using a CSR when the CostPerUseLimit is low.
Matthias Braun953393a2015-07-14 17:38:17 +00001125 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
1126 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
1127 << PrintReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
1128 << '\n');
1129 continue;
1130 }
Jakob Stoklund Olesen0e34c1d2011-04-20 18:19:48 +00001131
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001132 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001133 continue;
1134
1135 // Best so far.
1136 BestPhys = PhysReg;
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001137
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +00001138 // Stop if the hint can be used.
Jakob Stoklund Olesen3cb2cb82012-12-04 22:25:16 +00001139 if (Order.isHint())
Jakob Stoklund Olesen9918b332011-02-25 01:04:22 +00001140 break;
Jakob Stoklund Olesen1305bc02011-02-09 01:14:03 +00001141 }
1142
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001143 if (!BestPhys)
1144 return 0;
1145
Jakob Stoklund Olesen4931bbc2011-07-08 20:46:18 +00001146 evictInterference(VirtReg, BestPhys, NewVRegs);
Jakob Stoklund Olesen6bd68cd2011-02-23 00:29:52 +00001147 return BestPhys;
Andrew Trickccef0982010-12-09 18:15:21 +00001148}
1149
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00001150//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001151// Region Splitting
1152//===----------------------------------------------------------------------===//
1153
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001154/// addSplitConstraints - Fill out the SplitConstraints vector based on the
1155/// interference pattern in Physreg and its aliases. Add the constraints to
1156/// SpillPlacement and return the static cost of this split in Cost, assuming
1157/// that all preferences in SplitConstraints are met.
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001158/// Return false if there are no bundles with positive bias.
1159bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001160 BlockFrequency &Cost) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001161 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001162
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001163 // Reset interference dependent info.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001164 SplitConstraints.resize(UseBlocks.size());
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001165 BlockFrequency StaticCost = 0;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001166 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1167 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001168 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001169
Jakob Stoklund Olesenb1b76ad2011-02-09 22:50:26 +00001170 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001171 Intf.moveToBlock(BC.Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001172 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
1173 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
David Blaikie041f1aa2013-05-15 07:36:59 +00001174 BC.ChangesValue = BI.FirstDef.isValid();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001175
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001176 if (!Intf.hasInterference())
1177 continue;
1178
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001179 // Number of spill code instructions to insert.
1180 unsigned Ins = 0;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001181
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001182 // Interference for the live-in value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001183 if (BI.LiveIn) {
Richard Trieu7a083812016-02-18 22:09:30 +00001184 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
1185 BC.Entry = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001186 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +00001187 } else if (Intf.first() < BI.FirstInstr) {
1188 BC.Entry = SpillPlacement::PrefSpill;
1189 ++Ins;
1190 } else if (Intf.first() < BI.LastInstr) {
1191 ++Ins;
1192 }
Jakob Stoklund Olesenf248b202011-02-08 23:02:58 +00001193 }
1194
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001195 // Interference for the live-out value.
Jakob Stoklund Olesenca26e0a2011-04-02 06:03:38 +00001196 if (BI.LiveOut) {
Richard Trieu7a083812016-02-18 22:09:30 +00001197 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
1198 BC.Exit = SpillPlacement::MustSpill;
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001199 ++Ins;
Richard Trieu7a083812016-02-18 22:09:30 +00001200 } else if (Intf.last() > BI.LastInstr) {
1201 BC.Exit = SpillPlacement::PrefSpill;
1202 ++Ins;
1203 } else if (Intf.last() > BI.FirstInstr) {
1204 ++Ins;
1205 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001206 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001207
1208 // Accumulate the total frequency of inserted spill code.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001209 while (Ins--)
1210 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001211 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001212 Cost = StaticCost;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001213
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001214 // Add constraints for use-blocks. Note that these are the only constraints
1215 // that may add a positive bias, it is downhill from here.
1216 SpillPlacer->addConstraints(SplitConstraints);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001217 return SpillPlacer->scanActiveBundles();
1218}
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001219
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001220/// addThroughConstraints - Add constraints and links to SpillPlacer from the
1221/// live-through blocks in Blocks.
1222void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
1223 ArrayRef<unsigned> Blocks) {
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001224 const unsigned GroupSize = 8;
1225 SpillPlacement::BlockConstraint BCS[GroupSize];
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001226 unsigned TBS[GroupSize];
1227 unsigned B = 0, T = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001228
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001229 for (unsigned i = 0; i != Blocks.size(); ++i) {
1230 unsigned Number = Blocks[i];
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001231 Intf.moveToBlock(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001232
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001233 if (!Intf.hasInterference()) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001234 assert(T < GroupSize && "Array overflow");
1235 TBS[T] = Number;
1236 if (++T == GroupSize) {
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001237 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001238 T = 0;
1239 }
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001240 continue;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001241 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001242
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001243 assert(B < GroupSize && "Array overflow");
1244 BCS[B].Number = Number;
1245
Jakob Stoklund Olesen6d2bbc12011-04-07 17:27:46 +00001246 // Interference for the live-in value.
1247 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
1248 BCS[B].Entry = SpillPlacement::MustSpill;
1249 else
1250 BCS[B].Entry = SpillPlacement::PrefSpill;
1251
1252 // Interference for the live-out value.
1253 if (Intf.last() >= SA->getLastSplitPoint(Number))
1254 BCS[B].Exit = SpillPlacement::MustSpill;
1255 else
1256 BCS[B].Exit = SpillPlacement::PrefSpill;
1257
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001258 if (++B == GroupSize) {
Craig Toppere1d12942014-08-27 05:25:25 +00001259 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001260 B = 0;
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001261 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001262 }
1263
Craig Toppere1d12942014-08-27 05:25:25 +00001264 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001265 SpillPlacer->addLinks(makeArrayRef(TBS, T));
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001266}
1267
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001268void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001269 // Keep track of through blocks that have not been added to SpillPlacer.
1270 BitVector Todo = SA->getThroughBlocks();
1271 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
1272 unsigned AddedTo = 0;
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001273#ifndef NDEBUG
1274 unsigned Visited = 0;
1275#endif
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001276
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001277 while (true) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001278 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001279 // Find new through blocks in the periphery of PrefRegBundles.
1280 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
1281 unsigned Bundle = NewBundles[i];
1282 // Look at all blocks connected to Bundle in the full graph.
1283 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
1284 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
1285 I != E; ++I) {
1286 unsigned Block = *I;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001287 if (!Todo.test(Block))
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001288 continue;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001289 Todo.reset(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001290 // This is a new through block. Add it to SpillPlacer later.
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001291 ActiveBlocks.push_back(Block);
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001292#ifndef NDEBUG
1293 ++Visited;
1294#endif
1295 }
1296 }
1297 // Any new blocks to add?
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001298 if (ActiveBlocks.size() == AddedTo)
1299 break;
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001300
1301 // Compute through constraints from the interference, or assume that all
1302 // through blocks prefer spilling when forming compact regions.
Craig Toppere1d12942014-08-27 05:25:25 +00001303 auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
Jakob Stoklund Olesena953bf12011-07-23 03:22:33 +00001304 if (Cand.PhysReg)
1305 addThroughConstraints(Cand.Intf, NewBlocks);
1306 else
Jakob Stoklund Olesen86954522011-08-03 23:09:38 +00001307 // Provide a strong negative bias on through blocks to prevent unwanted
1308 // liveness on loop backedges.
1309 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
Jakob Stoklund Olesen91f3a302011-07-05 18:46:42 +00001310 AddedTo = ActiveBlocks.size();
1311
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001312 // Perhaps iterating can enable more bundles?
1313 SpillPlacer->iterate();
1314 }
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001315 DEBUG(dbgs() << ", v=" << Visited);
1316}
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001317
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001318/// calcCompactRegion - Compute the set of edge bundles that should be live
1319/// when splitting the current live range into compact regions. Compact
1320/// regions can be computed without looking at interference. They are the
1321/// regions formed by removing all the live-through blocks from the live range.
1322///
1323/// Returns false if the current live range is already compact, or if the
1324/// compact regions would form single block regions anyway.
1325bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1326 // Without any through blocks, the live range is already compact.
1327 if (!SA->getNumThroughBlocks())
1328 return false;
1329
1330 // Compact regions don't correspond to any physreg.
1331 Cand.reset(IntfCache, 0);
1332
1333 DEBUG(dbgs() << "Compact region bundles");
1334
1335 // Use the spill placer to determine the live bundles. GrowRegion pretends
1336 // that all the through blocks have interference when PhysReg is unset.
1337 SpillPlacer->prepare(Cand.LiveBundles);
1338
1339 // The static split cost will be zero since Cand.Intf reports no interference.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001340 BlockFrequency Cost;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001341 if (!addSplitConstraints(Cand.Intf, Cost)) {
1342 DEBUG(dbgs() << ", none.\n");
1343 return false;
1344 }
1345
1346 growRegion(Cand);
1347 SpillPlacer->finish();
1348
1349 if (!Cand.LiveBundles.any()) {
1350 DEBUG(dbgs() << ", none.\n");
1351 return false;
1352 }
1353
1354 DEBUG({
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001355 for (int i : Cand.LiveBundles.set_bits())
1356 dbgs() << " EB#" << i;
Jakob Stoklund Olesenecad62f2011-07-23 03:41:57 +00001357 dbgs() << ".\n";
1358 });
1359 return true;
1360}
1361
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001362/// calcSpillCost - Compute how expensive it would be to split the live range in
1363/// SA around all use blocks instead of forming bundle regions.
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001364BlockFrequency RAGreedy::calcSpillCost() {
1365 BlockFrequency Cost = 0;
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001366 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1367 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1368 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1369 unsigned Number = BI.MBB->getNumber();
1370 // We normally only need one spill instruction - a load or a store.
1371 Cost += SpillPlacer->getBlockFrequency(Number);
1372
1373 // Unless the value is redefined in the block.
Jakob Stoklund Olesen3c145052011-08-02 23:04:08 +00001374 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1375 Cost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001376 }
1377 return Cost;
1378}
1379
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001380/// \brief Check if splitting Evictee will create a local split interval in
1381/// basic block number BBNumber that may cause a bad eviction chain. This is
1382/// intended to prevent bad eviction sequences like:
1383/// movl %ebp, 8(%esp) # 4-byte Spill
1384/// movl %ecx, %ebp
1385/// movl %ebx, %ecx
1386/// movl %edi, %ebx
1387/// movl %edx, %edi
1388/// cltd
1389/// idivl %esi
1390/// movl %edi, %edx
1391/// movl %ebx, %edi
1392/// movl %ecx, %ebx
1393/// movl %ebp, %ecx
1394/// movl 16(%esp), %ebp # 4 - byte Reload
1395///
1396/// Such sequences are created in 2 scenarios:
1397///
1398/// Scenario #1:
1399/// vreg0 is evicted from physreg0 by vreg1.
1400/// Evictee vreg0 is intended for region splitting with split candidate
1401/// physreg0 (the reg vreg0 was evicted from).
1402/// Region splitting creates a local interval because of interference with the
1403/// evictor vreg1 (normally region spliitting creates 2 interval, the "by reg"
1404/// and "by stack" intervals and local interval created when interference
1405/// occurs).
1406/// One of the split intervals ends up evicting vreg2 from physreg1.
1407/// Evictee vreg2 is intended for region splitting with split candidate
1408/// physreg1.
1409/// One of the split intervals ends up evicting vreg3 from physreg2, etc.
1410///
1411/// Scenario #2
1412/// vreg0 is evicted from physreg0 by vreg1.
1413/// vreg2 is evicted from physreg2 by vreg3 etc.
1414/// Evictee vreg0 is intended for region splitting with split candidate
1415/// physreg1.
1416/// Region splitting creates a local interval because of interference with the
1417/// evictor vreg1.
1418/// One of the split intervals ends up evicting back original evictor vreg1
1419/// from physreg0 (the reg vreg0 was evicted from).
1420/// Another evictee vreg2 is intended for region splitting with split candidate
1421/// physreg1.
1422/// One of the split intervals ends up evicting vreg3 from physreg2, etc.
1423///
1424/// \param Evictee The register considered to be split.
1425/// \param Cand The split candidate that determines the physical register
1426/// we are splitting for and the interferences.
1427/// \param BBNumber The number of a BB for which the region split process will
1428/// create a local split interval.
1429/// \param Order The phisical registers that may get evicted by a split
1430/// artifact of Evictee.
1431/// \return True if splitting Evictee may cause a bad eviction chain, false
1432/// otherwise.
1433bool RAGreedy::splitCanCauseEvictionChain(unsigned Evictee,
1434 GlobalSplitCandidate &Cand,
1435 unsigned BBNumber,
1436 const AllocationOrder &Order) {
1437 EvictionTrack::EvictorInfo VregEvictorInfo = LastEvicted.getEvictor(Evictee);
1438 unsigned Evictor = VregEvictorInfo.first;
1439 unsigned PhysReg = VregEvictorInfo.second;
1440
1441 // No actual evictor.
1442 if (!Evictor || !PhysReg)
1443 return false;
1444
1445 float MaxWeight = 0;
1446 unsigned FutureEvictedPhysReg =
1447 getCheapestEvicteeWeight(Order, LIS->getInterval(Evictee),
1448 Cand.Intf.first(), Cand.Intf.last(), &MaxWeight);
1449
1450 // The bad eviction chain occurs when either the split candidate the the
1451 // evited reg or one of the split artifact will evict the evicting reg.
1452 if ((PhysReg != Cand.PhysReg) && (PhysReg != FutureEvictedPhysReg))
1453 return false;
1454
1455 Cand.Intf.moveToBlock(BBNumber);
1456
1457 // Check to see if the Evictor contains interference (with Evictee) in the
1458 // given BB. If so, this interference caused the eviction of Evictee from
1459 // PhysReg. This suggest that we will create a local interval during the
1460 // region split to avoid this interference This local interval may cause a bad
1461 // eviction chain.
1462 if (!LIS->hasInterval(Evictor))
1463 return false;
1464 LiveInterval &EvictorLI = LIS->getInterval(Evictor);
1465 if (EvictorLI.FindSegmentContaining(Cand.Intf.first()) == EvictorLI.end())
1466 return false;
1467
1468 // Now, check to see if the local interval we will create is going to be
1469 // expensive enough to evict somebody If so, this may cause a bad eviction
1470 // chain.
1471 VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1472 float splitArtifactWeight =
1473 VRAI.futureWeight(LIS->getInterval(Evictee),
1474 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1475 if (splitArtifactWeight >= 0 && splitArtifactWeight < MaxWeight)
1476 return false;
1477
1478 return true;
1479}
1480
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001481/// calcGlobalSplitCost - Return the global split cost of following the split
1482/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001483/// interference pattern in SplitConstraints.
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001484///
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001485BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
1486 const AllocationOrder &Order,
1487 bool *CanCauseEvictionChain) {
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001488 BlockFrequency GlobalCost = 0;
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001489 const BitVector &LiveBundles = Cand.LiveBundles;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001490 unsigned VirtRegToSplit = SA->getParent().reg;
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001491 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1492 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1493 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001494 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001495 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, false)];
1496 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)];
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001497 unsigned Ins = 0;
1498
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001499 Cand.Intf.moveToBlock(BC.Number);
1500 // Check wheather a local interval is going to be created during the region
1501 // split.
1502 if (EnableAdvancedRASplitCost && CanCauseEvictionChain &&
1503 Cand.Intf.hasInterference() && BI.LiveIn && BI.LiveOut && RegIn &&
1504 RegOut) {
1505
1506 if (splitCanCauseEvictionChain(VirtRegToSplit, Cand, BC.Number, Order)) {
1507 // This interfernce cause our eviction from this assignment, we might
1508 // evict somebody else, add that cost.
1509 // See splitCanCauseEvictionChain for detailed description of scenarios.
1510 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1511 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1512
1513 *CanCauseEvictionChain = true;
1514 }
1515 }
1516
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001517 if (BI.LiveIn)
1518 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1519 if (BI.LiveOut)
1520 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001521 while (Ins--)
1522 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001523 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001524
Jakob Stoklund Olesenc49df2c2011-04-12 21:30:53 +00001525 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1526 unsigned Number = Cand.ActiveBlocks[i];
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001527 bool RegIn = LiveBundles[Bundles->getBundle(Number, false)];
1528 bool RegOut = LiveBundles[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001529 if (!RegIn && !RegOut)
1530 continue;
1531 if (RegIn && RegOut) {
1532 // We need double spill code if this block has interference.
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001533 Cand.Intf.moveToBlock(Number);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001534 if (Cand.Intf.hasInterference()) {
1535 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1536 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001537
1538 // Check wheather a local interval is going to be created during the
1539 // region split.
1540 if (EnableAdvancedRASplitCost && CanCauseEvictionChain &&
1541 splitCanCauseEvictionChain(VirtRegToSplit, Cand, Number, Order)) {
1542 // This interfernce cause our eviction from this assignment, we might
1543 // evict somebody else, add that cost.
1544 // See splitCanCauseEvictionChain for detailed description of
1545 // scenarios.
1546 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1547 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1548
1549 *CanCauseEvictionChain = true;
1550 }
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001551 }
Jakob Stoklund Olesen8ce2f432011-04-06 21:32:41 +00001552 continue;
1553 }
1554 // live-in / stack-out or stack-in live-out.
1555 GlobalCost += SpillPlacer->getBlockFrequency(Number);
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001556 }
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001557 return GlobalCost;
1558}
1559
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001560/// splitAroundRegion - Split the current live range around the regions
1561/// determined by BundleCand and GlobalCand.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001562///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001563/// Before calling this function, GlobalCand and BundleCand must be initialized
1564/// so each bundle is assigned to a valid candidate, or NoCand for the
1565/// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1566/// objects must be initialized for the current live range, and intervals
1567/// created for the used candidates.
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001568///
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001569/// @param LREdit The LiveRangeEdit object handling the current split.
1570/// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1571/// must appear in this list.
1572void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1573 ArrayRef<unsigned> UsedCands) {
1574 // These are the intervals created for new global ranges. We may create more
1575 // intervals for local ranges.
1576 const unsigned NumGlobalIntvs = LREdit.size();
1577 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1578 assert(NumGlobalIntvs && "No global intervals configured");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001579
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001580 // Isolate even single instructions when dealing with a proper sub-class.
Jakob Stoklund Olesen22f37a12011-08-06 18:20:24 +00001581 // That guarantees register class inflation for the stack interval because it
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001582 // is all copies.
1583 unsigned Reg = SA->getParent().reg;
1584 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1585
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001586 // First handle all the blocks with uses.
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001587 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1588 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1589 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001590 unsigned Number = BI.MBB->getNumber();
1591 unsigned IntvIn = 0, IntvOut = 0;
1592 SlotIndex IntfIn, IntfOut;
1593 if (BI.LiveIn) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001594 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001595 if (CandIn != NoCand) {
1596 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1597 IntvIn = Cand.IntvIdx;
1598 Cand.Intf.moveToBlock(Number);
1599 IntfIn = Cand.Intf.first();
1600 }
1601 }
1602 if (BI.LiveOut) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001603 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001604 if (CandOut != NoCand) {
1605 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1606 IntvOut = Cand.IntvIdx;
1607 Cand.Intf.moveToBlock(Number);
1608 IntfOut = Cand.Intf.last();
1609 }
1610 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001611
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001612 // Create separate intervals for isolated blocks with multiple uses.
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001613 if (!IntvIn && !IntvOut) {
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001614 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
Jakob Stoklund Olesen8627ea92011-08-05 22:20:45 +00001615 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
Jakob Stoklund Olesenadc6a4c2011-06-30 01:30:39 +00001616 SE->splitSingleBlock(BI);
Jakob Stoklund Olesenc70b6972011-04-12 19:32:53 +00001617 continue;
1618 }
1619
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001620 if (IntvIn && IntvOut)
1621 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1622 else if (IntvIn)
1623 SE->splitRegInBlock(BI, IntvIn, IntfIn);
Jakob Stoklund Olesen795da1c2011-07-15 21:47:57 +00001624 else
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001625 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001626 }
1627
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001628 // Handle live-through blocks. The relevant live-through blocks are stored in
1629 // the ActiveBlocks list with each candidate. We need to filter out
1630 // duplicates.
1631 BitVector Todo = SA->getThroughBlocks();
1632 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1633 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1634 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1635 unsigned Number = Blocks[i];
1636 if (!Todo.test(Number))
1637 continue;
1638 Todo.reset(Number);
1639
1640 unsigned IntvIn = 0, IntvOut = 0;
1641 SlotIndex IntfIn, IntfOut;
1642
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001643 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001644 if (CandIn != NoCand) {
1645 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1646 IntvIn = Cand.IntvIdx;
1647 Cand.Intf.moveToBlock(Number);
1648 IntfIn = Cand.Intf.first();
1649 }
1650
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001651 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001652 if (CandOut != NoCand) {
1653 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1654 IntvOut = Cand.IntvIdx;
1655 Cand.Intf.moveToBlock(Number);
1656 IntfOut = Cand.Intf.last();
1657 }
1658 if (!IntvIn && !IntvOut)
1659 continue;
1660 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1661 }
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00001662 }
1663
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00001664 ++NumGlobalSplits;
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001665
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001666 SmallVector<unsigned, 8> IntvMap;
1667 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00001668 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00001669
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001670 ExtraRegInfo.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesen5cc91b22011-05-28 02:32:57 +00001671 unsigned OrigBlocks = SA->getNumLiveBlocks();
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001672
1673 // Sort out the new intervals created by splitting. We get four kinds:
1674 // - Remainder intervals should not be split again.
1675 // - Candidate intervals can be assigned to Cand.PhysReg.
1676 // - Block-local splits are candidates for local splitting.
1677 // - DCE leftovers should go back on the queue.
1678 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001679 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001680
1681 // Ignore old intervals from DCE.
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001682 if (getStage(Reg) != RS_New)
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001683 continue;
1684
1685 // Remainder interval. Don't try splitting again, spill if it doesn't
1686 // allocate.
1687 if (IntvMap[i] == 0) {
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00001688 setStage(Reg, RS_Spill);
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001689 continue;
1690 }
1691
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001692 // Global intervals. Allow repeated splitting as long as the number of live
1693 // blocks is strictly decreasing.
1694 if (IntvMap[i] < NumGlobalIntvs) {
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00001695 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001696 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1697 << " blocks as original.\n");
1698 // Don't allow repeated splitting as a safe guard against looping.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00001699 setStage(Reg, RS_Split2);
Jakob Stoklund Oleseneef23272011-04-26 22:33:12 +00001700 }
1701 continue;
1702 }
1703
1704 // Other intervals are treated as new. This includes local intervals created
1705 // for blocks with multiple uses, and anything created by DCE.
Jakob Stoklund Olesen6a663b82011-04-21 18:38:15 +00001706 }
1707
Jakob Stoklund Olesen28d79cd2011-03-27 22:49:21 +00001708 if (VerifyEnabled)
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001709 MF->verify(this, "After splitting live range around region");
1710}
1711
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001712unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001713 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001714 unsigned NumCands = 0;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001715 BlockFrequency SpillCost = calcSpillCost();
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001716 BlockFrequency BestCost;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001717
1718 // Check if we can split this live range around a compact region.
Jakob Stoklund Olesen45df7e02011-09-12 16:54:42 +00001719 bool HasCompact = calcCompactRegion(GlobalCand.front());
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001720 if (HasCompact) {
1721 // Yes, keep GlobalCand[0] as the compact region candidate.
1722 NumCands = 1;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001723 BestCost = BlockFrequency::getMaxFrequency();
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001724 } else {
1725 // No benefit from the compact region, our fallback will be per-block
1726 // splitting. Make sure we find a solution that is cheaper than spilling.
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001727 BestCost = SpillCost;
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001728 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1729 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001730 }
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001731
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001732 bool CanCauseEvictionChain = false;
Manman Ren9db66b32014-03-24 23:23:42 +00001733 unsigned BestCand =
Manman Ren78cf02a2014-03-25 00:16:25 +00001734 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001735 false /*IgnoreCSR*/, &CanCauseEvictionChain);
1736
1737 // Split candidates with compact regions can cause a bad eviction sequence.
1738 // See splitCanCauseEvictionChain for detailed description of scenarios.
1739 // To avoid it, we need to comapre the cost with the spill cost and not the
1740 // current max frequency.
1741 if (HasCompact && (BestCost > SpillCost) && (BestCand != NoCand) &&
1742 CanCauseEvictionChain) {
1743 return 0;
1744 }
Manman Ren9db66b32014-03-24 23:23:42 +00001745
1746 // No solutions found, fall back to single block splitting.
1747 if (!HasCompact && BestCand == NoCand)
1748 return 0;
1749
1750 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1751}
1752
1753unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1754 AllocationOrder &Order,
1755 BlockFrequency &BestCost,
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001756 unsigned &NumCands, bool IgnoreCSR,
1757 bool *CanCauseEvictionChain) {
Manman Ren9db66b32014-03-24 23:23:42 +00001758 unsigned BestCand = NoCand;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001759 Order.rewind();
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001760 while (unsigned PhysReg = Order.next()) {
Matthias Braun953393a2015-07-14 17:38:17 +00001761 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1762 continue;
Manman Ren78cf02a2014-03-25 00:16:25 +00001763
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001764 // Discard bad candidates before we run out of interference cache cursors.
1765 // This will only affect register classes with a lot of registers (>32).
1766 if (NumCands == IntfCache.getMaxCursors()) {
1767 unsigned WorstCount = ~0u;
1768 unsigned Worst = 0;
1769 for (unsigned i = 0; i != NumCands; ++i) {
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001770 if (i == BestCand || !GlobalCand[i].PhysReg)
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001771 continue;
1772 unsigned Count = GlobalCand[i].LiveBundles.count();
Richard Trieu7a083812016-02-18 22:09:30 +00001773 if (Count < WorstCount) {
1774 Worst = i;
1775 WorstCount = Count;
1776 }
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001777 }
1778 --NumCands;
1779 GlobalCand[Worst] = GlobalCand[NumCands];
Jakob Stoklund Olesen559d4dc2011-11-01 00:02:31 +00001780 if (BestCand == NumCands)
1781 BestCand = Worst;
Jakob Stoklund Olesena153ca52011-07-14 05:35:11 +00001782 }
1783
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001784 if (GlobalCand.size() <= NumCands)
1785 GlobalCand.resize(NumCands+1);
1786 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1787 Cand.reset(IntfCache, PhysReg);
Jakob Stoklund Olesen4b598e12011-03-05 01:10:31 +00001788
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001789 SpillPlacer->prepare(Cand.LiveBundles);
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001790 BlockFrequency Cost;
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001791 if (!addSplitConstraints(Cand.Intf, Cost)) {
Jakob Stoklund Olesened47ed42011-04-09 02:59:09 +00001792 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
Jakob Stoklund Olesen81439a82011-04-06 21:32:38 +00001793 continue;
1794 }
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001795 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1796 MBFI->printBlockFreq(dbgs(), Cost));
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001797 if (Cost >= BestCost) {
1798 DEBUG({
1799 if (BestCand == NoCand)
1800 dbgs() << " worse than no bundles\n";
1801 else
1802 dbgs() << " worse than "
1803 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1804 });
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001805 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001806 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001807 growRegion(Cand);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001808
Jakob Stoklund Olesen36b5d8a2011-04-06 19:13:57 +00001809 SpillPlacer->finish();
1810
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001811 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001812 if (!Cand.LiveBundles.any()) {
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001813 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001814 continue;
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001815 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001816
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001817 bool HasEvictionChain = false;
1818 Cost += calcGlobalSplitCost(Cand, Order, &HasEvictionChain);
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001819 DEBUG({
Michael Gottesmanb78dec82013-12-14 00:25:45 +00001820 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1821 << " with bundles";
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00001822 for (int i : Cand.LiveBundles.set_bits())
Jakob Stoklund Olesen1a9b66c2011-03-05 03:28:51 +00001823 dbgs() << " EB#" << i;
1824 dbgs() << ".\n";
1825 });
Jakob Stoklund Olesen032891b2011-04-22 22:47:40 +00001826 if (Cost < BestCost) {
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001827 BestCand = NumCands;
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00001828 BestCost = Cost;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001829 // See splitCanCauseEvictionChain for detailed description of bad
1830 // eviction chain scenarios.
1831 if (CanCauseEvictionChain)
1832 *CanCauseEvictionChain = HasEvictionChain;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001833 }
Jakob Stoklund Olesend7e99372011-07-14 00:17:10 +00001834 ++NumCands;
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001835 }
Marina Yatsinaf9371d82017-10-22 17:59:38 +00001836
1837 if (CanCauseEvictionChain && BestCand != NoCand) {
1838 // See splitCanCauseEvictionChain for detailed description of bad
1839 // eviction chain scenarios.
1840 DEBUG(dbgs() << "Best split candidate of vreg "
1841 << PrintReg(VirtReg.reg, TRI) << " may ");
1842 if (!(*CanCauseEvictionChain))
1843 DEBUG(dbgs() << "not ");
1844 DEBUG(dbgs() << "cause bad eviction chain\n");
1845 }
1846
Manman Ren9db66b32014-03-24 23:23:42 +00001847 return BestCand;
1848}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001849
Manman Ren9db66b32014-03-24 23:23:42 +00001850unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1851 bool HasCompact,
1852 SmallVectorImpl<unsigned> &NewVRegs) {
1853 SmallVector<unsigned, 8> UsedCands;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001854 // Prepare split editor.
Wei Mi9a16d652016-04-13 03:08:27 +00001855 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001856 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001857
1858 // Assign all edge bundles to the preferred candidate, or NoCand.
1859 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1860
1861 // Assign bundles for the best candidate region.
1862 if (BestCand != NoCand) {
1863 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1864 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1865 UsedCands.push_back(BestCand);
1866 Cand.IntvIdx = SE->openIntv();
1867 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1868 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001869 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001870 }
1871 }
1872
1873 // Assign bundles for the compact region.
1874 if (HasCompact) {
1875 GlobalSplitCandidate &Cand = GlobalCand.front();
1876 assert(!Cand.PhysReg && "Compact region has no physreg");
1877 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1878 UsedCands.push_back(0);
1879 Cand.IntvIdx = SE->openIntv();
1880 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1881 << Cand.IntvIdx << ".\n");
Chandler Carruth77eb5a02011-08-03 23:07:27 +00001882 (void)B;
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00001883 }
1884 }
1885
1886 splitAroundRegion(LREdit, UsedCands);
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00001887 return 0;
1888}
1889
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00001890//===----------------------------------------------------------------------===//
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001891// Per-Block Splitting
1892//===----------------------------------------------------------------------===//
1893
1894/// tryBlockSplit - Split a global live range around every block with uses. This
1895/// creates a lot of local live ranges, that will be split by tryLocalSplit if
1896/// they don't allocate.
1897unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001898 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001899 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1900 unsigned Reg = VirtReg.reg;
1901 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
Wei Mi9a16d652016-04-13 03:08:27 +00001902 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Oleseneecb2fb2011-09-12 16:49:21 +00001903 SE->reset(LREdit, SplitSpillMode);
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001904 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1905 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1906 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1907 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1908 SE->splitSingleBlock(BI);
1909 }
1910 // No blocks were split.
1911 if (LREdit.empty())
1912 return 0;
1913
1914 // We did split for some blocks.
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001915 SmallVector<unsigned, 8> IntvMap;
1916 SE->finish(&IntvMap);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001917
1918 // Tell LiveDebugVariables about the new ranges.
Mark Laceyf9ea8852013-08-14 23:50:04 +00001919 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0de95ef2011-08-05 23:10:40 +00001920
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001921 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1922
1923 // Sort out the new intervals created by splitting. The remainder interval
1924 // goes straight to spilling, the new local ranges get to stay RS_New.
1925 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00001926 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
Jakob Stoklund Olesen02cf10b2011-08-05 23:50:31 +00001927 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1928 setStage(LI, RS_Spill);
1929 }
1930
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00001931 if (VerifyEnabled)
1932 MF->verify(this, "After splitting live range around basic blocks");
1933 return 0;
1934}
1935
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001936//===----------------------------------------------------------------------===//
1937// Per-Instruction Splitting
1938//===----------------------------------------------------------------------===//
1939
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001940/// Get the number of allocatable registers that match the constraints of \p Reg
1941/// on \p MI and that are also in \p SuperRC.
1942static unsigned getNumAllocatableRegsForConstraints(
1943 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1944 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1945 const RegisterClassInfo &RCI) {
1946 assert(SuperRC && "Invalid register class");
1947
1948 const TargetRegisterClass *ConstrainedRC =
1949 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1950 /* ExploreBundle */ true);
1951 if (!ConstrainedRC)
1952 return 0;
1953 return RCI.getNumAllocatableRegs(ConstrainedRC);
1954}
1955
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001956/// tryInstructionSplit - Split a live range around individual instructions.
1957/// This is normally not worthwhile since the spiller is doing essentially the
1958/// same thing. However, when the live range is in a constrained register
1959/// class, it may help to insert copies such that parts of the live range can
1960/// be moved to a larger register class.
1961///
1962/// This is similar to spilling to a larger register class.
1963unsigned
1964RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00001965 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001966 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001967 // There is no point to this if there are no larger sub-classes.
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001968 if (!RegClassInfo.isProperSubClass(CurRC))
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001969 return 0;
1970
1971 // Always enable split spill mode, since we're effectively spilling to a
1972 // register.
Wei Mi9a16d652016-04-13 03:08:27 +00001973 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001974 SE->reset(LREdit, SplitEditor::SM_Size);
1975
1976 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1977 if (Uses.size() <= 1)
1978 return 0;
1979
1980 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1981
Eric Christopher433c4322015-03-10 23:46:01 +00001982 const TargetRegisterClass *SuperRC =
1983 TRI->getLargestLegalSuperClass(CurRC, *MF);
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001984 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1985 // Split around every non-copy instruction if this split will relax
1986 // the constraints on the virtual register.
1987 // Otherwise, splitting just inserts uncoalescable copies that do not help
1988 // the allocation.
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001989 for (unsigned i = 0; i != Uses.size(); ++i) {
1990 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00001991 if (MI->isFullCopy() ||
1992 SuperRCNumAllocatableRegs ==
1993 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1994 TRI, RCI)) {
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00001995 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1996 continue;
1997 }
1998 SE->openIntv();
1999 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
2000 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
2001 SE->useIntv(SegStart, SegStop);
2002 }
2003
2004 if (LREdit.empty()) {
2005 DEBUG(dbgs() << "All uses were copies.\n");
2006 return 0;
2007 }
2008
2009 SmallVector<unsigned, 8> IntvMap;
2010 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00002011 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002012 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2013
2014 // Assign all new registers to RS_Spill. This was the last chance.
2015 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
2016 return 0;
2017}
2018
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00002019//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002020// Local Splitting
2021//===----------------------------------------------------------------------===//
2022
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002023/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
2024/// in order to use PhysReg between two entries in SA->UseSlots.
2025///
2026/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
2027///
2028void RAGreedy::calcGapWeights(unsigned PhysReg,
2029 SmallVectorImpl<float> &GapWeight) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00002030 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
2031 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00002032 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002033 const unsigned NumGaps = Uses.size()-1;
2034
2035 // Start and end points for the interference check.
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00002036 SlotIndex StartIdx =
2037 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
2038 SlotIndex StopIdx =
2039 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002040
2041 GapWeight.assign(NumGaps, 0.0f);
2042
2043 // Add interference from each overlapping register.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002044 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2045 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
2046 .checkInterference())
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002047 continue;
2048
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00002049 // We know that VirtReg is a continuous interval from FirstInstr to
2050 // LastInstr, so we don't need InterferenceQuery.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002051 //
2052 // Interference that overlaps an instruction is counted in both gaps
2053 // surrounding the instruction. The exception is interference before
2054 // StartIdx and after StopIdx.
2055 //
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002056 LiveIntervalUnion::SegmentIter IntI =
2057 Matrix->getLiveUnions()[*Units] .find(StartIdx);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002058 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
2059 // Skip the gaps before IntI.
2060 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
2061 if (++Gap == NumGaps)
2062 break;
2063 if (Gap == NumGaps)
2064 break;
2065
2066 // Update the gaps covered by IntI.
2067 const float weight = IntI.value()->weight;
2068 for (; Gap != NumGaps; ++Gap) {
2069 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
2070 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
2071 break;
2072 }
2073 if (Gap == NumGaps)
2074 break;
2075 }
2076 }
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002077
2078 // Add fixed interference.
2079 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00002080 const LiveRange &LR = LIS->getRegUnit(*Units);
2081 LiveRange::const_iterator I = LR.find(StartIdx);
2082 LiveRange::const_iterator E = LR.end();
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002083
2084 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
2085 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
2086 while (Uses[Gap+1].getBoundaryIndex() < I->start)
2087 if (++Gap == NumGaps)
2088 break;
2089 if (Gap == NumGaps)
2090 break;
2091
2092 for (; Gap != NumGaps; ++Gap) {
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002093 GapWeight[Gap] = huge_valf;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002094 if (Uses[Gap+1].getBaseIndex() >= I->end)
2095 break;
2096 }
2097 if (Gap == NumGaps)
2098 break;
2099 }
2100 }
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002101}
2102
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002103/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
2104/// basic block.
2105///
2106unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002107 SmallVectorImpl<unsigned> &NewVRegs) {
Jakob Stoklund Olesenbf91c4e2011-04-06 03:57:00 +00002108 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
2109 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002110
2111 // Note that it is possible to have an interval that is live-in or live-out
2112 // while only covering a single block - A phi-def can use undef values from
2113 // predecessors, and the block could be a single-block loop.
2114 // We don't bother doing anything clever about such a case, we simply assume
Jakob Stoklund Olesen43859a62011-08-02 22:54:14 +00002115 // that the interval is continuous from FirstInstr to LastInstr. We should
2116 // make sure that we don't do anything illegal to such an interval, though.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002117
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00002118 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002119 if (Uses.size() <= 2)
2120 return 0;
2121 const unsigned NumGaps = Uses.size()-1;
2122
2123 DEBUG({
2124 dbgs() << "tryLocalSplit: ";
2125 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
Jakob Stoklund Olesen994fed62012-01-12 17:53:44 +00002126 dbgs() << ' ' << Uses[i];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002127 dbgs() << '\n';
2128 });
2129
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002130 // If VirtReg is live across any register mask operands, compute a list of
2131 // gaps with register masks.
2132 SmallVector<unsigned, 8> RegMaskGaps;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002133 if (Matrix->checkRegMaskInterference(VirtReg)) {
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002134 // Get regmask slots for the whole block.
2135 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002136 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002137 // Constrain to VirtReg's live range.
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002138 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
2139 Uses.front().getRegSlot()) - RMS.begin();
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002140 unsigned re = RMS.size();
2141 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002142 // Look for Uses[i] <= RMS <= Uses[i+1].
2143 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
2144 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002145 continue;
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002146 // Skip a regmask on the same instruction as the last use. It doesn't
2147 // overlap the live range.
2148 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
2149 break;
2150 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002151 RegMaskGaps.push_back(i);
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002152 // Advance ri to the next gap. A regmask on one of the uses counts in
2153 // both gaps.
2154 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
2155 ++ri;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002156 }
Jakob Stoklund Olesenb0c0d342012-02-14 23:51:27 +00002157 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002158 }
2159
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002160 // Since we allow local split results to be split again, there is a risk of
2161 // creating infinite loops. It is tempting to require that the new live
2162 // ranges have less instructions than the original. That would guarantee
2163 // convergence, but it is too strict. A live range with 3 instructions can be
2164 // split 2+3 (including the COPY), and we want to allow that.
2165 //
2166 // Instead we use these rules:
2167 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002168 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002169 // noop split, of course).
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002170 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002171 // the new ranges must have fewer instructions than before the split.
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002172 // 3. New ranges with the same number of instructions are marked RS_Split2,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002173 // smaller ranges are marked RS_New.
2174 //
2175 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
2176 // excessive splitting and infinite loops.
2177 //
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002178 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002179
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002180 // Best split candidate.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002181 unsigned BestBefore = NumGaps;
2182 unsigned BestAfter = 0;
2183 float BestDiff = 0;
2184
Jakob Stoklund Olesenefeb3a12013-07-16 18:26:18 +00002185 const float blockFreq =
2186 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
Michael Gottesman5e985ee2013-12-14 02:37:38 +00002187 (1.0f / MBFI->getEntryFreq());
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002188 SmallVector<float, 8> GapWeight;
2189
2190 Order.rewind();
2191 while (unsigned PhysReg = Order.next()) {
2192 // Keep track of the largest spill weight that would need to be evicted in
2193 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
2194 calcGapWeights(PhysReg, GapWeight);
2195
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002196 // Remove any gaps with regmask clobbers.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002197 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002198 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002199 GapWeight[RegMaskGaps[i]] = huge_valf;
Jakob Stoklund Olesen17402e32012-02-11 00:42:18 +00002200
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002201 // Try to find the best sequence of gaps to close.
2202 // The new spill weight must be larger than any gap interference.
2203
2204 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002205 unsigned SplitBefore = 0, SplitAfter = 1;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002206
2207 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
2208 // It is the spill weight that needs to be evicted.
2209 float MaxGap = GapWeight[0];
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002210
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002211 while (true) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002212 // Live before/after split?
2213 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
2214 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
2215
2216 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
2217 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
2218 << " i=" << MaxGap);
2219
2220 // Stop before the interval gets so big we wouldn't be making progress.
2221 if (!LiveBefore && !LiveAfter) {
2222 DEBUG(dbgs() << " all\n");
2223 break;
2224 }
2225 // Should the interval be extended or shrunk?
2226 bool Shrink = true;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002227
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002228 // How many gaps would the new range have?
2229 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
2230
2231 // Legally, without causing looping?
2232 bool Legal = !ProgressRequired || NewGaps < NumGaps;
2233
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002234 if (Legal && MaxGap < huge_valf) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002235 // Estimate the new spill weight. Each instruction reads or writes the
2236 // register. Conservatively assume there are no read-modify-write
2237 // instructions.
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002238 //
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002239 // Try to guess the size of the new interval.
Arnaud A. de Grandmaison829dd812014-11-04 20:51:24 +00002240 const float EstWeight = normalizeSpillWeight(
2241 blockFreq * (NewGaps + 1),
2242 Uses[SplitBefore].distance(Uses[SplitAfter]) +
2243 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
2244 1);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002245 // Would this split be possible to allocate?
2246 // Never allocate all gaps, we wouldn't be making progress.
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00002247 DEBUG(dbgs() << " w=" << EstWeight);
2248 if (EstWeight * Hysteresis >= MaxGap) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002249 Shrink = false;
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00002250 float Diff = EstWeight - MaxGap;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002251 if (Diff > BestDiff) {
2252 DEBUG(dbgs() << " (best)");
Jakob Stoklund Olesen357dd362011-04-30 05:07:46 +00002253 BestDiff = Hysteresis * Diff;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002254 BestBefore = SplitBefore;
2255 BestAfter = SplitAfter;
2256 }
2257 }
2258 }
2259
2260 // Try to shrink.
2261 if (Shrink) {
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002262 if (++SplitBefore < SplitAfter) {
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002263 DEBUG(dbgs() << " shrink\n");
2264 // Recompute the max when necessary.
2265 if (GapWeight[SplitBefore - 1] >= MaxGap) {
2266 MaxGap = GapWeight[SplitBefore];
2267 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
2268 MaxGap = std::max(MaxGap, GapWeight[i]);
2269 }
2270 continue;
2271 }
2272 MaxGap = 0;
2273 }
2274
2275 // Try to extend the interval.
2276 if (SplitAfter >= NumGaps) {
2277 DEBUG(dbgs() << " end\n");
2278 break;
2279 }
2280
2281 DEBUG(dbgs() << " extend\n");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002282 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002283 }
2284 }
2285
2286 // Didn't find any candidates?
2287 if (BestBefore == NumGaps)
2288 return 0;
2289
2290 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
2291 << '-' << Uses[BestAfter] << ", " << BestDiff
2292 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
2293
Wei Mi9a16d652016-04-13 03:08:27 +00002294 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00002295 SE->reset(LREdit);
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002296
Jakob Stoklund Olesenc9601982011-03-03 01:29:13 +00002297 SE->openIntv();
2298 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
2299 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
2300 SE->useIntv(SegStart, SegStop);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002301 SmallVector<unsigned, 8> IntvMap;
2302 SE->finish(&IntvMap);
Mark Laceyf9ea8852013-08-14 23:50:04 +00002303 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002304
2305 // If the new range has the same number of instructions as before, mark it as
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002306 // RS_Split2 so the next split will be forced to make progress. Otherwise,
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002307 // leave the new intervals as RS_New so they can compete.
2308 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
2309 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
2310 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
2311 if (NewGaps >= NumGaps) {
2312 DEBUG(dbgs() << "Tagging non-progress ranges: ");
2313 assert(!ProgressRequired && "Didn't make progress when it was required.");
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002314 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
2315 if (IntvMap[i] == 1) {
Mark Laceyf9ea8852013-08-14 23:50:04 +00002316 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
2317 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
Jakob Stoklund Olesendf476272011-06-06 23:55:20 +00002318 }
2319 DEBUG(dbgs() << '\n');
2320 }
Jakob Stoklund Olesen99827e82011-02-17 22:53:48 +00002321 ++NumLocalSplits;
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002322
2323 return 0;
2324}
2325
2326//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002327// Live Range Splitting
2328//===----------------------------------------------------------------------===//
2329
2330/// trySplit - Try to split VirtReg or one of its interferences, making it
2331/// assignable.
2332/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
2333unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002334 SmallVectorImpl<unsigned>&NewVRegs) {
Jakob Stoklund Olesend4bb1d42011-08-05 23:50:33 +00002335 // Ranges must be Split2 or less.
2336 if (getStage(VirtReg) >= RS_Spill)
2337 return 0;
2338
Jakob Stoklund Olesen93c87362011-02-17 19:13:53 +00002339 // Local intervals are handled separately.
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00002340 if (LIS->intervalIsInOneMBB(VirtReg)) {
Matthias Braun9f15a792016-11-18 19:43:18 +00002341 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
2342 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002343 SA->analyze(&VirtReg);
Jakob Stoklund Olesen0ce90492012-05-23 22:37:27 +00002344 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
2345 if (PhysReg || !NewVRegs.empty())
2346 return PhysReg;
2347 return tryInstructionSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen609bc442011-02-19 00:38:40 +00002348 }
2349
Matthias Braun9f15a792016-11-18 19:43:18 +00002350 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
2351 TimerGroupDescription, TimePassesIsEnabled);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002352
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002353 SA->analyze(&VirtReg);
2354
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002355 // FIXME: SplitAnalysis may repair broken live ranges coming from the
2356 // coalescer. That may cause the range to become allocatable which means that
2357 // tryRegionSplit won't be making progress. This check should be replaced with
2358 // an assertion when the coalescer is fixed.
2359 if (SA->didRepairRange()) {
2360 // VirtReg has changed, so all cached queries are invalid.
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00002361 Matrix->invalidateVirtRegs();
Jakob Stoklund Oleseneaa6ed12011-05-03 20:42:13 +00002362 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
2363 return PhysReg;
2364 }
2365
Jakob Stoklund Olesen45011172011-07-25 15:25:43 +00002366 // First try to split around a region spanning multiple blocks. RS_Split2
2367 // ranges already made dubious progress with region splitting, so they go
2368 // straight to single block splitting.
2369 if (getStage(VirtReg) < RS_Split2) {
2370 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2371 if (PhysReg || !NewVRegs.empty())
2372 return PhysReg;
2373 }
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002374
Jakob Stoklund Olesencef5d8f2011-08-05 23:04:18 +00002375 // Then isolate blocks.
2376 return tryBlockSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002377}
2378
Quentin Colombet87769712014-02-05 22:13:59 +00002379//===----------------------------------------------------------------------===//
2380// Last Chance Recoloring
2381//===----------------------------------------------------------------------===//
2382
Mikael Holmen07f1e2e2017-09-28 08:22:35 +00002383/// Return true if \p reg has any tied def operand.
2384static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) {
2385 for (const MachineOperand &MO : MRI->def_operands(reg))
2386 if (MO.isTied())
2387 return true;
2388
2389 return false;
2390}
2391
Quentin Colombet87769712014-02-05 22:13:59 +00002392/// mayRecolorAllInterferences - Check if the virtual registers that
2393/// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2394/// recolored to free \p PhysReg.
2395/// When true is returned, \p RecoloringCandidates has been augmented with all
2396/// the live intervals that need to be recolored in order to free \p PhysReg
2397/// for \p VirtReg.
2398/// \p FixedRegisters contains all the virtual registers that cannot be
2399/// recolored.
2400bool
2401RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
2402 SmallLISet &RecoloringCandidates,
2403 const SmallVirtRegSet &FixedRegisters) {
2404 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
2405
2406 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2407 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
2408 // If there is LastChanceRecoloringMaxInterference or more interferences,
2409 // chances are one would not be recolorable.
2410 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
Quentin Colombet567e30b2014-04-11 21:39:44 +00002411 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00002412 DEBUG(dbgs() << "Early abort: too many interferences.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002413 CutOffInfo |= CO_Interf;
Quentin Colombet87769712014-02-05 22:13:59 +00002414 return false;
2415 }
2416 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
2417 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
2418 // If Intf is done and sit on the same register class as VirtReg,
2419 // it would not be recolorable as it is in the same state as VirtReg.
Mikael Holmen07f1e2e2017-09-28 08:22:35 +00002420 // However, if VirtReg has tied defs and Intf doesn't, then
2421 // there is still a point in examining if it can be recolorable.
2422 if (((getStage(*Intf) == RS_Done &&
2423 MRI->getRegClass(Intf->reg) == CurRC) &&
2424 !(hasTiedDef(MRI, VirtReg.reg) && !hasTiedDef(MRI, Intf->reg))) ||
Quentin Colombet87769712014-02-05 22:13:59 +00002425 FixedRegisters.count(Intf->reg)) {
Mikael Holmen3bcc9f0c2017-09-27 11:27:50 +00002426 DEBUG(dbgs() << "Early abort: the interference is not recolorable.\n");
Quentin Colombet87769712014-02-05 22:13:59 +00002427 return false;
2428 }
2429 RecoloringCandidates.insert(Intf);
2430 }
2431 }
2432 return true;
2433}
2434
2435/// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2436/// its interferences.
2437/// Last chance recoloring chooses a color for \p VirtReg and recolors every
2438/// virtual register that was using it. The recoloring process may recursively
2439/// use the last chance recoloring. Therefore, when a virtual register has been
2440/// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2441/// be last-chance-recolored again during this recoloring "session".
2442/// E.g.,
2443/// Let
2444/// vA can use {R1, R2 }
2445/// vB can use { R2, R3}
2446/// vC can use {R1 }
2447/// Where vA, vB, and vC cannot be split anymore (they are reloads for
2448/// instance) and they all interfere.
2449///
2450/// vA is assigned R1
2451/// vB is assigned R2
2452/// vC tries to evict vA but vA is already done.
2453/// Regular register allocation fails.
2454///
2455/// Last chance recoloring kicks in:
2456/// vC does as if vA was evicted => vC uses R1.
2457/// vC is marked as fixed.
2458/// vA needs to find a color.
2459/// None are available.
2460/// vA cannot evict vC: vC is a fixed virtual register now.
2461/// vA does as if vB was evicted => vA uses R2.
2462/// vB needs to find a color.
2463/// R3 is available.
2464/// Recoloring => vC = R1, vA = R2, vB = R3
2465///
Alp Toker70b36992014-02-25 04:21:15 +00002466/// \p Order defines the preferred allocation order for \p VirtReg.
Quentin Colombet87769712014-02-05 22:13:59 +00002467/// \p NewRegs will contain any new virtual register that have been created
2468/// (split, spill) during the process and that must be assigned.
2469/// \p FixedRegisters contains all the virtual registers that cannot be
2470/// recolored.
2471/// \p Depth gives the current depth of the last chance recoloring.
2472/// \return a physical register that can be used for VirtReg or ~0u if none
2473/// exists.
2474unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2475 AllocationOrder &Order,
2476 SmallVectorImpl<unsigned> &NewVRegs,
2477 SmallVirtRegSet &FixedRegisters,
2478 unsigned Depth) {
2479 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2480 // Ranges must be Done.
Quentin Colombet0e3b5e02014-02-13 05:17:37 +00002481 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
Quentin Colombet87769712014-02-05 22:13:59 +00002482 "Last chance recoloring should really be last chance");
2483 // Set the max depth to LastChanceRecoloringMaxDepth.
2484 // We may want to reconsider that if we end up with a too large search space
2485 // for target with hundreds of registers.
2486 // Indeed, in that case we may want to cut the search space earlier.
Quentin Colombet567e30b2014-04-11 21:39:44 +00002487 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
Quentin Colombet87769712014-02-05 22:13:59 +00002488 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002489 CutOffInfo |= CO_Depth;
Quentin Colombet87769712014-02-05 22:13:59 +00002490 return ~0u;
2491 }
2492
2493 // Set of Live intervals that will need to be recolored.
2494 SmallLISet RecoloringCandidates;
2495 // Record the original mapping virtual register to physical register in case
2496 // the recoloring fails.
2497 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2498 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2499 // this recoloring "session".
2500 FixedRegisters.insert(VirtReg.reg);
Quentin Colombet318582f2016-09-16 22:00:50 +00002501 SmallVector<unsigned, 4> CurrentNewVRegs;
Quentin Colombet87769712014-02-05 22:13:59 +00002502
2503 Order.rewind();
2504 while (unsigned PhysReg = Order.next()) {
2505 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2506 << PrintReg(PhysReg, TRI) << '\n');
2507 RecoloringCandidates.clear();
2508 VirtRegToPhysReg.clear();
Quentin Colombet318582f2016-09-16 22:00:50 +00002509 CurrentNewVRegs.clear();
Quentin Colombet87769712014-02-05 22:13:59 +00002510
2511 // It is only possible to recolor virtual register interference.
2512 if (Matrix->checkInterference(VirtReg, PhysReg) >
2513 LiveRegMatrix::IK_VirtReg) {
Mikael Holmen3bcc9f0c2017-09-27 11:27:50 +00002514 DEBUG(dbgs() << "Some interferences are not with virtual registers.\n");
Quentin Colombet87769712014-02-05 22:13:59 +00002515
2516 continue;
2517 }
2518
2519 // Early give up on this PhysReg if it is obvious we cannot recolor all
2520 // the interferences.
2521 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2522 FixedRegisters)) {
Mikael Holmen3bcc9f0c2017-09-27 11:27:50 +00002523 DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
Quentin Colombet87769712014-02-05 22:13:59 +00002524 continue;
2525 }
2526
2527 // RecoloringCandidates contains all the virtual registers that interfer
2528 // with VirtReg on PhysReg (or one of its aliases).
2529 // Enqueue them for recoloring and perform the actual recoloring.
2530 PQueue RecoloringQueue;
2531 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2532 EndIt = RecoloringCandidates.end();
2533 It != EndIt; ++It) {
2534 unsigned ItVirtReg = (*It)->reg;
2535 enqueue(RecoloringQueue, *It);
2536 assert(VRM->hasPhys(ItVirtReg) &&
2537 "Interferences are supposed to be with allocated vairables");
2538
2539 // Record the current allocation.
2540 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2541 // unset the related struct.
2542 Matrix->unassign(**It);
2543 }
2544
2545 // Do as if VirtReg was assigned to PhysReg so that the underlying
2546 // recoloring has the right information about the interferes and
2547 // available colors.
2548 Matrix->assign(VirtReg, PhysReg);
2549
2550 // Save the current recoloring state.
2551 // If we cannot recolor all the interferences, we will have to start again
2552 // at this point for the next physical register.
2553 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
Quentin Colombet318582f2016-09-16 22:00:50 +00002554 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2555 FixedRegisters, Depth)) {
2556 // Push the queued vregs into the main queue.
2557 for (unsigned NewVReg : CurrentNewVRegs)
2558 NewVRegs.push_back(NewVReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002559 // Do not mess up with the global assignment process.
2560 // I.e., VirtReg must be unassigned.
2561 Matrix->unassign(VirtReg);
2562 return PhysReg;
2563 }
2564
2565 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2566 << PrintReg(PhysReg, TRI) << '\n');
2567
2568 // The recoloring attempt failed, undo the changes.
2569 FixedRegisters = SaveFixedRegisters;
2570 Matrix->unassign(VirtReg);
2571
Wei Mib5cf9e52016-11-08 18:19:36 +00002572 // For a newly created vreg which is also in RecoloringCandidates,
2573 // don't add it to NewVRegs because its physical register will be restored
2574 // below. Other vregs in CurrentNewVRegs are created by calling
2575 // selectOrSplit and should be added into NewVRegs.
Quentin Colombet318582f2016-09-16 22:00:50 +00002576 for (SmallVectorImpl<unsigned>::iterator Next = CurrentNewVRegs.begin(),
2577 End = CurrentNewVRegs.end();
2578 Next != End; ++Next) {
Wei Mib5cf9e52016-11-08 18:19:36 +00002579 if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
Quentin Colombet318582f2016-09-16 22:00:50 +00002580 continue;
2581 NewVRegs.push_back(*Next);
2582 }
2583
Quentin Colombet87769712014-02-05 22:13:59 +00002584 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2585 EndIt = RecoloringCandidates.end();
2586 It != EndIt; ++It) {
2587 unsigned ItVirtReg = (*It)->reg;
2588 if (VRM->hasPhys(ItVirtReg))
2589 Matrix->unassign(**It);
Matthias Braun953393a2015-07-14 17:38:17 +00002590 unsigned ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2591 Matrix->assign(**It, ItPhysReg);
Quentin Colombet87769712014-02-05 22:13:59 +00002592 }
2593 }
2594
2595 // Last chance recoloring did not worked either, give up.
2596 return ~0u;
2597}
2598
2599/// tryRecoloringCandidates - Try to assign a new color to every register
2600/// in \RecoloringQueue.
2601/// \p NewRegs will contain any new virtual register created during the
2602/// recoloring process.
2603/// \p FixedRegisters[in/out] contains all the registers that have been
2604/// recolored.
2605/// \return true if all virtual registers in RecoloringQueue were successfully
2606/// recolored, false otherwise.
2607bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2608 SmallVectorImpl<unsigned> &NewVRegs,
2609 SmallVirtRegSet &FixedRegisters,
2610 unsigned Depth) {
2611 while (!RecoloringQueue.empty()) {
2612 LiveInterval *LI = dequeue(RecoloringQueue);
2613 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2614 unsigned PhysReg;
2615 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
Quentin Colombet52ffa672016-10-13 19:27:48 +00002616 // When splitting happens, the live-range may actually be empty.
2617 // In that case, this is okay to continue the recoloring even
2618 // if we did not find an alternative color for it. Indeed,
2619 // there will not be anything to color for LI in the end.
2620 if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
Quentin Colombet87769712014-02-05 22:13:59 +00002621 return false;
Quentin Colombet52ffa672016-10-13 19:27:48 +00002622
2623 if (!PhysReg) {
2624 assert(LI->empty() && "Only empty live-range do not require a register");
2625 DEBUG(dbgs() << "Recoloring of " << *LI << " succeeded. Empty LI.\n");
2626 continue;
2627 }
Quentin Colombet87769712014-02-05 22:13:59 +00002628 DEBUG(dbgs() << "Recoloring of " << *LI
2629 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
Quentin Colombet52ffa672016-10-13 19:27:48 +00002630
Quentin Colombet87769712014-02-05 22:13:59 +00002631 Matrix->assign(*LI, PhysReg);
2632 FixedRegisters.insert(LI->reg);
2633 }
2634 return true;
2635}
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002636
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00002637//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002638// Main Entry Point
2639//===----------------------------------------------------------------------===//
2640
2641unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Mark Laceyf9ea8852013-08-14 23:50:04 +00002642 SmallVectorImpl<unsigned> &NewVRegs) {
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002643 CutOffInfo = CO_None;
2644 LLVMContext &Ctx = MF->getFunction()->getContext();
Quentin Colombet87769712014-02-05 22:13:59 +00002645 SmallVirtRegSet FixedRegisters;
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002646 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2647 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2648 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2649 if (CutOffEncountered == CO_Depth)
Quentin Colombet567e30b2014-04-11 21:39:44 +00002650 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2651 "reached. Use -fexhaustive-register-search to skip "
2652 "cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002653 else if (CutOffEncountered == CO_Interf)
2654 Ctx.emitError("register allocation failed: maximum interference for "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002655 "recoloring reached. Use -fexhaustive-register-search "
2656 "to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002657 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2658 Ctx.emitError("register allocation failed: maximum interference and "
Quentin Colombet567e30b2014-04-11 21:39:44 +00002659 "depth for recoloring reached. Use "
2660 "-fexhaustive-register-search to skip cutoffs");
Quentin Colombet96bd2a12014-04-04 02:05:21 +00002661 }
2662 return Reg;
Quentin Colombet87769712014-02-05 22:13:59 +00002663}
2664
Manman Ren9dee4492014-03-27 21:21:57 +00002665/// Using a CSR for the first time has a cost because it causes push|pop
2666/// to be added to prologue|epilogue. Splitting a cold section of the live
2667/// range can have lower cost than using the CSR for the first time;
2668/// Spilling a live range in the cold path can have lower cost than using
2669/// the CSR for the first time. Returns the physical register if we decide
2670/// to use the CSR; otherwise return 0.
2671unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2672 AllocationOrder &Order,
2673 unsigned PhysReg,
2674 unsigned &CostPerUseLimit,
2675 SmallVectorImpl<unsigned> &NewVRegs) {
Manman Ren9dee4492014-03-27 21:21:57 +00002676 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2677 // We choose spill over using the CSR for the first time if the spill cost
2678 // is lower than CSRCost.
2679 SA->analyze(&VirtReg);
2680 if (calcSpillCost() >= CSRCost)
2681 return PhysReg;
2682
2683 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2684 // we will not use a callee-saved register in tryEvict.
2685 CostPerUseLimit = 1;
2686 return 0;
2687 }
2688 if (getStage(VirtReg) < RS_Split) {
2689 // We choose pre-splitting over using the CSR for the first time if
2690 // the cost of splitting is lower than CSRCost.
2691 SA->analyze(&VirtReg);
2692 unsigned NumCands = 0;
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002693 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2694 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2695 NumCands, true /*IgnoreCSR*/);
Manman Ren9dee4492014-03-27 21:21:57 +00002696 if (BestCand == NoCand)
2697 // Use the CSR if we can't find a region split below CSRCost.
2698 return PhysReg;
2699
2700 // Perform the actual pre-splitting.
2701 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2702 return 0;
2703 }
2704 return PhysReg;
2705}
2706
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002707void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
2708 // Do not keep invalid information around.
2709 SetOfBrokenHints.remove(&LI);
2710}
2711
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00002712void RAGreedy::initializeCSRCost() {
2713 // We use the larger one out of the command-line option and the value report
2714 // by TRI.
2715 CSRCost = BlockFrequency(
2716 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2717 if (!CSRCost.getFrequency())
2718 return;
2719
2720 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2721 uint64_t ActualEntry = MBFI->getEntryFreq();
2722 if (!ActualEntry) {
2723 CSRCost = 0;
2724 return;
2725 }
2726 uint64_t FixedEntry = 1 << 14;
2727 if (ActualEntry < FixedEntry)
2728 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2729 else if (ActualEntry <= UINT32_MAX)
2730 // Invert the fraction and divide.
2731 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2732 else
2733 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2734 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2735}
2736
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002737/// \brief Collect the hint info for \p Reg.
2738/// The results are stored into \p Out.
2739/// \p Out is not cleared before being populated.
2740void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
2741 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2742 if (!Instr.isFullCopy())
2743 continue;
2744 // Look for the other end of the copy.
2745 unsigned OtherReg = Instr.getOperand(0).getReg();
2746 if (OtherReg == Reg) {
2747 OtherReg = Instr.getOperand(1).getReg();
2748 if (OtherReg == Reg)
2749 continue;
2750 }
2751 // Get the current assignment.
2752 unsigned OtherPhysReg = TargetRegisterInfo::isPhysicalRegister(OtherReg)
2753 ? OtherReg
2754 : VRM->getPhys(OtherReg);
2755 // Push the collected information.
2756 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2757 OtherPhysReg));
2758 }
2759}
2760
2761/// \brief Using the given \p List, compute the cost of the broken hints if
2762/// \p PhysReg was used.
2763/// \return The cost of \p List for \p PhysReg.
2764BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2765 unsigned PhysReg) {
2766 BlockFrequency Cost = 0;
2767 for (const HintInfo &Info : List) {
2768 if (Info.PhysReg != PhysReg)
2769 Cost += Info.Freq;
2770 }
2771 return Cost;
2772}
2773
2774/// \brief Using the register assigned to \p VirtReg, try to recolor
2775/// all the live ranges that are copy-related with \p VirtReg.
2776/// The recoloring is then propagated to all the live-ranges that have
2777/// been recolored and so on, until no more copies can be coalesced or
2778/// it is not profitable.
2779/// For a given live range, profitability is determined by the sum of the
2780/// frequencies of the non-identity copies it would introduce with the old
2781/// and new register.
2782void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
2783 // We have a broken hint, check if it is possible to fix it by
2784 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2785 // some register and PhysReg may be available for the other live-ranges.
2786 SmallSet<unsigned, 4> Visited;
2787 SmallVector<unsigned, 2> RecoloringCandidates;
2788 HintsInfo Info;
2789 unsigned Reg = VirtReg.reg;
2790 unsigned PhysReg = VRM->getPhys(Reg);
2791 // Start the recoloring algorithm from the input live-interval, then
2792 // it will propagate to the ones that are copy-related with it.
2793 Visited.insert(Reg);
2794 RecoloringCandidates.push_back(Reg);
2795
2796 DEBUG(dbgs() << "Trying to reconcile hints for: " << PrintReg(Reg, TRI) << '('
2797 << PrintReg(PhysReg, TRI) << ")\n");
2798
2799 do {
2800 Reg = RecoloringCandidates.pop_back_val();
2801
Hiroshi Inouea86c9202017-07-10 12:44:25 +00002802 // We cannot recolor physical register.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002803 if (TargetRegisterInfo::isPhysicalRegister(Reg))
2804 continue;
2805
2806 assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
2807
2808 // Get the live interval mapped with this virtual register to be able
2809 // to check for the interference with the new color.
2810 LiveInterval &LI = LIS->getInterval(Reg);
2811 unsigned CurrPhys = VRM->getPhys(Reg);
2812 // Check that the new color matches the register class constraints and
2813 // that it is free for this live range.
2814 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2815 Matrix->checkInterference(LI, PhysReg)))
2816 continue;
2817
2818 DEBUG(dbgs() << PrintReg(Reg, TRI) << '(' << PrintReg(CurrPhys, TRI)
2819 << ") is recolorable.\n");
2820
2821 // Gather the hint info.
2822 Info.clear();
2823 collectHintInfo(Reg, Info);
2824 // Check if recoloring the live-range will increase the cost of the
2825 // non-identity copies.
2826 if (CurrPhys != PhysReg) {
2827 DEBUG(dbgs() << "Checking profitability:\n");
2828 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2829 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2830 DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2831 << "\nNew Cost: " << NewCopiesCost.getFrequency() << '\n');
2832 if (OldCopiesCost < NewCopiesCost) {
2833 DEBUG(dbgs() << "=> Not profitable.\n");
2834 continue;
2835 }
2836 // At this point, the cost is either cheaper or equal. If it is
2837 // equal, we consider this is profitable because it may expose
2838 // more recoloring opportunities.
2839 DEBUG(dbgs() << "=> Profitable.\n");
2840 // Recolor the live-range.
2841 Matrix->unassign(LI);
2842 Matrix->assign(LI, PhysReg);
2843 }
2844 // Push all copy-related live-ranges to keep reconciling the broken
2845 // hints.
2846 for (const HintInfo &HI : Info) {
2847 if (Visited.insert(HI.Reg).second)
2848 RecoloringCandidates.push_back(HI.Reg);
2849 }
2850 } while (!RecoloringCandidates.empty());
2851}
2852
2853/// \brief Try to recolor broken hints.
2854/// Broken hints may be repaired by recoloring when an evicted variable
2855/// freed up a register for a larger live-range.
2856/// Consider the following example:
2857/// BB1:
2858/// a =
2859/// b =
2860/// BB2:
2861/// ...
2862/// = b
2863/// = a
2864/// Let us assume b gets split:
2865/// BB1:
2866/// a =
2867/// b =
2868/// BB2:
2869/// c = b
2870/// ...
2871/// d = c
2872/// = d
2873/// = a
2874/// Because of how the allocation work, b, c, and d may be assigned different
2875/// colors. Now, if a gets evicted later:
2876/// BB1:
2877/// a =
2878/// st a, SpillSlot
2879/// b =
2880/// BB2:
2881/// c = b
2882/// ...
2883/// d = c
2884/// = d
2885/// e = ld SpillSlot
2886/// = e
2887/// This is likely that we can assign the same register for b, c, and d,
2888/// getting rid of 2 copies.
2889void RAGreedy::tryHintsRecoloring() {
2890 for (LiveInterval *LI : SetOfBrokenHints) {
2891 assert(TargetRegisterInfo::isVirtualRegister(LI->reg) &&
2892 "Recoloring is possible only for virtual registers");
2893 // Some dead defs may be around (e.g., because of debug uses).
2894 // Ignore those.
2895 if (!VRM->hasPhys(LI->reg))
2896 continue;
2897 tryHintRecoloring(*LI);
2898 }
2899}
2900
Quentin Colombet87769712014-02-05 22:13:59 +00002901unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2902 SmallVectorImpl<unsigned> &NewVRegs,
2903 SmallVirtRegSet &FixedRegisters,
2904 unsigned Depth) {
Manman Ren78cf02a2014-03-25 00:16:25 +00002905 unsigned CostPerUseLimit = ~0u;
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002906 // First try assigning a free register.
Matthias Braun5d1f12d2015-07-15 22:16:00 +00002907 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
Manman Ren78cf02a2014-03-25 00:16:25 +00002908 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
Marina Yatsinaf9371d82017-10-22 17:59:38 +00002909 // If VirtReg got an assignment, the eviction info is no longre relevant.
2910 LastEvicted.clearEvicteeInfo(VirtReg.reg);
Manman Ren9dee4492014-03-27 21:21:57 +00002911 // When NewVRegs is not empty, we may have made decisions such as evicting
2912 // a virtual register, go with the earlier decisions and use the physical
2913 // register.
Matthias Braun953393a2015-07-14 17:38:17 +00002914 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
2915 NewVRegs.empty()) {
Manman Ren9dee4492014-03-27 21:21:57 +00002916 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2917 CostPerUseLimit, NewVRegs);
2918 if (CSRReg || !NewVRegs.empty())
2919 // Return now if we decide to use a CSR or create new vregs due to
2920 // pre-splitting.
2921 return CSRReg;
Manman Ren78cf02a2014-03-25 00:16:25 +00002922 } else
2923 return PhysReg;
2924 }
Andrew Trickccef0982010-12-09 18:15:21 +00002925
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002926 LiveRangeStage Stage = getStage(VirtReg);
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00002927 DEBUG(dbgs() << StageName[Stage]
2928 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
Jakob Stoklund Olesen25d57452011-05-25 23:58:36 +00002929
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002930 // Try to evict a less worthy live range, but only for ranges from the primary
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002931 // queue. The RS_Split ranges already failed to do this, and they should not
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002932 // get a second chance until they have been split.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002933 if (Stage != RS_Split)
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002934 if (unsigned PhysReg =
2935 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit)) {
2936 unsigned Hint = MRI->getSimpleHint(VirtReg.reg);
2937 // If VirtReg has a hint and that hint is broken record this
2938 // virtual register as a recoloring candidate for broken hint.
2939 // Indeed, since we evicted a variable in its neighborhood it is
2940 // likely we can at least partially recolor some of the
2941 // copy-related live-ranges.
2942 if (Hint && Hint != PhysReg)
2943 SetOfBrokenHints.insert(&VirtReg);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00002944 // If VirtReg eviction someone, the eviction info for it as an evictee is
2945 // no longre relevant.
2946 LastEvicted.clearEvicteeInfo(VirtReg.reg);
Jakob Stoklund Olesene9cc8e92011-06-01 18:45:02 +00002947 return PhysReg;
Quentin Colombeta799e2e2015-01-08 01:16:39 +00002948 }
Andrew Trickccef0982010-12-09 18:15:21 +00002949
Quentin Colombet63176862016-09-16 22:00:42 +00002950 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
Jakob Stoklund Olesen9fb04012011-01-19 22:11:48 +00002951
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002952 // The first time we see a live range, don't try to split or spill.
2953 // Wait until the second time, when all smaller ranges have been allocated.
2954 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002955 if (Stage < RS_Split) {
2956 setStage(VirtReg, RS_Split);
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +00002957 DEBUG(dbgs() << "wait for second round\n");
Mark Laceyf9ea8852013-08-14 23:50:04 +00002958 NewVRegs.push_back(VirtReg.reg);
Jakob Stoklund Olesene68a27e2011-02-24 23:21:36 +00002959 return 0;
2960 }
2961
Dylan McKayc328fe52016-10-11 01:04:36 +00002962 if (Stage < RS_Spill) {
2963 // Try splitting VirtReg or interferences.
2964 unsigned NewVRegSizeBefore = NewVRegs.size();
2965 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
Marina Yatsinaf9371d82017-10-22 17:59:38 +00002966 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) {
2967 // If VirtReg got split, the eviction info is no longre relevant.
2968 LastEvicted.clearEvicteeInfo(VirtReg.reg);
Dylan McKayc328fe52016-10-11 01:04:36 +00002969 return PhysReg;
Marina Yatsinaf9371d82017-10-22 17:59:38 +00002970 }
Dylan McKayc328fe52016-10-11 01:04:36 +00002971 }
2972
Jakob Stoklund Olesena5c88992011-05-06 21:58:30 +00002973 // If we couldn't allocate a register from spilling, there is probably some
Hiroshi Inoueff8453d2017-06-29 18:03:28 +00002974 // invalid inline assembly. The base class will report it.
Jakob Stoklund Olesen3ef8cf12011-07-25 15:25:41 +00002975 if (Stage >= RS_Done || !VirtReg.isSpillable())
Quentin Colombet87769712014-02-05 22:13:59 +00002976 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2977 Depth);
Jakob Stoklund Olesen5f9f0812011-03-01 21:10:07 +00002978
Jakob Stoklund Olesen0acb69d2010-12-22 22:01:30 +00002979 // Finally spill VirtReg itself.
Quentin Colombet11922942015-07-17 23:04:06 +00002980 if (EnableDeferredSpilling && getStage(VirtReg) < RS_Memory) {
2981 // TODO: This is experimental and in particular, we do not model
2982 // the live range splitting done by spilling correctly.
2983 // We would need a deep integration with the spiller to do the
2984 // right thing here. Anyway, that is still good for early testing.
2985 setStage(VirtReg, RS_Memory);
2986 DEBUG(dbgs() << "Do as if this register is in memory\n");
2987 NewVRegs.push_back(VirtReg.reg);
2988 } else {
Matthias Braun9f15a792016-11-18 19:43:18 +00002989 NamedRegionTimer T("spill", "Spiller", TimerGroupName,
2990 TimerGroupDescription, TimePassesIsEnabled);
Wei Mi9a16d652016-04-13 03:08:27 +00002991 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
Quentin Colombet11922942015-07-17 23:04:06 +00002992 spiller().spill(LRE);
2993 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002994
Quentin Colombet11922942015-07-17 23:04:06 +00002995 if (VerifyEnabled)
2996 MF->verify(this, "After spilling");
2997 }
Jakob Stoklund Olesen557a82c2011-03-16 22:56:08 +00002998
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00002999 // The live virtual register requesting allocation was spilled, so tell
3000 // the caller not to allocate anything during this round.
3001 return 0;
3002}
3003
Adam Nemeta9640662017-01-25 23:20:33 +00003004void RAGreedy::reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
3005 unsigned &FoldedReloads,
3006 unsigned &Spills,
3007 unsigned &FoldedSpills) {
3008 Reloads = 0;
3009 FoldedReloads = 0;
3010 Spills = 0;
3011 FoldedSpills = 0;
3012
3013 // Sum up the spill and reloads in subloops.
3014 for (MachineLoop *SubLoop : *L) {
3015 unsigned SubReloads;
3016 unsigned SubFoldedReloads;
3017 unsigned SubSpills;
3018 unsigned SubFoldedSpills;
3019
3020 reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
3021 SubSpills, SubFoldedSpills);
3022 Reloads += SubReloads;
3023 FoldedReloads += SubFoldedReloads;
3024 Spills += SubSpills;
3025 FoldedSpills += SubFoldedSpills;
3026 }
3027
3028 const MachineFrameInfo &MFI = MF->getFrameInfo();
3029 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
3030 int FI;
3031
3032 for (MachineBasicBlock *MBB : L->getBlocks())
3033 // Handle blocks that were not included in subloops.
3034 if (Loops->getLoopFor(MBB) == L)
3035 for (MachineInstr &MI : *MBB) {
3036 const MachineMemOperand *MMO;
3037
3038 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI))
3039 ++Reloads;
3040 else if (TII->hasLoadFromStackSlot(MI, MMO, FI) &&
3041 MFI.isSpillSlotObjectIndex(FI))
3042 ++FoldedReloads;
3043 else if (TII->isStoreToStackSlot(MI, FI) &&
3044 MFI.isSpillSlotObjectIndex(FI))
3045 ++Spills;
3046 else if (TII->hasStoreToStackSlot(MI, MMO, FI) &&
3047 MFI.isSpillSlotObjectIndex(FI))
3048 ++FoldedSpills;
3049 }
3050
3051 if (Reloads || FoldedReloads || Spills || FoldedSpills) {
3052 using namespace ore;
Eugene Zelenkofb69e662017-06-06 22:22:41 +00003053
Vivek Pandya95906582017-10-11 17:12:59 +00003054 ORE->emit([&]() {
3055 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReload",
3056 L->getStartLoc(), L->getHeader());
3057 if (Spills)
3058 R << NV("NumSpills", Spills) << " spills ";
3059 if (FoldedSpills)
3060 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
3061 if (Reloads)
3062 R << NV("NumReloads", Reloads) << " reloads ";
3063 if (FoldedReloads)
3064 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
3065 R << "generated in loop";
3066 return R;
3067 });
Adam Nemeta9640662017-01-25 23:20:33 +00003068 }
3069}
3070
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003071bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
3072 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
David Blaikiec8c29202012-08-22 17:18:53 +00003073 << "********** Function: " << mf.getName() << '\n');
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003074
3075 MF = &mf;
Eric Christopher60621802014-10-14 07:22:00 +00003076 TRI = MF->getSubtarget().getRegisterInfo();
3077 TII = MF->getSubtarget().getInstrInfo();
Quentin Colombet1fb3362a2014-01-02 22:47:22 +00003078 RCI.runOnMachineFunction(mf);
Quentin Colombet5caa6a22014-07-02 18:32:04 +00003079
3080 EnableLocalReassign = EnableLocalReassignment ||
Eric Christopher60621802014-10-14 07:22:00 +00003081 MF->getSubtarget().enableRALocalReassignment(
3082 MF->getTarget().getOptLevel());
Quentin Colombet5caa6a22014-07-02 18:32:04 +00003083
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003084 EnableAdvancedRASplitCost = ConsiderLocalIntervalCost ||
3085 MF->getSubtarget().enableAdvancedRASplitCost();
3086
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00003087 if (VerifyEnabled)
Jakob Stoklund Olesenbf4550e2010-12-18 00:06:56 +00003088 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesen2e98ee32010-12-17 23:16:35 +00003089
Jakob Stoklund Olesen2d2dec92012-06-20 22:52:29 +00003090 RegAllocBase::init(getAnalysis<VirtRegMap>(),
3091 getAnalysis<LiveIntervals>(),
3092 getAnalysis<LiveRegMatrix>());
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00003093 Indexes = &getAnalysis<SlotIndexes>();
Benjamin Kramere2a1d892013-06-17 19:00:36 +00003094 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
Jakob Stoklund Olesen1740e002010-12-17 23:16:32 +00003095 DomTree = &getAnalysis<MachineDominatorTree>();
Adam Nemeta9640662017-01-25 23:20:33 +00003096 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
Jakob Stoklund Olesenadecb5e2010-12-10 22:54:44 +00003097 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00003098 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00003099 Bundles = &getAnalysis<EdgeBundles>();
3100 SpillPlacer = &getAnalysis<SpillPlacement>();
Jakob Stoklund Olesenf8da0282011-05-06 18:00:02 +00003101 DebugVars = &getAnalysis<LiveDebugVariables>();
Wei Mic0223702016-07-08 21:08:09 +00003102 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Jakob Stoklund Olesen267f6c12011-01-18 21:13:27 +00003103
Duncan P. N. Exon Smitha5df8132014-04-08 19:18:56 +00003104 initializeCSRCost();
3105
Robert Lougher11a44b72015-08-10 11:59:44 +00003106 calculateSpillWeightsAndHints(*LIS, mf, VRM, *Loops, *MBFI);
Arnaud A. de Grandmaison760c1e02013-11-10 17:46:31 +00003107
Andrew Trick97064962013-07-25 07:26:26 +00003108 DEBUG(LIS->dump());
3109
Jakob Stoklund Olesenf1a60a62011-02-19 00:53:42 +00003110 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Wei Mic0223702016-07-08 21:08:09 +00003111 SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
Jakob Stoklund Olesen30a85632011-07-02 01:37:09 +00003112 ExtraRegInfo.clear();
3113 ExtraRegInfo.resize(MRI->getNumVirtRegs());
3114 NextCascade = 1;
Jakob Stoklund Olesen96eebf02012-06-20 22:52:26 +00003115 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
Jakob Stoklund Olesendab4b9a2011-07-26 23:41:46 +00003116 GlobalCand.resize(32); // This will grow as needed.
Quentin Colombeta799e2e2015-01-08 01:16:39 +00003117 SetOfBrokenHints.clear();
Marina Yatsinaf9371d82017-10-22 17:59:38 +00003118 LastEvicted.clear();
Jakob Stoklund Olesene7601e92010-12-15 23:46:13 +00003119
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003120 allocatePhysRegs();
Quentin Colombeta799e2e2015-01-08 01:16:39 +00003121 tryHintsRecoloring();
Wei Mi9a16d652016-04-13 03:08:27 +00003122 postOptimization();
Adam Nemeta9640662017-01-25 23:20:33 +00003123 reportNumberOfSplillsReloads();
Wei Mi9a16d652016-04-13 03:08:27 +00003124
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003125 releaseMemory();
Jakob Stoklund Olesenb8812a12010-12-08 03:26:16 +00003126 return true;
3127}