LLVM 24.0.0git
RegAllocGreedy.h
Go to the documentation of this file.
1//==- RegAllocGreedy.h ------- greedy register allocator ----------*-C++-*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8// This file defines the RAGreedy function pass for register allocation in
9// optimized builds.
10//===----------------------------------------------------------------------===//
11
12#ifndef LLVM_CODEGEN_REGALLOCGREEDY_H_
13#define LLVM_CODEGEN_REGALLOCGREEDY_H_
14
15#include "InterferenceCache.h"
16#include "RegAllocBase.h"
17#include "SplitKit.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/IndexedMap.h"
21#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/StringRef.h"
36#include <cstdint>
37#include <memory>
38#include <queue>
39#include <utility>
40
41namespace llvm {
42class AllocationOrder;
43class EdgeBundles;
44class LiveIntervals;
45class LiveRegMatrix;
49class MachineLoop;
50class MachineLoopInfo;
53class SlotIndexes;
54class TargetInstrInfo;
55class VirtRegMap;
56
59public:
60 struct RequiredAnalyses;
61
62 // Interface to eviction advisers
63 /// Track allocation stage and eviction loop prevention during allocation.
64 class ExtraRegInfo final {
65 // RegInfo - Keep additional information about each live range.
66 struct RegInfo {
67 LiveRangeStage Stage = RS_New;
68
69 // Cascade - Eviction loop prevention. See
70 // canEvictInterferenceBasedOnCost().
71 unsigned Cascade = 0;
72
73 RegInfo() = default;
74 };
75
77 unsigned NextCascade = 1;
78
79 public:
81 ExtraRegInfo(const ExtraRegInfo &) = delete;
82
83 LiveRangeStage getStage(Register Reg) const { return Info[Reg].Stage; }
84
85 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
86 return getStage(VirtReg.reg());
87 }
88
90 Info.grow(Reg.id());
91 Info[Reg].Stage = Stage;
92 }
93
94 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
95 setStage(VirtReg.reg(), Stage);
96 }
97
98 /// Return the current stage of the register, if present, otherwise
99 /// initialize it and return that.
101 Info.grow(Reg.id());
102 return getStage(Reg);
103 }
104
105 unsigned getCascade(Register Reg) const { return Info[Reg].Cascade; }
106
107 void setCascade(Register Reg, unsigned Cascade) {
108 Info.grow(Reg.id());
109 Info[Reg].Cascade = Cascade;
110 }
111
113 unsigned Cascade = getCascade(Reg);
114 if (!Cascade) {
115 Cascade = NextCascade++;
116 setCascade(Reg, Cascade);
117 }
118 return Cascade;
119 }
120
122 unsigned Cascade = getCascade(Reg);
123 if (!Cascade)
124 Cascade = NextCascade;
125 return Cascade;
126 }
127
128 template <typename Iterator>
129 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
130 for (; Begin != End; ++Begin) {
131 Register Reg = *Begin;
132 Info.grow(Reg.id());
133 if (Info[Reg].Stage == RS_New)
134 Info[Reg].Stage = NewStage;
135 }
136 }
137 void LRE_DidCloneVirtReg(Register New, Register Old);
138 };
139
141 LiveIntervals *getLiveIntervals() const { return LIS; }
142 VirtRegMap *getVirtRegMap() const { return VRM; }
144 const ExtraRegInfo &getExtraInfo() const { return *ExtraInfo; }
145 size_t getQueueSize() const { return Queue.size(); }
146 // end (interface to eviction advisers)
147
148 // Interface to priority advisers
150 return RegClassPriorityTrumpsGlobalness;
151 }
152 bool getReverseLocalAssignment() const { return ReverseLocalAssignment; }
153 // end (interface to priority advisers)
154
155private:
156 // Convenient shortcuts.
157 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
159
160 // We need to track all tentative recolorings so we can roll back any
161 // successful and unsuccessful recoloring attempts.
162 using RecoloringStack =
164
165 // context
166 MachineFunction *MF = nullptr;
167
168 // Shortcuts to some useful interface.
169 const TargetInstrInfo *TII = nullptr;
170
171 // analyses
172 SlotIndexes *Indexes = nullptr;
173 MachineBlockFrequencyInfo *MBFI = nullptr;
174 MachineDominatorTree *DomTree = nullptr;
175 MachineLoopInfo *Loops = nullptr;
177 EdgeBundles *Bundles = nullptr;
178 SpillPlacement *SpillPlacer = nullptr;
179 LiveDebugVariables *DebugVars = nullptr;
180 LiveStacks *LSS = nullptr; // Used by InlineSpiller
181 // Proxy for the advisors
182 RegAllocEvictionAdvisorProvider *EvictProvider = nullptr;
183 RegAllocPriorityAdvisorProvider *PriorityProvider = nullptr;
184
185 // state
186 std::unique_ptr<Spiller> SpillerInstance;
187 PQueue Queue;
188 std::unique_ptr<VirtRegAuxInfo> VRAI;
189 std::optional<ExtraRegInfo> ExtraInfo;
190 std::unique_ptr<RegAllocEvictionAdvisor> EvictAdvisor;
191
192 std::unique_ptr<RegAllocPriorityAdvisor> PriorityAdvisor;
193
194 // Enum CutOffStage to keep a track whether the register allocation failed
195 // because of the cutoffs encountered in last chance recoloring.
196 // Note: This is used as bitmask. New value should be next power of 2.
197 enum CutOffStage {
198 // No cutoffs encountered
199 CO_None = 0,
200
201 // lcr-max-depth cutoff encountered
202 CO_Depth = 1,
203
204 // lcr-max-interf cutoff encountered
205 CO_Interf = 2
206 };
207
208 uint8_t CutOffInfo = CutOffStage::CO_None;
209
210#ifndef NDEBUG
211 static const char *const StageName[];
212#endif
213
214 // splitting state.
215 std::unique_ptr<SplitAnalysis> SA;
216 std::unique_ptr<SplitEditor> SE;
217
218 /// Cached per-block interference maps
219 InterferenceCache IntfCache;
220
221 /// All basic blocks where the current register has uses.
222 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
223
224 /// Global live range splitting candidate info.
225 struct GlobalSplitCandidate {
226 // Register intended for assignment, or 0.
227 MCRegister PhysReg;
228
229 // SplitKit interval index for this candidate.
230 unsigned IntvIdx;
231
232 // Interference for PhysReg.
233 InterferenceCache::Cursor Intf;
234
235 // Bundles where this candidate should be live.
236 BitVector LiveBundles;
237 SmallVector<unsigned, 8> ActiveBlocks;
238
239 void reset(InterferenceCache &Cache, MCRegister Reg) {
240 PhysReg = Reg;
241 IntvIdx = 0;
242 Intf.setPhysReg(Cache, Reg);
243 LiveBundles.clear();
244 ActiveBlocks.clear();
245 }
246
247 // Set B[I] = C for every live bundle where B[I] was NoCand.
248 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
249 unsigned Count = 0;
250 for (unsigned I : LiveBundles.set_bits())
251 if (B[I] == NoCand) {
252 B[I] = C;
253 Count++;
254 }
255 return Count;
256 }
257 };
258
259 /// Candidate info for each PhysReg in AllocationOrder.
260 /// This vector never shrinks, but grows to the size of the largest register
261 /// class.
262 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
263
264 enum : unsigned { NoCand = ~0u };
265
266 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
267 /// NoCand which indicates the stack interval.
268 SmallVector<unsigned, 32> BundleCand;
269
270 /// Callee-save register cost, calculated once per machine function.
271 BlockFrequency CSRCost;
272
273 /// Set of broken hints that may be reconciled later because of eviction.
274 SmallSetVector<const LiveInterval *, 8> SetOfBrokenHints;
275
276 /// The register cost values. This list will be recreated for each Machine
277 /// Function
278 ArrayRef<uint8_t> RegCosts;
279
280 /// Flags for the live range priority calculation, determined once per
281 /// machine function.
282 bool RegClassPriorityTrumpsGlobalness = false;
283
284 bool ReverseLocalAssignment = false;
285
286public:
287 RAGreedy(RequiredAnalyses &Analyses, const RegAllocFilterFunc F = nullptr);
288
289 Spiller &spiller() override { return *SpillerInstance; }
290 void enqueueImpl(const LiveInterval *LI) override;
291 const LiveInterval *dequeue() override;
292 MCRegister selectOrSplit(const LiveInterval &,
293 SmallVectorImpl<Register> &) override;
294 void aboutToRemoveInterval(const LiveInterval &) override;
295
296 /// Perform register allocation.
297 bool run(MachineFunction &mf);
298
299 void releaseMemory();
300
301private:
302 MCRegister selectOrSplitImpl(const LiveInterval &,
304 RecoloringStack &, unsigned = 0);
305
306 bool LRE_CanEraseVirtReg(Register) override;
307 void LRE_WillShrinkVirtReg(Register) override;
308 void LRE_DidCloneVirtReg(Register, Register) override;
309 void enqueue(PQueue &CurQueue, const LiveInterval *LI);
310 const LiveInterval *dequeue(PQueue &CurQueue);
311
312 bool hasVirtRegAlloc();
313 BlockFrequency calcBlockSplitCost();
314 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency &,
315 BlockFrequency MaxCost);
316 bool addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
317 bool growRegion(GlobalSplitCandidate &Cand);
318 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate &,
319 const AllocationOrder &Order);
320 bool calcCompactRegion(GlobalSplitCandidate &);
321 void splitAroundRegion(LiveRangeEdit &, ArrayRef<unsigned>);
322 void calcGapWeights(MCRegister, SmallVectorImpl<float> &);
323 void evictInterference(const LiveInterval &, MCRegister,
325 bool mayRecolorAllInterferences(MCRegister PhysReg,
326 const LiveInterval &VirtReg,
327 SmallLISet &RecoloringCandidates,
328 const SmallVirtRegSet &FixedRegisters);
329
330 MCRegister tryAssign(const LiveInterval &, AllocationOrder &,
332 MCRegister tryEvict(const LiveInterval &, AllocationOrder &,
334 const SmallVirtRegSet &);
335 MCRegister tryRegionSplit(const LiveInterval &, AllocationOrder &,
337 /// Calculate cost of region splitting around the specified register.
338 unsigned calculateRegionSplitCostAroundReg(MCRegister PhysReg,
339 AllocationOrder &Order,
340 BlockFrequency &BestCost,
341 unsigned &NumCands,
342 unsigned &BestCand);
343 /// Calculate cost of region splitting.
344 unsigned calculateRegionSplitCost(const LiveInterval &VirtReg,
345 AllocationOrder &Order,
346 BlockFrequency &BestCost,
347 unsigned &NumCands, bool IgnoreCSR);
348 /// Perform region splitting.
349 MCRegister doRegionSplit(const LiveInterval &VirtReg, unsigned BestCand,
350 bool HasCompact,
351 SmallVectorImpl<Register> &NewVRegs);
352 /// Try to split VirtReg around physical Hint register.
353 bool trySplitAroundHintReg(MCRegister Hint, const LiveInterval &VirtReg,
355 AllocationOrder &Order);
356 /// Check other options before using a callee-saved register for the first
357 /// time.
358 MCRegister tryAssignCSRFirstTime(const LiveInterval &VirtReg,
359 AllocationOrder &Order, MCRegister PhysReg,
360 uint8_t &CostPerUseLimit,
361 SmallVectorImpl<Register> &NewVRegs);
362 /// Return the rematerialization cost, or BlockFrequency::max() if
363 /// rematerialization is not possible.
364 BlockFrequency calcRematCost(const LiveInterval &VirtReg,
365 AllocationOrder &Order) const;
366 BlockFrequency calcSpillCost(const LiveInterval &LI);
367 void initializeCSRCost();
368 MCRegister tryBlockSplit(const LiveInterval &, AllocationOrder &,
370 MCRegister tryInstructionSplit(const LiveInterval &, AllocationOrder &,
372 MCRegister tryLocalSplit(const LiveInterval &, AllocationOrder &,
374 MCRegister trySplit(const LiveInterval &, AllocationOrder &,
376 MCRegister tryLastChanceRecoloring(const LiveInterval &, AllocationOrder &,
378 SmallVirtRegSet &, RecoloringStack &,
379 unsigned);
380 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<Register> &,
381 SmallVirtRegSet &, RecoloringStack &, unsigned);
382 void tryHintRecoloring(const LiveInterval &, DenseSet<Register> &);
383 void tryHintsRecoloring();
384
385 /// Model the information carried by one end of a copy.
386 struct HintInfo {
387 /// The block containing the copy.
388 const MachineBasicBlock *MBB;
389 /// The virtual register or physical register.
391 /// Its currently assigned register.
392 /// In case of a physical register Reg == PhysReg.
393 MCRegister PhysReg;
394
395 HintInfo(const MachineBasicBlock *MBB, Register Reg, MCRegister PhysReg)
396 : MBB(MBB), Reg(Reg), PhysReg(PhysReg) {}
397 };
398 using HintsInfo = SmallVector<HintInfo, 4>;
399
400 BlockFrequency getBrokenHintFreq(const HintsInfo &, MCRegister);
401 void collectHintInfo(Register, HintsInfo &);
402
403 /// Greedy RA statistic to remark.
404 struct RAGreedyStats {
405 unsigned Reloads = 0;
406 unsigned FoldedReloads = 0;
407 unsigned ZeroCostFoldedReloads = 0;
408 unsigned Spills = 0;
409 unsigned FoldedSpills = 0;
410 unsigned Copies = 0;
411 float ReloadsCost = 0.0f;
412 float FoldedReloadsCost = 0.0f;
413 float SpillsCost = 0.0f;
414 float FoldedSpillsCost = 0.0f;
415 float CopiesCost = 0.0f;
416
417 bool isEmpty() {
418 return !(Reloads || FoldedReloads || Spills || FoldedSpills ||
419 ZeroCostFoldedReloads || Copies);
420 }
421
422 void add(const RAGreedyStats &other) {
423 Reloads += other.Reloads;
424 FoldedReloads += other.FoldedReloads;
425 ZeroCostFoldedReloads += other.ZeroCostFoldedReloads;
426 Spills += other.Spills;
427 FoldedSpills += other.FoldedSpills;
428 Copies += other.Copies;
429 ReloadsCost += other.ReloadsCost;
430 FoldedReloadsCost += other.FoldedReloadsCost;
431 SpillsCost += other.SpillsCost;
432 FoldedSpillsCost += other.FoldedSpillsCost;
433 CopiesCost += other.CopiesCost;
434 }
435
436 void report(MachineOptimizationRemarkMissed &R);
437 };
438
439 /// Compute statistic for a basic block.
440 RAGreedyStats computeStats(MachineBasicBlock &MBB);
441
442 /// Compute and report statistic through a remark.
443 RAGreedyStats reportStats(MachineLoop *L);
444
445 /// Report the statistic for each loop.
446 void reportStats();
447};
448} // namespace llvm
449#endif // #ifndef LLVM_CODEGEN_REGALLOCGREEDY_H_
MachineBasicBlock & MBB
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_LIBRARY_VISIBILITY
Definition Compiler.h:137
const HexagonInstrInfo * TII
Hexagon Hardware Loops
This file implements an indexed map.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
SI Lower i1 Copies
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Cursor - The primary query interface for the block interference cache.
LiveInterval - This class represents the liveness of a register, or stack slot.
Register reg() const
Callback methods for LiveRangeEdit owners.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
Diagnostic information for missed-optimization remarks.
Track allocation stage and eviction loop prevention during allocation.
LiveRangeStage getStage(Register Reg) const
void setCascade(Register Reg, unsigned Cascade)
unsigned getOrAssignNewCascade(Register Reg)
LiveRangeStage getStage(const LiveInterval &VirtReg) const
ExtraRegInfo(const ExtraRegInfo &)=delete
void setStage(Register Reg, LiveRangeStage Stage)
void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage)
void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage)
unsigned getCascade(Register Reg) const
unsigned getCascadeOrCurrentNext(Register Reg) const
LiveRangeStage getOrInitStage(Register Reg)
Return the current stage of the register, if present, otherwise initialize it and return that.
const ExtraRegInfo & getExtraInfo() const
Spiller & spiller() override
VirtRegMap * getVirtRegMap() const
RAGreedy(RequiredAnalyses &Analyses, const RegAllocFilterFunc F=nullptr)
LiveIntervals * getLiveIntervals() const
const RegisterClassInfo & getRegClassInfo() const
bool getReverseLocalAssignment() const
size_t getQueueSize() const
LiveRegMatrix * getInterferenceMatrix() const
bool getRegClassPriorityTrumpsGlobalness() const
RegAllocBase(const RegAllocFilterFunc F=nullptr)
LiveIntervals * LIS
LiveRegMatrix * Matrix
VirtRegMap * VRM
RegisterClassInfo * RegClassInfo
Common provider for legacy and new pass managers.
Common provider for getting the priority advisor and logging rewards.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
SlotIndexes pass.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Spiller interface.
Definition Spiller.h:33
TargetInstrInfo - Interface to description of machine instruction set.
This is an optimization pass for GlobalISel generic memory operations.
SmallSet< Register, 16 > SmallVirtRegSet
@ RS_New
Newly created live range that has never been queued.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320