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 /// List of registers defined and used by a machine instruction.
145 class RegisterOperands {
147 /// List of virtual regiserts and register units read by the instruction.
148 SmallVector<unsigned, 8> Uses;
149 /// \brief List of virtual registers and register units defined by the
150 /// instruction which are not dead.
151 SmallVector<unsigned, 8> Defs;
152 /// \brief List of virtual registers and register units defined by the
153 /// instruction but dead.
154 SmallVector<unsigned, 8> DeadDefs;
156 /// Analyze the given instruction \p MI and fill in the Uses, Defs and
157 /// DeadDefs list based on the MachineOperand flags.
158 void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI,
159 const MachineRegisterInfo &MRI, bool IgnoreDead = false);
161 /// Use liveness information to find dead defs not marked with a dead flag
162 /// and move them to the DeadDefs vector.
163 void detectDeadDefs(const MachineInstr &MI, const LiveIntervals &LIS);
166 /// Array of PressureDiffs.
167 class PressureDiffs {
168 PressureDiff *PDiffArray;
172 PressureDiffs(): PDiffArray(nullptr), Size(0), Max(0) {}
173 ~PressureDiffs() { free(PDiffArray); }
175 void clear() { Size = 0; }
177 void init(unsigned N);
179 PressureDiff &operator[](unsigned Idx) {
180 assert(Idx < Size && "PressureDiff index out of bounds");
181 return PDiffArray[Idx];
183 const PressureDiff &operator[](unsigned Idx) const {
184 return const_cast<PressureDiffs*>(this)->operator[](Idx);
186 /// \brief Record pressure difference induced by the given operand list to
187 /// node with index \p Idx.
188 void addInstruction(unsigned Idx, const RegisterOperands &RegOpers,
189 const MachineRegisterInfo &MRI);
192 /// Store the effects of a change in pressure on things that MI scheduler cares
195 /// Excess records the value of the largest difference in register units beyond
196 /// the target's pressure limits across the affected pressure sets, where
197 /// largest is defined as the absolute value of the difference. Negative
198 /// ExcessUnits indicates a reduction in pressure that had already exceeded the
201 /// CriticalMax records the largest increase in the tracker's max pressure that
202 /// exceeds the critical limit for some pressure set determined by the client.
204 /// CurrentMax records the largest increase in the tracker's max pressure that
205 /// exceeds the current limit for some pressure set determined by the client.
206 struct RegPressureDelta {
207 PressureChange Excess;
208 PressureChange CriticalMax;
209 PressureChange CurrentMax;
211 RegPressureDelta() {}
213 bool operator==(const RegPressureDelta &RHS) const {
214 return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
215 && CurrentMax == RHS.CurrentMax;
217 bool operator!=(const RegPressureDelta &RHS) const {
218 return !operator==(RHS);
222 /// A set of live virtual registers and physical register units.
224 /// This is a wrapper around a SparseSet which deals with mapping register unit
225 /// and virtual register indexes to an index usable by the sparse set.
228 SparseSet<unsigned> Regs;
229 unsigned NumRegUnits;
231 unsigned getSparseIndexFromReg(unsigned Reg) const {
232 if (TargetRegisterInfo::isVirtualRegister(Reg))
233 return TargetRegisterInfo::virtReg2Index(Reg) + NumRegUnits;
234 assert(Reg < NumRegUnits);
237 unsigned getRegFromSparseIndex(unsigned SparseIndex) const {
238 if (SparseIndex >= NumRegUnits)
239 return TargetRegisterInfo::index2VirtReg(SparseIndex-NumRegUnits);
245 void init(const MachineRegisterInfo &MRI);
247 bool contains(unsigned Reg) const {
248 unsigned SparseIndex = getSparseIndexFromReg(Reg);
249 return Regs.count(SparseIndex);
252 bool insert(unsigned Reg) {
253 unsigned SparseIndex = getSparseIndexFromReg(Reg);
254 return Regs.insert(SparseIndex).second;
257 bool erase(unsigned Reg) {
258 unsigned SparseIndex = getSparseIndexFromReg(Reg);
259 return Regs.erase(SparseIndex);
262 size_t size() const {
266 template<typename ContainerT>
267 void appendTo(ContainerT &To) const {
268 for (unsigned I : Regs) {
269 unsigned Reg = getRegFromSparseIndex(I);
275 /// Track the current register pressure at some position in the instruction
276 /// stream, and remember the high water mark within the region traversed. This
277 /// does not automatically consider live-through ranges. The client may
278 /// independently adjust for global liveness.
280 /// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
281 /// be tracked across a larger region by storing a RegisterPressure result at
282 /// each block boundary and explicitly adjusting pressure to account for block
283 /// live-in and live-out register sets.
285 /// RegPressureTracker holds a reference to a RegisterPressure result that it
286 /// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
287 /// is invalid until it reaches the end of the block or closeRegion() is
288 /// explicitly called. Similarly, P.TopIdx is invalid during upward
289 /// tracking. Changing direction has the side effect of closing region, and
290 /// traversing past TopIdx or BottomIdx reopens it.
291 class RegPressureTracker {
292 const MachineFunction *MF;
293 const TargetRegisterInfo *TRI;
294 const RegisterClassInfo *RCI;
295 const MachineRegisterInfo *MRI;
296 const LiveIntervals *LIS;
298 /// We currently only allow pressure tracking within a block.
299 const MachineBasicBlock *MBB;
301 /// Track the max pressure within the region traversed so far.
304 /// Run in two modes dependending on whether constructed with IntervalPressure
305 /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
306 bool RequireIntervals;
308 /// True if UntiedDefs will be populated.
309 bool TrackUntiedDefs;
311 /// Register pressure corresponds to liveness before this instruction
312 /// iterator. It may point to the end of the block or a DebugValue rather than
314 MachineBasicBlock::const_iterator CurrPos;
316 /// Pressure map indexed by pressure set ID, not class ID.
317 std::vector<unsigned> CurrSetPressure;
319 /// Set of live registers.
322 /// Set of vreg defs that start a live range.
323 SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
324 /// Live-through pressure.
325 std::vector<unsigned> LiveThruPressure;
328 RegPressureTracker(IntervalPressure &rp) :
329 MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
330 RequireIntervals(true), TrackUntiedDefs(false) {}
332 RegPressureTracker(RegionPressure &rp) :
333 MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
334 RequireIntervals(false), TrackUntiedDefs(false) {}
338 void init(const MachineFunction *mf, const RegisterClassInfo *rci,
339 const LiveIntervals *lis, const MachineBasicBlock *mbb,
340 MachineBasicBlock::const_iterator pos,
341 bool ShouldTrackUntiedDefs = false);
343 /// Force liveness of virtual registers or physical register
344 /// units. Particularly useful to initialize the livein/out state of the
345 /// tracker before the first call to advance/recede.
346 void addLiveRegs(ArrayRef<unsigned> Regs);
348 /// Get the MI position corresponding to this register pressure.
349 MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
351 // Reset the MI position corresponding to the register pressure. This allows
352 // schedulers to move instructions above the RegPressureTracker's
353 // CurrPos. Since the pressure is computed before CurrPos, the iterator
354 // position changes while pressure does not.
355 void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
357 /// Recede across the previous instruction.
358 void recede(SmallVectorImpl<unsigned> *LiveUses = nullptr);
360 /// Recede across the previous instruction.
361 /// This "low-level" variant assumes that recedeSkipDebugValues() was
362 /// called previously and takes precomputed RegisterOperands for the
364 void recede(const RegisterOperands &RegOpers,
365 SmallVectorImpl<unsigned> *LiveUses = nullptr);
367 /// Recede until we find an instruction which is not a DebugValue.
368 void recedeSkipDebugValues();
370 /// Advance across the current instruction.
373 /// Finalize the region boundaries and recored live ins and live outs.
376 /// Initialize the LiveThru pressure set based on the untied defs found in
378 void initLiveThru(const RegPressureTracker &RPTracker);
380 /// Copy an existing live thru pressure result.
381 void initLiveThru(ArrayRef<unsigned> PressureSet) {
382 LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
385 ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
387 /// Get the resulting register pressure over the traversed region.
388 /// This result is complete if closeRegion() was explicitly invoked.
389 RegisterPressure &getPressure() { return P; }
390 const RegisterPressure &getPressure() const { return P; }
392 /// Get the register set pressure at the current position, which may be less
393 /// than the pressure across the traversed region.
394 const std::vector<unsigned> &getRegSetPressureAtPos() const {
395 return CurrSetPressure;
398 bool isTopClosed() const;
399 bool isBottomClosed() const;
404 /// Consider the pressure increase caused by traversing this instruction
405 /// bottom-up. Find the pressure set with the most change beyond its pressure
406 /// limit based on the tracker's current pressure, and record the number of
407 /// excess register units of that pressure set introduced by this instruction.
408 void getMaxUpwardPressureDelta(const MachineInstr *MI,
410 RegPressureDelta &Delta,
411 ArrayRef<PressureChange> CriticalPSets,
412 ArrayRef<unsigned> MaxPressureLimit);
414 void getUpwardPressureDelta(const MachineInstr *MI,
415 /*const*/ PressureDiff &PDiff,
416 RegPressureDelta &Delta,
417 ArrayRef<PressureChange> CriticalPSets,
418 ArrayRef<unsigned> MaxPressureLimit) const;
420 /// Consider the pressure increase caused by traversing this instruction
421 /// top-down. Find the pressure set with the most change beyond its pressure
422 /// limit based on the tracker's current pressure, and record the number of
423 /// excess register units of that pressure set introduced by this instruction.
424 void getMaxDownwardPressureDelta(const MachineInstr *MI,
425 RegPressureDelta &Delta,
426 ArrayRef<PressureChange> CriticalPSets,
427 ArrayRef<unsigned> MaxPressureLimit);
429 /// Find the pressure set with the most change beyond its pressure limit after
430 /// traversing this instruction either upward or downward depending on the
431 /// closed end of the current region.
432 void getMaxPressureDelta(const MachineInstr *MI,
433 RegPressureDelta &Delta,
434 ArrayRef<PressureChange> CriticalPSets,
435 ArrayRef<unsigned> MaxPressureLimit) {
437 return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
440 assert(isBottomClosed() && "Uninitialized pressure tracker");
441 return getMaxUpwardPressureDelta(MI, nullptr, Delta, CriticalPSets,
445 /// Get the pressure of each PSet after traversing this instruction bottom-up.
446 void getUpwardPressure(const MachineInstr *MI,
447 std::vector<unsigned> &PressureResult,
448 std::vector<unsigned> &MaxPressureResult);
450 /// Get the pressure of each PSet after traversing this instruction top-down.
451 void getDownwardPressure(const MachineInstr *MI,
452 std::vector<unsigned> &PressureResult,
453 std::vector<unsigned> &MaxPressureResult);
455 void getPressureAfterInst(const MachineInstr *MI,
456 std::vector<unsigned> &PressureResult,
457 std::vector<unsigned> &MaxPressureResult) {
459 return getUpwardPressure(MI, PressureResult, MaxPressureResult);
461 assert(isBottomClosed() && "Uninitialized pressure tracker");
462 return getDownwardPressure(MI, PressureResult, MaxPressureResult);
465 bool hasUntiedDef(unsigned VirtReg) const {
466 return UntiedDefs.count(VirtReg);
472 void discoverLiveOut(unsigned Reg);
473 void discoverLiveIn(unsigned Reg);
475 /// \brief Get the SlotIndex for the first nondebug instruction including or
476 /// after the current position.
477 SlotIndex getCurrSlot() const;
479 void increaseRegPressure(ArrayRef<unsigned> Regs);
480 void decreaseRegPressure(ArrayRef<unsigned> Regs);
482 void bumpUpwardPressure(const MachineInstr *MI);
483 void bumpDownwardPressure(const MachineInstr *MI);
486 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
487 const TargetRegisterInfo *TRI);
488 } // end namespace llvm