LLVM  mainline
RegisterPressure.h
Go to the documentation of this file.
00001 //===-- RegisterPressure.h - Dynamic Register Pressure -*- C++ -*-------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the RegisterPressure class which can be used to track
00011 // MachineInstr level register pressure.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_CODEGEN_REGISTERPRESSURE_H
00016 #define LLVM_CODEGEN_REGISTERPRESSURE_H
00017 
00018 #include "llvm/ADT/SparseSet.h"
00019 #include "llvm/CodeGen/SlotIndexes.h"
00020 #include "llvm/Target/TargetRegisterInfo.h"
00021 
00022 namespace llvm {
00023 
00024 class LiveIntervals;
00025 class LiveRange;
00026 class RegisterClassInfo;
00027 class MachineInstr;
00028 
00029 /// Base class for register pressure results.
00030 struct RegisterPressure {
00031   /// Map of max reg pressure indexed by pressure set ID, not class ID.
00032   std::vector<unsigned> MaxSetPressure;
00033 
00034   /// List of live in virtual registers or physical register units.
00035   SmallVector<unsigned,8> LiveInRegs;
00036   SmallVector<unsigned,8> LiveOutRegs;
00037 
00038   void dump(const TargetRegisterInfo *TRI) const;
00039 };
00040 
00041 /// RegisterPressure computed within a region of instructions delimited by
00042 /// TopIdx and BottomIdx.  During pressure computation, the maximum pressure per
00043 /// register pressure set is increased. Once pressure within a region is fully
00044 /// computed, the live-in and live-out sets are recorded.
00045 ///
00046 /// This is preferable to RegionPressure when LiveIntervals are available,
00047 /// because delimiting regions by SlotIndex is more robust and convenient than
00048 /// holding block iterators. The block contents can change without invalidating
00049 /// the pressure result.
00050 struct IntervalPressure : RegisterPressure {
00051   /// Record the boundary of the region being tracked.
00052   SlotIndex TopIdx;
00053   SlotIndex BottomIdx;
00054 
00055   void reset();
00056 
00057   void openTop(SlotIndex NextTop);
00058 
00059   void openBottom(SlotIndex PrevBottom);
00060 };
00061 
00062 /// RegisterPressure computed within a region of instructions delimited by
00063 /// TopPos and BottomPos. This is a less precise version of IntervalPressure for
00064 /// use when LiveIntervals are unavailable.
00065 struct RegionPressure : RegisterPressure {
00066   /// Record the boundary of the region being tracked.
00067   MachineBasicBlock::const_iterator TopPos;
00068   MachineBasicBlock::const_iterator BottomPos;
00069 
00070   void reset();
00071 
00072   void openTop(MachineBasicBlock::const_iterator PrevTop);
00073 
00074   void openBottom(MachineBasicBlock::const_iterator PrevBottom);
00075 };
00076 
00077 /// Capture a change in pressure for a single pressure set. UnitInc may be
00078 /// expressed in terms of upward or downward pressure depending on the client
00079 /// and will be dynamically adjusted for current liveness.
00080 ///
00081 /// Pressure increments are tiny, typically 1-2 units, and this is only for
00082 /// heuristics, so we don't check UnitInc overflow. Instead, we may have a
00083 /// higher level assert that pressure is consistent within a region. We also
00084 /// effectively ignore dead defs which don't affect heuristics much.
00085 class PressureChange {
00086   uint16_t PSetID; // ID+1. 0=Invalid.
00087   int16_t  UnitInc;
00088 public:
00089   PressureChange(): PSetID(0), UnitInc(0) {}
00090   PressureChange(unsigned id): PSetID(id+1), UnitInc(0) {
00091     assert(id < UINT16_MAX && "PSetID overflow.");
00092   }
00093 
00094   bool isValid() const { return PSetID > 0; }
00095 
00096   unsigned getPSet() const {
00097     assert(isValid() && "invalid PressureChange");
00098     return PSetID - 1;
00099   }
00100   // If PSetID is invalid, return UINT16_MAX to give it lowest priority.
00101   unsigned getPSetOrMax() const { return (PSetID - 1) & UINT16_MAX; }
00102 
00103   int getUnitInc() const { return UnitInc; }
00104 
00105   void setUnitInc(int Inc) { UnitInc = Inc; }
00106 
00107   bool operator==(const PressureChange &RHS) const {
00108     return PSetID == RHS.PSetID && UnitInc == RHS.UnitInc;
00109   }
00110 };
00111 
00112 template <> struct isPodLike<PressureChange> {
00113    static const bool value = true;
00114 };
00115 
00116 /// List of PressureChanges in order of increasing, unique PSetID.
00117 ///
00118 /// Use a small fixed number, because we can fit more PressureChanges in an
00119 /// empty SmallVector than ever need to be tracked per register class. If more
00120 /// PSets are affected, then we only track the most constrained.
00121 class PressureDiff {
00122   // The initial design was for MaxPSets=4, but that requires PSet partitions,
00123   // which are not yet implemented. (PSet partitions are equivalent PSets given
00124   // the register classes actually in use within the scheduling region.)
00125   enum { MaxPSets = 16 };
00126 
00127   PressureChange PressureChanges[MaxPSets];
00128 public:
00129   typedef PressureChange* iterator;
00130   typedef const PressureChange* const_iterator;
00131   iterator begin() { return &PressureChanges[0]; }
00132   iterator end() { return &PressureChanges[MaxPSets]; }
00133   const_iterator begin() const { return &PressureChanges[0]; }
00134   const_iterator end() const { return &PressureChanges[MaxPSets]; }
00135 
00136   void addPressureChange(unsigned RegUnit, bool IsDec,
00137                          const MachineRegisterInfo *MRI);
00138 };
00139 
00140 /// Array of PressureDiffs.
00141 class PressureDiffs {
00142   PressureDiff *PDiffArray;
00143   unsigned Size;
00144   unsigned Max;
00145 public:
00146   PressureDiffs(): PDiffArray(nullptr), Size(0), Max(0) {}
00147   ~PressureDiffs() { free(PDiffArray); }
00148 
00149   void clear() { Size = 0; }
00150 
00151   void init(unsigned N);
00152 
00153   PressureDiff &operator[](unsigned Idx) {
00154     assert(Idx < Size && "PressureDiff index out of bounds");
00155     return PDiffArray[Idx];
00156   }
00157   const PressureDiff &operator[](unsigned Idx) const {
00158     return const_cast<PressureDiffs*>(this)->operator[](Idx);
00159   }
00160 };
00161 
00162 /// Store the effects of a change in pressure on things that MI scheduler cares
00163 /// about.
00164 ///
00165 /// Excess records the value of the largest difference in register units beyond
00166 /// the target's pressure limits across the affected pressure sets, where
00167 /// largest is defined as the absolute value of the difference. Negative
00168 /// ExcessUnits indicates a reduction in pressure that had already exceeded the
00169 /// target's limits.
00170 ///
00171 /// CriticalMax records the largest increase in the tracker's max pressure that
00172 /// exceeds the critical limit for some pressure set determined by the client.
00173 ///
00174 /// CurrentMax records the largest increase in the tracker's max pressure that
00175 /// exceeds the current limit for some pressure set determined by the client.
00176 struct RegPressureDelta {
00177   PressureChange Excess;
00178   PressureChange CriticalMax;
00179   PressureChange CurrentMax;
00180 
00181   RegPressureDelta() {}
00182 
00183   bool operator==(const RegPressureDelta &RHS) const {
00184     return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
00185       && CurrentMax == RHS.CurrentMax;
00186   }
00187   bool operator!=(const RegPressureDelta &RHS) const {
00188     return !operator==(RHS);
00189   }
00190 };
00191 
00192 /// \brief A set of live virtual registers and physical register units.
00193 ///
00194 /// Virtual and physical register numbers require separate sparse sets, but most
00195 /// of the RegisterPressureTracker handles them uniformly.
00196 struct LiveRegSet {
00197   SparseSet<unsigned> PhysRegs;
00198   SparseSet<unsigned, VirtReg2IndexFunctor> VirtRegs;
00199 
00200   bool contains(unsigned Reg) const {
00201     if (TargetRegisterInfo::isVirtualRegister(Reg))
00202       return VirtRegs.count(Reg);
00203     return PhysRegs.count(Reg);
00204   }
00205 
00206   bool insert(unsigned Reg) {
00207     if (TargetRegisterInfo::isVirtualRegister(Reg))
00208       return VirtRegs.insert(Reg).second;
00209     return PhysRegs.insert(Reg).second;
00210   }
00211 
00212   bool erase(unsigned Reg) {
00213     if (TargetRegisterInfo::isVirtualRegister(Reg))
00214       return VirtRegs.erase(Reg);
00215     return PhysRegs.erase(Reg);
00216   }
00217 };
00218 
00219 /// Track the current register pressure at some position in the instruction
00220 /// stream, and remember the high water mark within the region traversed. This
00221 /// does not automatically consider live-through ranges. The client may
00222 /// independently adjust for global liveness.
00223 ///
00224 /// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
00225 /// be tracked across a larger region by storing a RegisterPressure result at
00226 /// each block boundary and explicitly adjusting pressure to account for block
00227 /// live-in and live-out register sets.
00228 ///
00229 /// RegPressureTracker holds a reference to a RegisterPressure result that it
00230 /// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
00231 /// is invalid until it reaches the end of the block or closeRegion() is
00232 /// explicitly called. Similarly, P.TopIdx is invalid during upward
00233 /// tracking. Changing direction has the side effect of closing region, and
00234 /// traversing past TopIdx or BottomIdx reopens it.
00235 class RegPressureTracker {
00236   const MachineFunction     *MF;
00237   const TargetRegisterInfo  *TRI;
00238   const RegisterClassInfo   *RCI;
00239   const MachineRegisterInfo *MRI;
00240   const LiveIntervals       *LIS;
00241 
00242   /// We currently only allow pressure tracking within a block.
00243   const MachineBasicBlock *MBB;
00244 
00245   /// Track the max pressure within the region traversed so far.
00246   RegisterPressure &P;
00247 
00248   /// Run in two modes dependending on whether constructed with IntervalPressure
00249   /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
00250   bool RequireIntervals;
00251 
00252   /// True if UntiedDefs will be populated.
00253   bool TrackUntiedDefs;
00254 
00255   /// Register pressure corresponds to liveness before this instruction
00256   /// iterator. It may point to the end of the block or a DebugValue rather than
00257   /// an instruction.
00258   MachineBasicBlock::const_iterator CurrPos;
00259 
00260   /// Pressure map indexed by pressure set ID, not class ID.
00261   std::vector<unsigned> CurrSetPressure;
00262 
00263   /// Set of live registers.
00264   LiveRegSet LiveRegs;
00265 
00266   /// Set of vreg defs that start a live range.
00267   SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
00268   /// Live-through pressure.
00269   std::vector<unsigned> LiveThruPressure;
00270 
00271 public:
00272   RegPressureTracker(IntervalPressure &rp) :
00273     MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
00274     RequireIntervals(true), TrackUntiedDefs(false) {}
00275 
00276   RegPressureTracker(RegionPressure &rp) :
00277     MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
00278     RequireIntervals(false), TrackUntiedDefs(false) {}
00279 
00280   void reset();
00281 
00282   void init(const MachineFunction *mf, const RegisterClassInfo *rci,
00283             const LiveIntervals *lis, const MachineBasicBlock *mbb,
00284             MachineBasicBlock::const_iterator pos,
00285             bool ShouldTrackUntiedDefs = false);
00286 
00287   /// Force liveness of virtual registers or physical register
00288   /// units. Particularly useful to initialize the livein/out state of the
00289   /// tracker before the first call to advance/recede.
00290   void addLiveRegs(ArrayRef<unsigned> Regs);
00291 
00292   /// Get the MI position corresponding to this register pressure.
00293   MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
00294 
00295   // Reset the MI position corresponding to the register pressure. This allows
00296   // schedulers to move instructions above the RegPressureTracker's
00297   // CurrPos. Since the pressure is computed before CurrPos, the iterator
00298   // position changes while pressure does not.
00299   void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
00300 
00301   /// \brief Get the SlotIndex for the first nondebug instruction including or
00302   /// after the current position.
00303   SlotIndex getCurrSlot() const;
00304 
00305   /// Recede across the previous instruction.
00306   bool recede(SmallVectorImpl<unsigned> *LiveUses = nullptr,
00307               PressureDiff *PDiff = nullptr);
00308 
00309   /// Advance across the current instruction.
00310   bool advance();
00311 
00312   /// Finalize the region boundaries and recored live ins and live outs.
00313   void closeRegion();
00314 
00315   /// Initialize the LiveThru pressure set based on the untied defs found in
00316   /// RPTracker.
00317   void initLiveThru(const RegPressureTracker &RPTracker);
00318 
00319   /// Copy an existing live thru pressure result.
00320   void initLiveThru(ArrayRef<unsigned> PressureSet) {
00321     LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
00322   }
00323 
00324   ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
00325 
00326   /// Get the resulting register pressure over the traversed region.
00327   /// This result is complete if either advance() or recede() has returned true,
00328   /// or if closeRegion() was explicitly invoked.
00329   RegisterPressure &getPressure() { return P; }
00330   const RegisterPressure &getPressure() const { return P; }
00331 
00332   /// Get the register set pressure at the current position, which may be less
00333   /// than the pressure across the traversed region.
00334   std::vector<unsigned> &getRegSetPressureAtPos() { return CurrSetPressure; }
00335 
00336   void discoverLiveOut(unsigned Reg);
00337   void discoverLiveIn(unsigned Reg);
00338 
00339   bool isTopClosed() const;
00340   bool isBottomClosed() const;
00341 
00342   void closeTop();
00343   void closeBottom();
00344 
00345   /// Consider the pressure increase caused by traversing this instruction
00346   /// bottom-up. Find the pressure set with the most change beyond its pressure
00347   /// limit based on the tracker's current pressure, and record the number of
00348   /// excess register units of that pressure set introduced by this instruction.
00349   void getMaxUpwardPressureDelta(const MachineInstr *MI,
00350                                  PressureDiff *PDiff,
00351                                  RegPressureDelta &Delta,
00352                                  ArrayRef<PressureChange> CriticalPSets,
00353                                  ArrayRef<unsigned> MaxPressureLimit);
00354 
00355   void getUpwardPressureDelta(const MachineInstr *MI,
00356                               /*const*/ PressureDiff &PDiff,
00357                               RegPressureDelta &Delta,
00358                               ArrayRef<PressureChange> CriticalPSets,
00359                               ArrayRef<unsigned> MaxPressureLimit) const;
00360 
00361   /// Consider the pressure increase caused by traversing this instruction
00362   /// top-down. Find the pressure set with the most change beyond its pressure
00363   /// limit based on the tracker's current pressure, and record the number of
00364   /// excess register units of that pressure set introduced by this instruction.
00365   void getMaxDownwardPressureDelta(const MachineInstr *MI,
00366                                    RegPressureDelta &Delta,
00367                                    ArrayRef<PressureChange> CriticalPSets,
00368                                    ArrayRef<unsigned> MaxPressureLimit);
00369 
00370   /// Find the pressure set with the most change beyond its pressure limit after
00371   /// traversing this instruction either upward or downward depending on the
00372   /// closed end of the current region.
00373   void getMaxPressureDelta(const MachineInstr *MI,
00374                            RegPressureDelta &Delta,
00375                            ArrayRef<PressureChange> CriticalPSets,
00376                            ArrayRef<unsigned> MaxPressureLimit) {
00377     if (isTopClosed())
00378       return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
00379                                          MaxPressureLimit);
00380 
00381     assert(isBottomClosed() && "Uninitialized pressure tracker");
00382     return getMaxUpwardPressureDelta(MI, nullptr, Delta, CriticalPSets,
00383                                      MaxPressureLimit);
00384   }
00385 
00386   /// Get the pressure of each PSet after traversing this instruction bottom-up.
00387   void getUpwardPressure(const MachineInstr *MI,
00388                          std::vector<unsigned> &PressureResult,
00389                          std::vector<unsigned> &MaxPressureResult);
00390 
00391   /// Get the pressure of each PSet after traversing this instruction top-down.
00392   void getDownwardPressure(const MachineInstr *MI,
00393                            std::vector<unsigned> &PressureResult,
00394                            std::vector<unsigned> &MaxPressureResult);
00395 
00396   void getPressureAfterInst(const MachineInstr *MI,
00397                             std::vector<unsigned> &PressureResult,
00398                             std::vector<unsigned> &MaxPressureResult) {
00399     if (isTopClosed())
00400       return getUpwardPressure(MI, PressureResult, MaxPressureResult);
00401 
00402     assert(isBottomClosed() && "Uninitialized pressure tracker");
00403     return getDownwardPressure(MI, PressureResult, MaxPressureResult);
00404   }
00405 
00406   bool hasUntiedDef(unsigned VirtReg) const {
00407     return UntiedDefs.count(VirtReg);
00408   }
00409 
00410   void dump() const;
00411 
00412 protected:
00413   const LiveRange *getLiveRange(unsigned Reg) const;
00414 
00415   void increaseRegPressure(ArrayRef<unsigned> Regs);
00416   void decreaseRegPressure(ArrayRef<unsigned> Regs);
00417 
00418   void bumpUpwardPressure(const MachineInstr *MI);
00419   void bumpDownwardPressure(const MachineInstr *MI);
00420 };
00421 
00422 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
00423                         const TargetRegisterInfo *TRI);
00424 } // end namespace llvm
00425 
00426 #endif