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 /// Increase register pressure for each pressure set impacted by this register
39 /// class. Normally called by RegPressureTracker, but may be called manually
40 /// to account for live through (global liveness).
42 /// \param Reg is either a virtual register number or register unit number.
43 void increase(unsigned Reg, const TargetRegisterInfo *TRI,
44 const MachineRegisterInfo *MRI);
46 /// Decrease register pressure for each pressure set impacted by this register
47 /// class. This is only useful to account for spilling or rematerialization.
49 /// \param Reg is either a virtual register number or register unit number.
50 void decrease(unsigned Reg, const TargetRegisterInfo *TRI,
51 const MachineRegisterInfo *MRI);
53 void dump(const TargetRegisterInfo *TRI) const;
56 /// RegisterPressure computed within a region of instructions delimited by
57 /// TopIdx and BottomIdx. During pressure computation, the maximum pressure per
58 /// register pressure set is increased. Once pressure within a region is fully
59 /// computed, the live-in and live-out sets are recorded.
61 /// This is preferable to RegionPressure when LiveIntervals are available,
62 /// because delimiting regions by SlotIndex is more robust and convenient than
63 /// holding block iterators. The block contents can change without invalidating
64 /// the pressure result.
65 struct IntervalPressure : RegisterPressure {
66 /// Record the boundary of the region being tracked.
72 void openTop(SlotIndex NextTop);
74 void openBottom(SlotIndex PrevBottom);
77 /// RegisterPressure computed within a region of instructions delimited by
78 /// TopPos and BottomPos. This is a less precise version of IntervalPressure for
79 /// use when LiveIntervals are unavailable.
80 struct RegionPressure : RegisterPressure {
81 /// Record the boundary of the region being tracked.
82 MachineBasicBlock::const_iterator TopPos;
83 MachineBasicBlock::const_iterator BottomPos;
87 void openTop(MachineBasicBlock::const_iterator PrevTop);
89 void openBottom(MachineBasicBlock::const_iterator PrevBottom);
92 /// Capture a change in pressure for a single pressure set. UnitInc may be
93 /// expressed in terms of upward or downward pressure depending on the client
94 /// and will be dynamically adjusted for current liveness.
96 /// Pressure increments are tiny, typically 1-2 units, and this is only for
97 /// heuristics, so we don't check UnitInc overflow. Instead, we may have a
98 /// higher level assert that pressure is consistent within a region. We also
99 /// effectively ignore dead defs which don't affect heuristics much.
100 class PressureChange {
101 uint16_t PSetID; // ID+1. 0=Invalid.
104 PressureChange(): PSetID(0), UnitInc(0) {}
105 PressureChange(unsigned id): PSetID(id+1), UnitInc(0) {
106 assert(id < UINT16_MAX && "PSetID overflow.");
109 bool isValid() const { return PSetID > 0; }
111 unsigned getPSet() const {
112 assert(isValid() && "invalid PressureChange");
115 // If PSetID is invalid, return UINT16_MAX to give it lowest priority.
116 unsigned getPSetOrMax() const { return (PSetID - 1) & UINT16_MAX; }
118 int getUnitInc() const { return UnitInc; }
120 void setUnitInc(int Inc) { UnitInc = Inc; }
122 bool operator==(const PressureChange &RHS) const {
123 return PSetID == RHS.PSetID && UnitInc == RHS.UnitInc;
127 template <> struct isPodLike<PressureChange> {
128 static const bool value = true;
131 /// List of PressureChanges in order of increasing, unique PSetID.
133 /// Use a small fixed number, because we can fit more PressureChanges in an
134 /// empty SmallVector than ever need to be tracked per register class. If more
135 /// PSets are affected, then we only track the most constrained.
137 // The initial design was for MaxPSets=4, but that requires PSet partitions,
138 // which are not yet implemented. (PSet partitions are equivalent PSets given
139 // the register classes actually in use within the scheduling region.)
140 enum { MaxPSets = 16 };
142 PressureChange PressureChanges[MaxPSets];
144 typedef PressureChange* iterator;
145 typedef const PressureChange* const_iterator;
146 iterator begin() { return &PressureChanges[0]; }
147 iterator end() { return &PressureChanges[MaxPSets]; }
149 void addPressureChange(unsigned RegUnit, bool IsDec,
150 const MachineRegisterInfo *MRI);
153 /// Array of PressureDiffs.
154 class PressureDiffs {
155 PressureDiff *PDiffArray;
159 PressureDiffs(): PDiffArray(0), Size(0), Max(0) {}
161 void init(unsigned N);
163 PressureDiff &operator[](unsigned Idx) {
164 assert(Idx < Size && "PressureDiff index out of bounds");
165 return PDiffArray[Idx];
167 const PressureDiff &operator[](unsigned Idx) const {
168 return const_cast<PressureDiffs*>(this)->operator[](Idx);
172 /// Store the effects of a change in pressure on things that MI scheduler cares
175 /// Excess records the value of the largest difference in register units beyond
176 /// the target's pressure limits across the affected pressure sets, where
177 /// largest is defined as the absolute value of the difference. Negative
178 /// ExcessUnits indicates a reduction in pressure that had already exceeded the
181 /// CriticalMax records the largest increase in the tracker's max pressure that
182 /// exceeds the critical limit for some pressure set determined by the client.
184 /// CurrentMax records the largest increase in the tracker's max pressure that
185 /// exceeds the current limit for some pressure set determined by the client.
186 struct RegPressureDelta {
187 PressureChange Excess;
188 PressureChange CriticalMax;
189 PressureChange CurrentMax;
191 RegPressureDelta() {}
193 bool operator==(const RegPressureDelta &RHS) const {
194 return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
195 && CurrentMax == RHS.CurrentMax;
197 bool operator!=(const RegPressureDelta &RHS) const {
198 return !operator==(RHS);
202 /// \brief A set of live virtual registers and physical register units.
204 /// Virtual and physical register numbers require separate sparse sets, but most
205 /// of the RegisterPressureTracker handles them uniformly.
207 SparseSet<unsigned> PhysRegs;
208 SparseSet<unsigned, VirtReg2IndexFunctor> VirtRegs;
210 bool contains(unsigned Reg) const {
211 if (TargetRegisterInfo::isVirtualRegister(Reg))
212 return VirtRegs.count(Reg);
213 return PhysRegs.count(Reg);
216 bool insert(unsigned Reg) {
217 if (TargetRegisterInfo::isVirtualRegister(Reg))
218 return VirtRegs.insert(Reg).second;
219 return PhysRegs.insert(Reg).second;
222 bool erase(unsigned Reg) {
223 if (TargetRegisterInfo::isVirtualRegister(Reg))
224 return VirtRegs.erase(Reg);
225 return PhysRegs.erase(Reg);
229 /// Track the current register pressure at some position in the instruction
230 /// stream, and remember the high water mark within the region traversed. This
231 /// does not automatically consider live-through ranges. The client may
232 /// independently adjust for global liveness.
234 /// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
235 /// be tracked across a larger region by storing a RegisterPressure result at
236 /// each block boundary and explicitly adjusting pressure to account for block
237 /// live-in and live-out register sets.
239 /// RegPressureTracker holds a reference to a RegisterPressure result that it
240 /// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
241 /// is invalid until it reaches the end of the block or closeRegion() is
242 /// explicitly called. Similarly, P.TopIdx is invalid during upward
243 /// tracking. Changing direction has the side effect of closing region, and
244 /// traversing past TopIdx or BottomIdx reopens it.
245 class RegPressureTracker {
246 const MachineFunction *MF;
247 const TargetRegisterInfo *TRI;
248 const RegisterClassInfo *RCI;
249 const MachineRegisterInfo *MRI;
250 const LiveIntervals *LIS;
252 /// We currently only allow pressure tracking within a block.
253 const MachineBasicBlock *MBB;
255 /// Track the max pressure within the region traversed so far.
258 /// Run in two modes dependending on whether constructed with IntervalPressure
259 /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
260 bool RequireIntervals;
262 /// True if UntiedDefs will be populated.
263 bool TrackUntiedDefs;
265 /// Register pressure corresponds to liveness before this instruction
266 /// iterator. It may point to the end of the block or a DebugValue rather than
268 MachineBasicBlock::const_iterator CurrPos;
270 /// Pressure map indexed by pressure set ID, not class ID.
271 std::vector<unsigned> CurrSetPressure;
273 /// Set of live registers.
276 /// Set of vreg defs that start a live range.
277 SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
278 /// Live-through pressure.
279 std::vector<unsigned> LiveThruPressure;
282 RegPressureTracker(IntervalPressure &rp) :
283 MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(true),
284 TrackUntiedDefs(false) {}
286 RegPressureTracker(RegionPressure &rp) :
287 MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(false),
288 TrackUntiedDefs(false) {}
290 void init(const MachineFunction *mf, const RegisterClassInfo *rci,
291 const LiveIntervals *lis, const MachineBasicBlock *mbb,
292 MachineBasicBlock::const_iterator pos,
293 bool ShouldTrackUntiedDefs = false);
295 /// Force liveness of virtual registers or physical register
296 /// units. Particularly useful to initialize the livein/out state of the
297 /// tracker before the first call to advance/recede.
298 void addLiveRegs(ArrayRef<unsigned> Regs);
300 /// Get the MI position corresponding to this register pressure.
301 MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
303 // Reset the MI position corresponding to the register pressure. This allows
304 // schedulers to move instructions above the RegPressureTracker's
305 // CurrPos. Since the pressure is computed before CurrPos, the iterator
306 // position changes while pressure does not.
307 void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
309 /// \brief Get the SlotIndex for the first nondebug instruction including or
310 /// after the current position.
311 SlotIndex getCurrSlot() const;
313 /// Recede across the previous instruction.
314 bool recede(SmallVectorImpl<unsigned> *LiveUses = 0, PressureDiff *PDiff = 0);
316 /// Advance across the current instruction.
319 /// Finalize the region boundaries and recored live ins and live outs.
322 /// Initialize the LiveThru pressure set based on the untied defs found in
324 void initLiveThru(const RegPressureTracker &RPTracker);
326 /// Copy an existing live thru pressure result.
327 void initLiveThru(ArrayRef<unsigned> PressureSet) {
328 LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
331 ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
333 /// Get the resulting register pressure over the traversed region.
334 /// This result is complete if either advance() or recede() has returned true,
335 /// or if closeRegion() was explicitly invoked.
336 RegisterPressure &getPressure() { return P; }
337 const RegisterPressure &getPressure() const { return P; }
339 /// Get the register set pressure at the current position, which may be less
340 /// than the pressure across the traversed region.
341 std::vector<unsigned> &getRegSetPressureAtPos() { return CurrSetPressure; }
343 void discoverLiveOut(unsigned Reg);
344 void discoverLiveIn(unsigned Reg);
346 bool isTopClosed() const;
347 bool isBottomClosed() const;
352 /// Consider the pressure increase caused by traversing this instruction
353 /// bottom-up. Find the pressure set with the most change beyond its pressure
354 /// limit based on the tracker's current pressure, and record the number of
355 /// excess register units of that pressure set introduced by this instruction.
356 void getMaxUpwardPressureDelta(const MachineInstr *MI,
358 RegPressureDelta &Delta,
359 ArrayRef<PressureChange> CriticalPSets,
360 ArrayRef<unsigned> MaxPressureLimit);
362 void getUpwardPressureDelta(const MachineInstr *MI,
363 /*const*/ PressureDiff &PDiff,
364 RegPressureDelta &Delta,
365 ArrayRef<PressureChange> CriticalPSets,
366 ArrayRef<unsigned> MaxPressureLimit) const;
368 /// Consider the pressure increase caused by traversing this instruction
369 /// top-down. Find the pressure set with the most change beyond its pressure
370 /// limit based on the tracker's current pressure, and record the number of
371 /// excess register units of that pressure set introduced by this instruction.
372 void getMaxDownwardPressureDelta(const MachineInstr *MI,
373 RegPressureDelta &Delta,
374 ArrayRef<PressureChange> CriticalPSets,
375 ArrayRef<unsigned> MaxPressureLimit);
377 /// Find the pressure set with the most change beyond its pressure limit after
378 /// traversing this instruction either upward or downward depending on the
379 /// closed end of the current region.
380 void getMaxPressureDelta(const MachineInstr *MI,
381 RegPressureDelta &Delta,
382 ArrayRef<PressureChange> CriticalPSets,
383 ArrayRef<unsigned> MaxPressureLimit) {
385 return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
388 assert(isBottomClosed() && "Uninitialized pressure tracker");
389 return getMaxUpwardPressureDelta(MI, 0, Delta, CriticalPSets,
393 /// Get the pressure of each PSet after traversing this instruction bottom-up.
394 void getUpwardPressure(const MachineInstr *MI,
395 std::vector<unsigned> &PressureResult,
396 std::vector<unsigned> &MaxPressureResult);
398 /// Get the pressure of each PSet after traversing this instruction top-down.
399 void getDownwardPressure(const MachineInstr *MI,
400 std::vector<unsigned> &PressureResult,
401 std::vector<unsigned> &MaxPressureResult);
403 void getPressureAfterInst(const MachineInstr *MI,
404 std::vector<unsigned> &PressureResult,
405 std::vector<unsigned> &MaxPressureResult) {
407 return getUpwardPressure(MI, PressureResult, MaxPressureResult);
409 assert(isBottomClosed() && "Uninitialized pressure tracker");
410 return getDownwardPressure(MI, PressureResult, MaxPressureResult);
413 bool hasUntiedDef(unsigned VirtReg) const {
414 return UntiedDefs.count(VirtReg);
420 const LiveInterval *getInterval(unsigned Reg) const;
422 void increaseRegPressure(ArrayRef<unsigned> Regs);
423 void decreaseRegPressure(ArrayRef<unsigned> Regs);
425 void bumpUpwardPressure(const MachineInstr *MI);
426 void bumpDownwardPressure(const MachineInstr *MI);
429 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
430 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
431 const TargetRegisterInfo *TRI);
433 } // end namespace llvm