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) {}
160 ~PressureDiffs() { free(PDiffArray); }
162 void init(unsigned N);
164 PressureDiff &operator[](unsigned Idx) {
165 assert(Idx < Size && "PressureDiff index out of bounds");
166 return PDiffArray[Idx];
168 const PressureDiff &operator[](unsigned Idx) const {
169 return const_cast<PressureDiffs*>(this)->operator[](Idx);
173 /// Store the effects of a change in pressure on things that MI scheduler cares
176 /// Excess records the value of the largest difference in register units beyond
177 /// the target's pressure limits across the affected pressure sets, where
178 /// largest is defined as the absolute value of the difference. Negative
179 /// ExcessUnits indicates a reduction in pressure that had already exceeded the
182 /// CriticalMax records the largest increase in the tracker's max pressure that
183 /// exceeds the critical limit for some pressure set determined by the client.
185 /// CurrentMax records the largest increase in the tracker's max pressure that
186 /// exceeds the current limit for some pressure set determined by the client.
187 struct RegPressureDelta {
188 PressureChange Excess;
189 PressureChange CriticalMax;
190 PressureChange CurrentMax;
192 RegPressureDelta() {}
194 bool operator==(const RegPressureDelta &RHS) const {
195 return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
196 && CurrentMax == RHS.CurrentMax;
198 bool operator!=(const RegPressureDelta &RHS) const {
199 return !operator==(RHS);
203 /// \brief A set of live virtual registers and physical register units.
205 /// Virtual and physical register numbers require separate sparse sets, but most
206 /// of the RegisterPressureTracker handles them uniformly.
208 SparseSet<unsigned> PhysRegs;
209 SparseSet<unsigned, VirtReg2IndexFunctor> VirtRegs;
211 bool contains(unsigned Reg) const {
212 if (TargetRegisterInfo::isVirtualRegister(Reg))
213 return VirtRegs.count(Reg);
214 return PhysRegs.count(Reg);
217 bool insert(unsigned Reg) {
218 if (TargetRegisterInfo::isVirtualRegister(Reg))
219 return VirtRegs.insert(Reg).second;
220 return PhysRegs.insert(Reg).second;
223 bool erase(unsigned Reg) {
224 if (TargetRegisterInfo::isVirtualRegister(Reg))
225 return VirtRegs.erase(Reg);
226 return PhysRegs.erase(Reg);
230 /// Track the current register pressure at some position in the instruction
231 /// stream, and remember the high water mark within the region traversed. This
232 /// does not automatically consider live-through ranges. The client may
233 /// independently adjust for global liveness.
235 /// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
236 /// be tracked across a larger region by storing a RegisterPressure result at
237 /// each block boundary and explicitly adjusting pressure to account for block
238 /// live-in and live-out register sets.
240 /// RegPressureTracker holds a reference to a RegisterPressure result that it
241 /// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
242 /// is invalid until it reaches the end of the block or closeRegion() is
243 /// explicitly called. Similarly, P.TopIdx is invalid during upward
244 /// tracking. Changing direction has the side effect of closing region, and
245 /// traversing past TopIdx or BottomIdx reopens it.
246 class RegPressureTracker {
247 const MachineFunction *MF;
248 const TargetRegisterInfo *TRI;
249 const RegisterClassInfo *RCI;
250 const MachineRegisterInfo *MRI;
251 const LiveIntervals *LIS;
253 /// We currently only allow pressure tracking within a block.
254 const MachineBasicBlock *MBB;
256 /// Track the max pressure within the region traversed so far.
259 /// Run in two modes dependending on whether constructed with IntervalPressure
260 /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
261 bool RequireIntervals;
263 /// True if UntiedDefs will be populated.
264 bool TrackUntiedDefs;
266 /// Register pressure corresponds to liveness before this instruction
267 /// iterator. It may point to the end of the block or a DebugValue rather than
269 MachineBasicBlock::const_iterator CurrPos;
271 /// Pressure map indexed by pressure set ID, not class ID.
272 std::vector<unsigned> CurrSetPressure;
274 /// Set of live registers.
277 /// Set of vreg defs that start a live range.
278 SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
279 /// Live-through pressure.
280 std::vector<unsigned> LiveThruPressure;
283 RegPressureTracker(IntervalPressure &rp) :
284 MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(true),
285 TrackUntiedDefs(false) {}
287 RegPressureTracker(RegionPressure &rp) :
288 MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(false),
289 TrackUntiedDefs(false) {}
291 void init(const MachineFunction *mf, const RegisterClassInfo *rci,
292 const LiveIntervals *lis, const MachineBasicBlock *mbb,
293 MachineBasicBlock::const_iterator pos,
294 bool ShouldTrackUntiedDefs = false);
296 /// Force liveness of virtual registers or physical register
297 /// units. Particularly useful to initialize the livein/out state of the
298 /// tracker before the first call to advance/recede.
299 void addLiveRegs(ArrayRef<unsigned> Regs);
301 /// Get the MI position corresponding to this register pressure.
302 MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
304 // Reset the MI position corresponding to the register pressure. This allows
305 // schedulers to move instructions above the RegPressureTracker's
306 // CurrPos. Since the pressure is computed before CurrPos, the iterator
307 // position changes while pressure does not.
308 void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
310 /// \brief Get the SlotIndex for the first nondebug instruction including or
311 /// after the current position.
312 SlotIndex getCurrSlot() const;
314 /// Recede across the previous instruction.
315 bool recede(SmallVectorImpl<unsigned> *LiveUses = 0, PressureDiff *PDiff = 0);
317 /// Advance across the current instruction.
320 /// Finalize the region boundaries and recored live ins and live outs.
323 /// Initialize the LiveThru pressure set based on the untied defs found in
325 void initLiveThru(const RegPressureTracker &RPTracker);
327 /// Copy an existing live thru pressure result.
328 void initLiveThru(ArrayRef<unsigned> PressureSet) {
329 LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
332 ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
334 /// Get the resulting register pressure over the traversed region.
335 /// This result is complete if either advance() or recede() has returned true,
336 /// or if closeRegion() was explicitly invoked.
337 RegisterPressure &getPressure() { return P; }
338 const RegisterPressure &getPressure() const { return P; }
340 /// Get the register set pressure at the current position, which may be less
341 /// than the pressure across the traversed region.
342 std::vector<unsigned> &getRegSetPressureAtPos() { return CurrSetPressure; }
344 void discoverLiveOut(unsigned Reg);
345 void discoverLiveIn(unsigned Reg);
347 bool isTopClosed() const;
348 bool isBottomClosed() const;
353 /// Consider the pressure increase caused by traversing this instruction
354 /// bottom-up. Find the pressure set with the most change beyond its pressure
355 /// limit based on the tracker's current pressure, and record the number of
356 /// excess register units of that pressure set introduced by this instruction.
357 void getMaxUpwardPressureDelta(const MachineInstr *MI,
359 RegPressureDelta &Delta,
360 ArrayRef<PressureChange> CriticalPSets,
361 ArrayRef<unsigned> MaxPressureLimit);
363 void getUpwardPressureDelta(const MachineInstr *MI,
364 /*const*/ PressureDiff &PDiff,
365 RegPressureDelta &Delta,
366 ArrayRef<PressureChange> CriticalPSets,
367 ArrayRef<unsigned> MaxPressureLimit) const;
369 /// Consider the pressure increase caused by traversing this instruction
370 /// top-down. Find the pressure set with the most change beyond its pressure
371 /// limit based on the tracker's current pressure, and record the number of
372 /// excess register units of that pressure set introduced by this instruction.
373 void getMaxDownwardPressureDelta(const MachineInstr *MI,
374 RegPressureDelta &Delta,
375 ArrayRef<PressureChange> CriticalPSets,
376 ArrayRef<unsigned> MaxPressureLimit);
378 /// Find the pressure set with the most change beyond its pressure limit after
379 /// traversing this instruction either upward or downward depending on the
380 /// closed end of the current region.
381 void getMaxPressureDelta(const MachineInstr *MI,
382 RegPressureDelta &Delta,
383 ArrayRef<PressureChange> CriticalPSets,
384 ArrayRef<unsigned> MaxPressureLimit) {
386 return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
389 assert(isBottomClosed() && "Uninitialized pressure tracker");
390 return getMaxUpwardPressureDelta(MI, 0, Delta, CriticalPSets,
394 /// Get the pressure of each PSet after traversing this instruction bottom-up.
395 void getUpwardPressure(const MachineInstr *MI,
396 std::vector<unsigned> &PressureResult,
397 std::vector<unsigned> &MaxPressureResult);
399 /// Get the pressure of each PSet after traversing this instruction top-down.
400 void getDownwardPressure(const MachineInstr *MI,
401 std::vector<unsigned> &PressureResult,
402 std::vector<unsigned> &MaxPressureResult);
404 void getPressureAfterInst(const MachineInstr *MI,
405 std::vector<unsigned> &PressureResult,
406 std::vector<unsigned> &MaxPressureResult) {
408 return getUpwardPressure(MI, PressureResult, MaxPressureResult);
410 assert(isBottomClosed() && "Uninitialized pressure tracker");
411 return getDownwardPressure(MI, PressureResult, MaxPressureResult);
414 bool hasUntiedDef(unsigned VirtReg) const {
415 return UntiedDefs.count(VirtReg);
421 const LiveInterval *getInterval(unsigned Reg) const;
423 void increaseRegPressure(ArrayRef<unsigned> Regs);
424 void decreaseRegPressure(ArrayRef<unsigned> Regs);
426 void bumpUpwardPressure(const MachineInstr *MI);
427 void bumpDownwardPressure(const MachineInstr *MI);
430 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
431 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
432 const TargetRegisterInfo *TRI);
434 } // end namespace llvm