mi-sched: update PressureDiffs on-the-fly for liveness.
[oota-llvm.git] / include / llvm / CodeGen / RegisterPressure.h
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
15 #ifndef LLVM_CODEGEN_REGISTERPRESSURE_H
16 #define LLVM_CODEGEN_REGISTERPRESSURE_H
17
18 #include "llvm/ADT/SparseSet.h"
19 #include "llvm/CodeGen/SlotIndexes.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21
22 namespace llvm {
23
24 class LiveIntervals;
25 class LiveInterval;
26 class RegisterClassInfo;
27 class MachineInstr;
28
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;
33
34   /// List of live in virtual registers or physical register units.
35   SmallVector<unsigned,8> LiveInRegs;
36   SmallVector<unsigned,8> LiveOutRegs;
37
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).
41   ///
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);
45
46   /// Decrease register pressure for each pressure set impacted by this register
47   /// class. This is only useful to account for spilling or rematerialization.
48   ///
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);
52
53   void dump(const TargetRegisterInfo *TRI) const;
54 };
55
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.
60 ///
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.
67   SlotIndex TopIdx;
68   SlotIndex BottomIdx;
69
70   void reset();
71
72   void openTop(SlotIndex NextTop);
73
74   void openBottom(SlotIndex PrevBottom);
75 };
76
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;
84
85   void reset();
86
87   void openTop(MachineBasicBlock::const_iterator PrevTop);
88
89   void openBottom(MachineBasicBlock::const_iterator PrevBottom);
90 };
91
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.
95 ///
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.
102   int16_t  UnitInc;
103 public:
104   PressureChange(): PSetID(0), UnitInc(0) {}
105   PressureChange(unsigned id): PSetID(id+1), UnitInc(0) {
106     assert(id < UINT16_MAX && "PSetID overflow.");
107   }
108
109   bool isValid() const { return PSetID > 0; }
110
111   unsigned getPSet() const {
112     assert(isValid() && "invalid PressureChange");
113     return PSetID - 1;
114   }
115   // If PSetID is invalid, return UINT16_MAX to give it lowest priority.
116   unsigned getPSetOrMax() const { return (PSetID - 1) & UINT16_MAX; }
117
118   int getUnitInc() const { return UnitInc; }
119
120   void setUnitInc(int Inc) { UnitInc = Inc; }
121
122   bool operator==(const PressureChange &RHS) const {
123     return PSetID == RHS.PSetID && UnitInc == RHS.UnitInc;
124   }
125 };
126
127 template <> struct isPodLike<PressureChange> {
128    static const bool value = true;
129 };
130
131 /// List of PressureChanges in order of increasing, unique PSetID.
132 ///
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.
136 class PressureDiff {
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 };
141
142   PressureChange PressureChanges[MaxPSets];
143 public:
144   typedef PressureChange* iterator;
145   typedef const PressureChange* const_iterator;
146   iterator begin() { return &PressureChanges[0]; }
147   iterator end() { return &PressureChanges[MaxPSets]; }
148
149   void addPressureChange(unsigned RegUnit, bool IsDec,
150                          const MachineRegisterInfo *MRI);
151 };
152
153 /// Array of PressureDiffs.
154 class PressureDiffs {
155   PressureDiff *PDiffArray;
156   unsigned Size;
157   unsigned Max;
158 public:
159   PressureDiffs(): PDiffArray(0), Size(0), Max(0) {}
160
161   void init(unsigned N);
162
163   PressureDiff &operator[](unsigned Idx) {
164     assert(Idx < Size && "PressureDiff index out of bounds");
165     return PDiffArray[Idx];
166   }
167   const PressureDiff &operator[](unsigned Idx) const {
168     return const_cast<PressureDiffs*>(this)->operator[](Idx);
169   }
170 };
171
172 /// Store the effects of a change in pressure on things that MI scheduler cares
173 /// about.
174 ///
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
179 /// target's limits.
180 ///
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.
183 ///
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;
190
191   RegPressureDelta() {}
192
193   bool operator==(const RegPressureDelta &RHS) const {
194     return Excess == RHS.Excess && CriticalMax == RHS.CriticalMax
195       && CurrentMax == RHS.CurrentMax;
196   }
197   bool operator!=(const RegPressureDelta &RHS) const {
198     return !operator==(RHS);
199   }
200 };
201
202 /// \brief A set of live virtual registers and physical register units.
203 ///
204 /// Virtual and physical register numbers require separate sparse sets, but most
205 /// of the RegisterPressureTracker handles them uniformly.
206 struct LiveRegSet {
207   SparseSet<unsigned> PhysRegs;
208   SparseSet<unsigned, VirtReg2IndexFunctor> VirtRegs;
209
210   bool contains(unsigned Reg) const {
211     if (TargetRegisterInfo::isVirtualRegister(Reg))
212       return VirtRegs.count(Reg);
213     return PhysRegs.count(Reg);
214   }
215
216   bool insert(unsigned Reg) {
217     if (TargetRegisterInfo::isVirtualRegister(Reg))
218       return VirtRegs.insert(Reg).second;
219     return PhysRegs.insert(Reg).second;
220   }
221
222   bool erase(unsigned Reg) {
223     if (TargetRegisterInfo::isVirtualRegister(Reg))
224       return VirtRegs.erase(Reg);
225     return PhysRegs.erase(Reg);
226   }
227 };
228
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.
233 ///
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.
238 ///
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;
251
252   /// We currently only allow pressure tracking within a block.
253   const MachineBasicBlock *MBB;
254
255   /// Track the max pressure within the region traversed so far.
256   RegisterPressure &P;
257
258   /// Run in two modes dependending on whether constructed with IntervalPressure
259   /// or RegisterPressure. If requireIntervals is false, LIS are ignored.
260   bool RequireIntervals;
261
262   /// True if UntiedDefs will be populated.
263   bool TrackUntiedDefs;
264
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
267   /// an instruction.
268   MachineBasicBlock::const_iterator CurrPos;
269
270   /// Pressure map indexed by pressure set ID, not class ID.
271   std::vector<unsigned> CurrSetPressure;
272
273   /// Set of live registers.
274   LiveRegSet LiveRegs;
275
276   /// Set of vreg defs that start a live range.
277   SparseSet<unsigned, VirtReg2IndexFunctor> UntiedDefs;
278   /// Live-through pressure.
279   std::vector<unsigned> LiveThruPressure;
280
281 public:
282   RegPressureTracker(IntervalPressure &rp) :
283     MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(true),
284     TrackUntiedDefs(false) {}
285
286   RegPressureTracker(RegionPressure &rp) :
287     MF(0), TRI(0), RCI(0), LIS(0), MBB(0), P(rp), RequireIntervals(false),
288     TrackUntiedDefs(false) {}
289
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);
294
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);
299
300   /// Get the MI position corresponding to this register pressure.
301   MachineBasicBlock::const_iterator getPos() const { return CurrPos; }
302
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; }
308
309   /// \brief Get the SlotIndex for the first nondebug instruction including or
310   /// after the current position.
311   SlotIndex getCurrSlot() const;
312
313   /// Recede across the previous instruction.
314   bool recede(SmallVectorImpl<unsigned> *LiveUses = 0, PressureDiff *PDiff = 0);
315
316   /// Advance across the current instruction.
317   bool advance();
318
319   /// Finalize the region boundaries and recored live ins and live outs.
320   void closeRegion();
321
322   /// Initialize the LiveThru pressure set based on the untied defs found in
323   /// RPTracker.
324   void initLiveThru(const RegPressureTracker &RPTracker);
325
326   /// Copy an existing live thru pressure result.
327   void initLiveThru(ArrayRef<unsigned> PressureSet) {
328     LiveThruPressure.assign(PressureSet.begin(), PressureSet.end());
329   }
330
331   ArrayRef<unsigned> getLiveThru() const { return LiveThruPressure; }
332
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; }
338
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; }
342
343   void discoverLiveOut(unsigned Reg);
344   void discoverLiveIn(unsigned Reg);
345
346   bool isTopClosed() const;
347   bool isBottomClosed() const;
348
349   void closeTop();
350   void closeBottom();
351
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,
357                                  PressureDiff *PDiff,
358                                  RegPressureDelta &Delta,
359                                  ArrayRef<PressureChange> CriticalPSets,
360                                  ArrayRef<unsigned> MaxPressureLimit);
361
362   void getUpwardPressureDelta(const MachineInstr *MI,
363                               /*const*/ PressureDiff &PDiff,
364                               RegPressureDelta &Delta,
365                               ArrayRef<PressureChange> CriticalPSets,
366                               ArrayRef<unsigned> MaxPressureLimit) const;
367
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);
376
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) {
384     if (isTopClosed())
385       return getMaxDownwardPressureDelta(MI, Delta, CriticalPSets,
386                                          MaxPressureLimit);
387
388     assert(isBottomClosed() && "Uninitialized pressure tracker");
389     return getMaxUpwardPressureDelta(MI, 0, Delta, CriticalPSets,
390                                      MaxPressureLimit);
391   }
392
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);
397
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);
402
403   void getPressureAfterInst(const MachineInstr *MI,
404                             std::vector<unsigned> &PressureResult,
405                             std::vector<unsigned> &MaxPressureResult) {
406     if (isTopClosed())
407       return getUpwardPressure(MI, PressureResult, MaxPressureResult);
408
409     assert(isBottomClosed() && "Uninitialized pressure tracker");
410     return getDownwardPressure(MI, PressureResult, MaxPressureResult);
411   }
412
413   bool hasUntiedDef(unsigned VirtReg) const {
414     return UntiedDefs.count(VirtReg);
415   }
416
417   void dump() const;
418
419 protected:
420   const LiveInterval *getInterval(unsigned Reg) const;
421
422   void increaseRegPressure(ArrayRef<unsigned> Regs);
423   void decreaseRegPressure(ArrayRef<unsigned> Regs);
424
425   void bumpUpwardPressure(const MachineInstr *MI);
426   void bumpDownwardPressure(const MachineInstr *MI);
427 };
428
429 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
430 void dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
431                         const TargetRegisterInfo *TRI);
432 #endif
433 } // end namespace llvm
434
435 #endif