1 //===-- RegisterPressure.h - Dynamic Register Pressure -*- C++ -*-------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the RegisterPressure class which can be used to track
11 // MachineInstr level register pressure.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_REGISTERPRESSURE_H
16 #define LLVM_CODEGEN_REGISTERPRESSURE_H
18 #include "llvm/ADT/SparseSet.h"
19 #include "llvm/CodeGen/SlotIndexes.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
26 class RegisterClassInfo;
29 /// Base class for register pressure results.
30 struct RegisterPressure {
31 /// Map of max reg pressure indexed by pressure set ID, not class ID.
32 std::vector<unsigned> MaxSetPressure;
34 /// List of live in virtual registers or physical register units.
35 SmallVector<unsigned,8> LiveInRegs;
36 SmallVector<unsigned,8> LiveOutRegs;
38 void dump(const TargetRegisterInfo *TRI) const;
41 /// RegisterPressure computed within a region of instructions delimited by
42 /// TopIdx and BottomIdx. During pressure computation, the maximum pressure per
43 /// register pressure set is increased. Once pressure within a region is fully
44 /// computed, the live-in and live-out sets are recorded.
46 /// This is preferable to RegionPressure when LiveIntervals are available,
47 /// because delimiting regions by SlotIndex is more robust and convenient than
48 /// holding block iterators. The block contents can change without invalidating
49 /// the pressure result.
50 struct IntervalPressure : RegisterPressure {
51 /// Record the boundary of the region being tracked.
57 void openTop(SlotIndex NextTop);
59 void openBottom(SlotIndex PrevBottom);
62 /// RegisterPressure computed within a region of instructions delimited by
63 /// TopPos and BottomPos. This is a less precise version of IntervalPressure for
64 /// use when LiveIntervals are unavailable.
65 struct RegionPressure : RegisterPressure {
66 /// Record the boundary of the region being tracked.
67 MachineBasicBlock::const_iterator TopPos;
68 MachineBasicBlock::const_iterator BottomPos;
72 void openTop(MachineBasicBlock::const_iterator PrevTop);
74 void openBottom(MachineBasicBlock::const_iterator PrevBottom);
77 /// Capture a change in pressure for a single pressure set. UnitInc may be
78 /// expressed in terms of upward or downward pressure depending on the client
79 /// and will be dynamically adjusted for current liveness.
81 /// Pressure increments are tiny, typically 1-2 units, and this is only for
82 /// heuristics, so we don't check UnitInc overflow. Instead, we may have a
83 /// higher level assert that pressure is consistent within a region. We also
84 /// effectively ignore dead defs which don't affect heuristics much.
85 class PressureChange {
86 uint16_t PSetID; // ID+1. 0=Invalid.
89 PressureChange(): PSetID(0), UnitInc(0) {}
90 PressureChange(unsigned id): PSetID(id+1), UnitInc(0) {
91 assert(id < UINT16_MAX && "PSetID overflow.");
94 bool isValid() const { return PSetID > 0; }
96 unsigned getPSet() const {
97 assert(isValid() && "invalid PressureChange");
100 // If PSetID is invalid, return UINT16_MAX to give it lowest priority.
101 unsigned getPSetOrMax() const { return (PSetID - 1) & UINT16_MAX; }
103 int getUnitInc() const { return UnitInc; }
105 void setUnitInc(int Inc) { UnitInc = Inc; }
107 bool operator==(const PressureChange &RHS) const {
108 return PSetID == RHS.PSetID && UnitInc == RHS.UnitInc;
112 template <> struct isPodLike<PressureChange> {
113 static const bool value = true;
116 /// List of PressureChanges in order of increasing, unique PSetID.
118 /// Use a small fixed number, because we can fit more PressureChanges in an
119 /// empty SmallVector than ever need to be tracked per register class. If more
120 /// PSets are affected, then we only track the most constrained.
122 // The initial design was for MaxPSets=4, but that requires PSet partitions,
123 // which are not yet implemented. (PSet partitions are equivalent PSets given
124 // the register classes actually in use within the scheduling region.)
125 enum { MaxPSets = 16 };
127 PressureChange PressureChanges[MaxPSets];
129 typedef PressureChange* iterator;
130 iterator nonconst_begin() { return &PressureChanges[0]; }
131 iterator nonconst_end() { return &PressureChanges[MaxPSets]; }
134 typedef const PressureChange* const_iterator;
135 const_iterator begin() const { return &PressureChanges[0]; }
136 const_iterator end() const { return &PressureChanges[MaxPSets]; }
138 void addPressureChange(unsigned RegUnit, bool IsDec,
139 const MachineRegisterInfo *MRI);
141 LLVM_DUMP_METHOD void dump(const TargetRegisterInfo &TRI) const;
144 /// Array of PressureDiffs.
145 class PressureDiffs {
146 PressureDiff *PDiffArray;
150 PressureDiffs(): PDiffArray(nullptr), Size(0), Max(0) {}
151 ~PressureDiffs() { free(PDiffArray); }
153 void clear() { Size = 0; }
155 void init(unsigned N);
157 PressureDiff &operator[](unsigned Idx) {
158 assert(Idx < Size && "PressureDiff index out of bounds");
159 return PDiffArray[Idx];
161 const PressureDiff &operator[](unsigned Idx) const {
162 return const_cast<PressureDiffs*>(this)->operator[](Idx);
166 /// Store the effects of a change in pressure on things that MI scheduler cares
169 /// Excess records the value of the largest difference in register units beyond
170 /// the target's pressure limits across the affected pressure sets, where
171 /// largest is defined as the absolute value of the difference. Negative
172 /// ExcessUnits indicates a reduction in pressure that had already exceeded the
175 /// CriticalMax records the largest increase in the tracker's max pressure that
176 /// exceeds the critical limit for some pressure set determined by the client.
178 /// CurrentMax records the largest increase in the tracker's max pressure that
179 /// exceeds the current limit for some pressure set determined by the client.
180 struct RegPressureDelta {
181 PressureChange Excess;
182 PressureChange CriticalMax;
183 PressureChange CurrentMax;
185 RegPressureDelta() {}
187 bool operator==(const RegPressureDelta &RHS) const {
188 return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
189 && CurrentMax == RHS.CurrentMax;
191 bool operator!=(const RegPressureDelta &RHS) const {
192 return !operator==(RHS);
196 /// A set of live virtual registers and physical register units.
198 /// This is a wrapper around a SparseSet which deals with mapping register unit
199 /// and virtual register indexes to an index usable by the sparse set.
202 SparseSet<unsigned> Regs;
203 unsigned NumRegUnits;
205 unsigned getSparseIndexFromReg(unsigned Reg) const {
206 if (TargetRegisterInfo::isVirtualRegister(Reg))
207 return TargetRegisterInfo::virtReg2Index(Reg) + NumRegUnits;
208 assert(Reg < NumRegUnits);
211 unsigned getRegFromSparseIndex(unsigned SparseIndex) const {
212 if (SparseIndex >= NumRegUnits)
213 return TargetRegisterInfo::index2VirtReg(SparseIndex-NumRegUnits);
219 void init(const MachineRegisterInfo &MRI);
221 bool contains(unsigned Reg) const {
222 unsigned SparseIndex = getSparseIndexFromReg(Reg);
223 return Regs.count(SparseIndex);
226 bool insert(unsigned Reg) {
227 unsigned SparseIndex = getSparseIndexFromReg(Reg);
228 return Regs.insert(SparseIndex).second;
231 bool erase(unsigned Reg) {
232 unsigned SparseIndex = getSparseIndexFromReg(Reg);
233 return Regs.erase(SparseIndex);
236 size_t size() const {
240 template<typename ContainerT>
241 void appendTo(ContainerT &To) const {
242 for (unsigned I : Regs) {
243 unsigned Reg = getRegFromSparseIndex(I);
249 /// Track the current register pressure at some position in the instruction
250 /// stream, and remember the high water mark within the region traversed. This
251 /// does not automatically consider live-through ranges. The client may
252 /// independently adjust for global liveness.
254 /// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
255 /// be tracked across a larger region by storing a RegisterPressure result at
256 /// each block boundary and explicitly adjusting pressure to account for block
257 /// live-in and live-out register sets.
259 /// RegPressureTracker holds a reference to a RegisterPressure result that it
260 /// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
261 /// is invalid until it reaches the end of the block or closeRegion() is
262 /// explicitly called. Similarly, P.TopIdx is invalid during upward
263 /// tracking. Changing direction has the side effect of closing region, and
264 /// traversing past TopIdx or BottomIdx reopens it.
265 class RegPressureTracker {
266 const MachineFunction *MF;
267 const TargetRegisterInfo *TRI;
268 const RegisterClassInfo *RCI;
269 const MachineRegisterInfo *MRI;
270 const LiveIntervals *LIS;
272 /// We currently only allow pressure tracking within a block.
273 const MachineBasicBlock *MBB;
275 /// Track the max pressure within the region traversed so far.
278 /// Run in two modes dependending on whether constructed with IntervalPressure
279 /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
280 bool RequireIntervals;
282 /// True if UntiedDefs will be populated.
283 bool TrackUntiedDefs;
285 /// Register pressure corresponds to liveness before this instruction
286 /// iterator. It may point to the end of the block or a DebugValue rather than
288 MachineBasicBlock::const_iterator CurrPos;
290 /// Pressure map indexed by pressure set ID, not class ID.
291 std::vector<unsigned> CurrSetPressure;
293 /// Set of live registers.
296 /// Set of vreg defs that start a live range.
297 SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
298 /// Live-through pressure.
299 std::vector<unsigned> LiveThruPressure;
302 RegPressureTracker(IntervalPressure &rp) :
303 MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
304 RequireIntervals(true), TrackUntiedDefs(false) {}
306 RegPressureTracker(RegionPressure &rp) :
307 MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
308 RequireIntervals(false), TrackUntiedDefs(false) {}
312 void init(const MachineFunction *mf, const RegisterClassInfo *rci,
313 const LiveIntervals *lis, const MachineBasicBlock *mbb,
314 MachineBasicBlock::const_iterator pos,
315 bool ShouldTrackUntiedDefs = false);
317 /// Force liveness of virtual registers or physical register
318 /// units. Particularly useful to initialize the livein/out state of the
319 /// tracker before the first call to advance/recede.
320 void addLiveRegs(ArrayRef<unsigned> Regs);
322 /// Get the MI position corresponding to this register pressure.
323 MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
325 // Reset the MI position corresponding to the register pressure. This allows
326 // schedulers to move instructions above the RegPressureTracker's
327 // CurrPos. Since the pressure is computed before CurrPos, the iterator
328 // position changes while pressure does not.
329 void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
331 /// \brief Get the SlotIndex for the first nondebug instruction including or
332 /// after the current position.
333 SlotIndex getCurrSlot() const;
335 /// Recede across the previous instruction.
336 bool recede(SmallVectorImpl<unsigned> *LiveUses = nullptr,
337 PressureDiff *PDiff = nullptr);
339 /// Advance across the current instruction.
342 /// Finalize the region boundaries and recored live ins and live outs.
345 /// Initialize the LiveThru pressure set based on the untied defs found in
347 void initLiveThru(const RegPressureTracker &RPTracker);
349 /// Copy an existing live thru pressure result.
350 void initLiveThru(ArrayRef<unsigned> PressureSet) {
351 LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
354 ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
356 /// Get the resulting register pressure over the traversed region.
357 /// This result is complete if either advance() or recede() has returned true,
358 /// or if closeRegion() was explicitly invoked.
359 RegisterPressure &getPressure() { return P; }
360 const RegisterPressure &getPressure() const { return P; }
362 /// Get the register set pressure at the current position, which may be less
363 /// than the pressure across the traversed region.
364 const std::vector<unsigned> &getRegSetPressureAtPos() const {
365 return CurrSetPressure;
368 void discoverLiveOut(unsigned Reg);
369 void discoverLiveIn(unsigned Reg);
371 bool isTopClosed() const;
372 bool isBottomClosed() const;
377 /// Consider the pressure increase caused by traversing this instruction
378 /// bottom-up. Find the pressure set with the most change beyond its pressure
379 /// limit based on the tracker's current pressure, and record the number of
380 /// excess register units of that pressure set introduced by this instruction.
381 void getMaxUpwardPressureDelta(const MachineInstr *MI,
383 RegPressureDelta &Delta,
384 ArrayRef<PressureChange> CriticalPSets,
385 ArrayRef<unsigned> MaxPressureLimit);
387 void getUpwardPressureDelta(const MachineInstr *MI,
388 /*const*/ PressureDiff &PDiff,
389 RegPressureDelta &Delta,
390 ArrayRef<PressureChange> CriticalPSets,
391 ArrayRef<unsigned> MaxPressureLimit) const;
393 /// Consider the pressure increase caused by traversing this instruction
394 /// top-down. Find the pressure set with the most change beyond its pressure
395 /// limit based on the tracker's current pressure, and record the number of
396 /// excess register units of that pressure set introduced by this instruction.
397 void getMaxDownwardPressureDelta(const MachineInstr *MI,
398 RegPressureDelta &Delta,
399 ArrayRef<PressureChange> CriticalPSets,
400 ArrayRef<unsigned> MaxPressureLimit);
402 /// Find the pressure set with the most change beyond its pressure limit after
403 /// traversing this instruction either upward or downward depending on the
404 /// closed end of the current region.
405 void getMaxPressureDelta(const MachineInstr *MI,
406 RegPressureDelta &Delta,
407 ArrayRef<PressureChange> CriticalPSets,
408 ArrayRef<unsigned> MaxPressureLimit) {
410 return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
413 assert(isBottomClosed() && "Uninitialized pressure tracker");
414 return getMaxUpwardPressureDelta(MI, nullptr, Delta, CriticalPSets,
418 /// Get the pressure of each PSet after traversing this instruction bottom-up.
419 void getUpwardPressure(const MachineInstr *MI,
420 std::vector<unsigned> &PressureResult,
421 std::vector<unsigned> &MaxPressureResult);
423 /// Get the pressure of each PSet after traversing this instruction top-down.
424 void getDownwardPressure(const MachineInstr *MI,
425 std::vector<unsigned> &PressureResult,
426 std::vector<unsigned> &MaxPressureResult);
428 void getPressureAfterInst(const MachineInstr *MI,
429 std::vector<unsigned> &PressureResult,
430 std::vector<unsigned> &MaxPressureResult) {
432 return getUpwardPressure(MI, PressureResult, MaxPressureResult);
434 assert(isBottomClosed() && "Uninitialized pressure tracker");
435 return getDownwardPressure(MI, PressureResult, MaxPressureResult);
438 bool hasUntiedDef(unsigned VirtReg) const {
439 return UntiedDefs.count(VirtReg);
445 const LiveRange *getLiveRange(unsigned Reg) const;
447 void increaseRegPressure(ArrayRef<unsigned> Regs);
448 void decreaseRegPressure(ArrayRef<unsigned> Regs);
450 void bumpUpwardPressure(const MachineInstr *MI);
451 void bumpDownwardPressure(const MachineInstr *MI);
454 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
455 const TargetRegisterInfo *TRI);
456 } // end namespace llvm