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 /// \brief A set of live virtual registers and physical register units.
198 /// Virtual and physical register numbers require separate sparse sets, but most
199 /// of the RegisterPressureTracker handles them uniformly.
201 SparseSet<unsigned> PhysRegs;
202 SparseSet<unsigned, VirtReg2IndexFunctor> VirtRegs;
204 bool contains(unsigned Reg) const {
205 if (TargetRegisterInfo::isVirtualRegister(Reg))
206 return VirtRegs.count(Reg);
207 return PhysRegs.count(Reg);
210 bool insert(unsigned Reg) {
211 if (TargetRegisterInfo::isVirtualRegister(Reg))
212 return VirtRegs.insert(Reg).second;
213 return PhysRegs.insert(Reg).second;
216 bool erase(unsigned Reg) {
217 if (TargetRegisterInfo::isVirtualRegister(Reg))
218 return VirtRegs.erase(Reg);
219 return PhysRegs.erase(Reg);
223 /// Track the current register pressure at some position in the instruction
224 /// stream, and remember the high water mark within the region traversed. This
225 /// does not automatically consider live-through ranges. The client may
226 /// independently adjust for global liveness.
228 /// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
229 /// be tracked across a larger region by storing a RegisterPressure result at
230 /// each block boundary and explicitly adjusting pressure to account for block
231 /// live-in and live-out register sets.
233 /// RegPressureTracker holds a reference to a RegisterPressure result that it
234 /// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
235 /// is invalid until it reaches the end of the block or closeRegion() is
236 /// explicitly called. Similarly, P.TopIdx is invalid during upward
237 /// tracking. Changing direction has the side effect of closing region, and
238 /// traversing past TopIdx or BottomIdx reopens it.
239 class RegPressureTracker {
240 const MachineFunction *MF;
241 const TargetRegisterInfo *TRI;
242 const RegisterClassInfo *RCI;
243 const MachineRegisterInfo *MRI;
244 const LiveIntervals *LIS;
246 /// We currently only allow pressure tracking within a block.
247 const MachineBasicBlock *MBB;
249 /// Track the max pressure within the region traversed so far.
252 /// Run in two modes dependending on whether constructed with IntervalPressure
253 /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
254 bool RequireIntervals;
256 /// True if UntiedDefs will be populated.
257 bool TrackUntiedDefs;
259 /// Register pressure corresponds to liveness before this instruction
260 /// iterator. It may point to the end of the block or a DebugValue rather than
262 MachineBasicBlock::const_iterator CurrPos;
264 /// Pressure map indexed by pressure set ID, not class ID.
265 std::vector<unsigned> CurrSetPressure;
267 /// Set of live registers.
270 /// Set of vreg defs that start a live range.
271 SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
272 /// Live-through pressure.
273 std::vector<unsigned> LiveThruPressure;
276 RegPressureTracker(IntervalPressure &rp) :
277 MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
278 RequireIntervals(true), TrackUntiedDefs(false) {}
280 RegPressureTracker(RegionPressure &rp) :
281 MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
282 RequireIntervals(false), TrackUntiedDefs(false) {}
286 void init(const MachineFunction *mf, const RegisterClassInfo *rci,
287 const LiveIntervals *lis, const MachineBasicBlock *mbb,
288 MachineBasicBlock::const_iterator pos,
289 bool ShouldTrackUntiedDefs = false);
291 /// Force liveness of virtual registers or physical register
292 /// units. Particularly useful to initialize the livein/out state of the
293 /// tracker before the first call to advance/recede.
294 void addLiveRegs(ArrayRef<unsigned> Regs);
296 /// Get the MI position corresponding to this register pressure.
297 MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
299 // Reset the MI position corresponding to the register pressure. This allows
300 // schedulers to move instructions above the RegPressureTracker's
301 // CurrPos. Since the pressure is computed before CurrPos, the iterator
302 // position changes while pressure does not.
303 void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
305 /// \brief Get the SlotIndex for the first nondebug instruction including or
306 /// after the current position.
307 SlotIndex getCurrSlot() const;
309 /// Recede across the previous instruction.
310 bool recede(SmallVectorImpl<unsigned> *LiveUses = nullptr,
311 PressureDiff *PDiff = nullptr);
313 /// Advance across the current instruction.
316 /// Finalize the region boundaries and recored live ins and live outs.
319 /// Initialize the LiveThru pressure set based on the untied defs found in
321 void initLiveThru(const RegPressureTracker &RPTracker);
323 /// Copy an existing live thru pressure result.
324 void initLiveThru(ArrayRef<unsigned> PressureSet) {
325 LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
328 ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
330 /// Get the resulting register pressure over the traversed region.
331 /// This result is complete if either advance() or recede() has returned true,
332 /// or if closeRegion() was explicitly invoked.
333 RegisterPressure &getPressure() { return P; }
334 const RegisterPressure &getPressure() const { return P; }
336 /// Get the register set pressure at the current position, which may be less
337 /// than the pressure across the traversed region.
338 const std::vector<unsigned> &getRegSetPressureAtPos() const {
339 return CurrSetPressure;
342 void discoverLiveOut(unsigned Reg);
343 void discoverLiveIn(unsigned Reg);
345 bool isTopClosed() const;
346 bool isBottomClosed() const;
351 /// Consider the pressure increase caused by traversing this instruction
352 /// bottom-up. Find the pressure set with the most change beyond its pressure
353 /// limit based on the tracker's current pressure, and record the number of
354 /// excess register units of that pressure set introduced by this instruction.
355 void getMaxUpwardPressureDelta(const MachineInstr *MI,
357 RegPressureDelta &Delta,
358 ArrayRef<PressureChange> CriticalPSets,
359 ArrayRef<unsigned> MaxPressureLimit);
361 void getUpwardPressureDelta(const MachineInstr *MI,
362 /*const*/ PressureDiff &PDiff,
363 RegPressureDelta &Delta,
364 ArrayRef<PressureChange> CriticalPSets,
365 ArrayRef<unsigned> MaxPressureLimit) const;
367 /// Consider the pressure increase caused by traversing this instruction
368 /// top-down. Find the pressure set with the most change beyond its pressure
369 /// limit based on the tracker's current pressure, and record the number of
370 /// excess register units of that pressure set introduced by this instruction.
371 void getMaxDownwardPressureDelta(const MachineInstr *MI,
372 RegPressureDelta &Delta,
373 ArrayRef<PressureChange> CriticalPSets,
374 ArrayRef<unsigned> MaxPressureLimit);
376 /// Find the pressure set with the most change beyond its pressure limit after
377 /// traversing this instruction either upward or downward depending on the
378 /// closed end of the current region.
379 void getMaxPressureDelta(const MachineInstr *MI,
380 RegPressureDelta &Delta,
381 ArrayRef<PressureChange> CriticalPSets,
382 ArrayRef<unsigned> MaxPressureLimit) {
384 return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
387 assert(isBottomClosed() && "Uninitialized pressure tracker");
388 return getMaxUpwardPressureDelta(MI, nullptr, Delta, CriticalPSets,
392 /// Get the pressure of each PSet after traversing this instruction bottom-up.
393 void getUpwardPressure(const MachineInstr *MI,
394 std::vector<unsigned> &PressureResult,
395 std::vector<unsigned> &MaxPressureResult);
397 /// Get the pressure of each PSet after traversing this instruction top-down.
398 void getDownwardPressure(const MachineInstr *MI,
399 std::vector<unsigned> &PressureResult,
400 std::vector<unsigned> &MaxPressureResult);
402 void getPressureAfterInst(const MachineInstr *MI,
403 std::vector<unsigned> &PressureResult,
404 std::vector<unsigned> &MaxPressureResult) {
406 return getUpwardPressure(MI, PressureResult, MaxPressureResult);
408 assert(isBottomClosed() && "Uninitialized pressure tracker");
409 return getDownwardPressure(MI, PressureResult, MaxPressureResult);
412 bool hasUntiedDef(unsigned VirtReg) const {
413 return UntiedDefs.count(VirtReg);
419 const LiveRange *getLiveRange(unsigned Reg) const;
421 void increaseRegPressure(ArrayRef<unsigned> Regs);
422 void decreaseRegPressure(ArrayRef<unsigned> Regs);
424 void bumpUpwardPressure(const MachineInstr *MI);
425 void bumpDownwardPressure(const MachineInstr *MI);
428 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
429 const TargetRegisterInfo *TRI);
430 } // end namespace llvm