RegisterPressure.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. //===-- RegisterPressure.h - Dynamic Register Pressure -*- C++ -*-------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the RegisterPressure class which can be used to track
  11. // MachineInstr level register pressure.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_CODEGEN_REGISTERPRESSURE_H
  15. #define LLVM_CODEGEN_REGISTERPRESSURE_H
  16. #include "llvm/ADT/SparseSet.h"
  17. #include "llvm/CodeGen/SlotIndexes.h"
  18. #include "llvm/Target/TargetRegisterInfo.h"
  19. namespace llvm {
  20. class LiveIntervals;
  21. class LiveRange;
  22. class RegisterClassInfo;
  23. class MachineInstr;
  24. /// Base class for register pressure results.
  25. struct RegisterPressure {
  26. /// Map of max reg pressure indexed by pressure set ID, not class ID.
  27. std::vector<unsigned> MaxSetPressure;
  28. /// List of live in virtual registers or physical register units.
  29. SmallVector<unsigned,8> LiveInRegs;
  30. SmallVector<unsigned,8> LiveOutRegs;
  31. void dump(const TargetRegisterInfo *TRI) const;
  32. };
  33. /// RegisterPressure computed within a region of instructions delimited by
  34. /// TopIdx and BottomIdx. During pressure computation, the maximum pressure per
  35. /// register pressure set is increased. Once pressure within a region is fully
  36. /// computed, the live-in and live-out sets are recorded.
  37. ///
  38. /// This is preferable to RegionPressure when LiveIntervals are available,
  39. /// because delimiting regions by SlotIndex is more robust and convenient than
  40. /// holding block iterators. The block contents can change without invalidating
  41. /// the pressure result.
  42. struct IntervalPressure : RegisterPressure {
  43. /// Record the boundary of the region being tracked.
  44. SlotIndex TopIdx;
  45. SlotIndex BottomIdx;
  46. void reset();
  47. void openTop(SlotIndex NextTop);
  48. void openBottom(SlotIndex PrevBottom);
  49. };
  50. /// RegisterPressure computed within a region of instructions delimited by
  51. /// TopPos and BottomPos. This is a less precise version of IntervalPressure for
  52. /// use when LiveIntervals are unavailable.
  53. struct RegionPressure : RegisterPressure {
  54. /// Record the boundary of the region being tracked.
  55. MachineBasicBlock::const_iterator TopPos;
  56. MachineBasicBlock::const_iterator BottomPos;
  57. void reset();
  58. void openTop(MachineBasicBlock::const_iterator PrevTop);
  59. void openBottom(MachineBasicBlock::const_iterator PrevBottom);
  60. };
  61. /// Capture a change in pressure for a single pressure set. UnitInc may be
  62. /// expressed in terms of upward or downward pressure depending on the client
  63. /// and will be dynamically adjusted for current liveness.
  64. ///
  65. /// Pressure increments are tiny, typically 1-2 units, and this is only for
  66. /// heuristics, so we don't check UnitInc overflow. Instead, we may have a
  67. /// higher level assert that pressure is consistent within a region. We also
  68. /// effectively ignore dead defs which don't affect heuristics much.
  69. class PressureChange {
  70. uint16_t PSetID; // ID+1. 0=Invalid.
  71. int16_t UnitInc;
  72. public:
  73. PressureChange(): PSetID(0), UnitInc(0) {}
  74. PressureChange(unsigned id): PSetID(id+1), UnitInc(0) {
  75. assert(id < UINT16_MAX && "PSetID overflow.");
  76. }
  77. bool isValid() const { return PSetID > 0; }
  78. unsigned getPSet() const {
  79. assert(isValid() && "invalid PressureChange");
  80. return PSetID - 1;
  81. }
  82. // If PSetID is invalid, return UINT16_MAX to give it lowest priority.
  83. unsigned getPSetOrMax() const { return (PSetID - 1) & UINT16_MAX; }
  84. int getUnitInc() const { return UnitInc; }
  85. void setUnitInc(int Inc) { UnitInc = Inc; }
  86. bool operator==(const PressureChange &RHS) const {
  87. return PSetID == RHS.PSetID && UnitInc == RHS.UnitInc;
  88. }
  89. };
  90. template <> struct isPodLike<PressureChange> {
  91. static const bool value = true;
  92. };
  93. /// List of PressureChanges in order of increasing, unique PSetID.
  94. ///
  95. /// Use a small fixed number, because we can fit more PressureChanges in an
  96. /// empty SmallVector than ever need to be tracked per register class. If more
  97. /// PSets are affected, then we only track the most constrained.
  98. class PressureDiff {
  99. // The initial design was for MaxPSets=4, but that requires PSet partitions,
  100. // which are not yet implemented. (PSet partitions are equivalent PSets given
  101. // the register classes actually in use within the scheduling region.)
  102. enum { MaxPSets = 16 };
  103. PressureChange PressureChanges[MaxPSets];
  104. public:
  105. typedef PressureChange* iterator;
  106. typedef const PressureChange* const_iterator;
  107. iterator begin() { return &PressureChanges[0]; }
  108. iterator end() { return &PressureChanges[MaxPSets]; }
  109. const_iterator begin() const { return &PressureChanges[0]; }
  110. const_iterator end() const { return &PressureChanges[MaxPSets]; }
  111. void addPressureChange(unsigned RegUnit, bool IsDec,
  112. const MachineRegisterInfo *MRI);
  113. LLVM_DUMP_METHOD void dump(const TargetRegisterInfo &TRI) const;
  114. };
  115. /// Array of PressureDiffs.
  116. class PressureDiffs {
  117. PressureDiff *PDiffArray;
  118. unsigned Size;
  119. unsigned Max;
  120. public:
  121. PressureDiffs(): PDiffArray(nullptr), Size(0), Max(0) {}
  122. ~PressureDiffs() { free(PDiffArray); }
  123. void clear() { Size = 0; }
  124. void init(unsigned N);
  125. PressureDiff &operator[](unsigned Idx) {
  126. assert(Idx < Size && "PressureDiff index out of bounds");
  127. return PDiffArray[Idx];
  128. }
  129. const PressureDiff &operator[](unsigned Idx) const {
  130. return const_cast<PressureDiffs*>(this)->operator[](Idx);
  131. }
  132. };
  133. /// Store the effects of a change in pressure on things that MI scheduler cares
  134. /// about.
  135. ///
  136. /// Excess records the value of the largest difference in register units beyond
  137. /// the target's pressure limits across the affected pressure sets, where
  138. /// largest is defined as the absolute value of the difference. Negative
  139. /// ExcessUnits indicates a reduction in pressure that had already exceeded the
  140. /// target's limits.
  141. ///
  142. /// CriticalMax records the largest increase in the tracker's max pressure that
  143. /// exceeds the critical limit for some pressure set determined by the client.
  144. ///
  145. /// CurrentMax records the largest increase in the tracker's max pressure that
  146. /// exceeds the current limit for some pressure set determined by the client.
  147. struct RegPressureDelta {
  148. PressureChange Excess;
  149. PressureChange CriticalMax;
  150. PressureChange CurrentMax;
  151. RegPressureDelta() {}
  152. bool operator==(const RegPressureDelta &RHS) const {
  153. return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
  154. && CurrentMax == RHS.CurrentMax;
  155. }
  156. bool operator!=(const RegPressureDelta &RHS) const {
  157. return !operator==(RHS);
  158. }
  159. };
  160. /// \brief A set of live virtual registers and physical register units.
  161. ///
  162. /// Virtual and physical register numbers require separate sparse sets, but most
  163. /// of the RegisterPressureTracker handles them uniformly.
  164. struct LiveRegSet {
  165. SparseSet<unsigned> PhysRegs;
  166. SparseSet<unsigned, VirtReg2IndexFunctor> VirtRegs;
  167. bool contains(unsigned Reg) const {
  168. if (TargetRegisterInfo::isVirtualRegister(Reg))
  169. return VirtRegs.count(Reg);
  170. return PhysRegs.count(Reg);
  171. }
  172. bool insert(unsigned Reg) {
  173. if (TargetRegisterInfo::isVirtualRegister(Reg))
  174. return VirtRegs.insert(Reg).second;
  175. return PhysRegs.insert(Reg).second;
  176. }
  177. bool erase(unsigned Reg) {
  178. if (TargetRegisterInfo::isVirtualRegister(Reg))
  179. return VirtRegs.erase(Reg);
  180. return PhysRegs.erase(Reg);
  181. }
  182. };
  183. /// Track the current register pressure at some position in the instruction
  184. /// stream, and remember the high water mark within the region traversed. This
  185. /// does not automatically consider live-through ranges. The client may
  186. /// independently adjust for global liveness.
  187. ///
  188. /// Each RegPressureTracker only works within a MachineBasicBlock. Pressure can
  189. /// be tracked across a larger region by storing a RegisterPressure result at
  190. /// each block boundary and explicitly adjusting pressure to account for block
  191. /// live-in and live-out register sets.
  192. ///
  193. /// RegPressureTracker holds a reference to a RegisterPressure result that it
  194. /// computes incrementally. During downward tracking, P.BottomIdx or P.BottomPos
  195. /// is invalid until it reaches the end of the block or closeRegion() is
  196. /// explicitly called. Similarly, P.TopIdx is invalid during upward
  197. /// tracking. Changing direction has the side effect of closing region, and
  198. /// traversing past TopIdx or BottomIdx reopens it.
  199. class RegPressureTracker {
  200. const MachineFunction *MF;
  201. const TargetRegisterInfo *TRI;
  202. const RegisterClassInfo *RCI;
  203. const MachineRegisterInfo *MRI;
  204. const LiveIntervals *LIS;
  205. /// We currently only allow pressure tracking within a block.
  206. const MachineBasicBlock *MBB;
  207. /// Track the max pressure within the region traversed so far.
  208. RegisterPressure &P;
  209. /// Run in two modes dependending on whether constructed with IntervalPressure
  210. /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
  211. bool RequireIntervals;
  212. /// True if UntiedDefs will be populated.
  213. bool TrackUntiedDefs;
  214. /// Register pressure corresponds to liveness before this instruction
  215. /// iterator. It may point to the end of the block or a DebugValue rather than
  216. /// an instruction.
  217. MachineBasicBlock::const_iterator CurrPos;
  218. /// Pressure map indexed by pressure set ID, not class ID.
  219. std::vector<unsigned> CurrSetPressure;
  220. /// Set of live registers.
  221. LiveRegSet LiveRegs;
  222. /// Set of vreg defs that start a live range.
  223. SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
  224. /// Live-through pressure.
  225. std::vector<unsigned> LiveThruPressure;
  226. public:
  227. RegPressureTracker(IntervalPressure &rp) :
  228. MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
  229. RequireIntervals(true), TrackUntiedDefs(false) {}
  230. RegPressureTracker(RegionPressure &rp) :
  231. MF(nullptr), TRI(nullptr), RCI(nullptr), LIS(nullptr), MBB(nullptr), P(rp),
  232. RequireIntervals(false), TrackUntiedDefs(false) {}
  233. void reset();
  234. void init(const MachineFunction *mf, const RegisterClassInfo *rci,
  235. const LiveIntervals *lis, const MachineBasicBlock *mbb,
  236. MachineBasicBlock::const_iterator pos,
  237. bool ShouldTrackUntiedDefs = false);
  238. /// Force liveness of virtual registers or physical register
  239. /// units. Particularly useful to initialize the livein/out state of the
  240. /// tracker before the first call to advance/recede.
  241. void addLiveRegs(ArrayRef<unsigned> Regs);
  242. /// Get the MI position corresponding to this register pressure.
  243. MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
  244. // Reset the MI position corresponding to the register pressure. This allows
  245. // schedulers to move instructions above the RegPressureTracker's
  246. // CurrPos. Since the pressure is computed before CurrPos, the iterator
  247. // position changes while pressure does not.
  248. void setPos(MachineBasicBlock::const_iterator Pos) { CurrPos = Pos; }
  249. /// \brief Get the SlotIndex for the first nondebug instruction including or
  250. /// after the current position.
  251. SlotIndex getCurrSlot() const;
  252. /// Recede across the previous instruction.
  253. bool recede(SmallVectorImpl<unsigned> *LiveUses = nullptr,
  254. PressureDiff *PDiff = nullptr);
  255. /// Advance across the current instruction.
  256. bool advance();
  257. /// Finalize the region boundaries and recored live ins and live outs.
  258. void closeRegion();
  259. /// Initialize the LiveThru pressure set based on the untied defs found in
  260. /// RPTracker.
  261. void initLiveThru(const RegPressureTracker &RPTracker);
  262. /// Copy an existing live thru pressure result.
  263. void initLiveThru(ArrayRef<unsigned> PressureSet) {
  264. LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
  265. }
  266. ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
  267. /// Get the resulting register pressure over the traversed region.
  268. /// This result is complete if either advance() or recede() has returned true,
  269. /// or if closeRegion() was explicitly invoked.
  270. RegisterPressure &getPressure() { return P; }
  271. const RegisterPressure &getPressure() const { return P; }
  272. /// Get the register set pressure at the current position, which may be less
  273. /// than the pressure across the traversed region.
  274. std::vector<unsigned> &getRegSetPressureAtPos() { return CurrSetPressure; }
  275. void discoverLiveOut(unsigned Reg);
  276. void discoverLiveIn(unsigned Reg);
  277. bool isTopClosed() const;
  278. bool isBottomClosed() const;
  279. void closeTop();
  280. void closeBottom();
  281. /// Consider the pressure increase caused by traversing this instruction
  282. /// bottom-up. Find the pressure set with the most change beyond its pressure
  283. /// limit based on the tracker's current pressure, and record the number of
  284. /// excess register units of that pressure set introduced by this instruction.
  285. void getMaxUpwardPressureDelta(const MachineInstr *MI,
  286. PressureDiff *PDiff,
  287. RegPressureDelta &Delta,
  288. ArrayRef<PressureChange> CriticalPSets,
  289. ArrayRef<unsigned> MaxPressureLimit);
  290. void getUpwardPressureDelta(const MachineInstr *MI,
  291. /*const*/ PressureDiff &PDiff,
  292. RegPressureDelta &Delta,
  293. ArrayRef<PressureChange> CriticalPSets,
  294. ArrayRef<unsigned> MaxPressureLimit) const;
  295. /// Consider the pressure increase caused by traversing this instruction
  296. /// top-down. Find the pressure set with the most change beyond its pressure
  297. /// limit based on the tracker's current pressure, and record the number of
  298. /// excess register units of that pressure set introduced by this instruction.
  299. void getMaxDownwardPressureDelta(const MachineInstr *MI,
  300. RegPressureDelta &Delta,
  301. ArrayRef<PressureChange> CriticalPSets,
  302. ArrayRef<unsigned> MaxPressureLimit);
  303. /// Find the pressure set with the most change beyond its pressure limit after
  304. /// traversing this instruction either upward or downward depending on the
  305. /// closed end of the current region.
  306. void getMaxPressureDelta(const MachineInstr *MI,
  307. RegPressureDelta &Delta,
  308. ArrayRef<PressureChange> CriticalPSets,
  309. ArrayRef<unsigned> MaxPressureLimit) {
  310. if (isTopClosed())
  311. return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
  312. MaxPressureLimit);
  313. assert(isBottomClosed() && "Uninitialized pressure tracker");
  314. return getMaxUpwardPressureDelta(MI, nullptr, Delta, CriticalPSets,
  315. MaxPressureLimit);
  316. }
  317. /// Get the pressure of each PSet after traversing this instruction bottom-up.
  318. void getUpwardPressure(const MachineInstr *MI,
  319. std::vector<unsigned> &PressureResult,
  320. std::vector<unsigned> &MaxPressureResult);
  321. /// Get the pressure of each PSet after traversing this instruction top-down.
  322. void getDownwardPressure(const MachineInstr *MI,
  323. std::vector<unsigned> &PressureResult,
  324. std::vector<unsigned> &MaxPressureResult);
  325. void getPressureAfterInst(const MachineInstr *MI,
  326. std::vector<unsigned> &PressureResult,
  327. std::vector<unsigned> &MaxPressureResult) {
  328. if (isTopClosed())
  329. return getUpwardPressure(MI, PressureResult, MaxPressureResult);
  330. assert(isBottomClosed() && "Uninitialized pressure tracker");
  331. return getDownwardPressure(MI, PressureResult, MaxPressureResult);
  332. }
  333. bool hasUntiedDef(unsigned VirtReg) const {
  334. return UntiedDefs.count(VirtReg);
  335. }
  336. void dump() const;
  337. protected:
  338. const LiveRange *getLiveRange(unsigned Reg) const;
  339. void increaseRegPressure(ArrayRef<unsigned> Regs);
  340. void decreaseRegPressure(ArrayRef<unsigned> Regs);
  341. void bumpUpwardPressure(const MachineInstr *MI);
  342. void bumpDownwardPressure(const MachineInstr *MI);
  343. };
  344. void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
  345. const TargetRegisterInfo *TRI);
  346. } // end namespace llvm
  347. #endif