1//===-- RegisterPressure.cpp - Dynamic Register Pressure ------------------===//
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 implements the RegisterPressure class which can be used to track
11// MachineInstr level register pressure.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/RegisterPressure.h"
16#include "llvm/CodeGen/LiveInterval.h"
17#include "llvm/CodeGen/LiveIntervalAnalysis.h"
18#include "llvm/CodeGen/MachineRegisterInfo.h"
19#include "llvm/CodeGen/RegisterClassInfo.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/Support/raw_ostream.h"
22
23using namespace llvm;
24
25/// Increase pressure for each pressure set provided by TargetRegisterInfo.
26static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure,
27                                PSetIterator PSetI) {
28  unsigned Weight = PSetI.getWeight();
29  for (; PSetI.isValid(); ++PSetI)
30    CurrSetPressure[*PSetI] += Weight;
31}
32
33/// Decrease pressure for each pressure set provided by TargetRegisterInfo.
34static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure,
35                                PSetIterator PSetI) {
36  unsigned Weight = PSetI.getWeight();
37  for (; PSetI.isValid(); ++PSetI) {
38    assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow");
39    CurrSetPressure[*PSetI] -= Weight;
40  }
41}
42
43LLVM_DUMP_METHOD
44void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
45                              const TargetRegisterInfo *TRI) {
46  bool Empty = true;
47  for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) {
48    if (SetPressure[i] != 0) {
49      dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << '\n';
50      Empty = false;
51    }
52  }
53  if (Empty)
54    dbgs() << "\n";
55}
56
57LLVM_DUMP_METHOD
58void RegisterPressure::dump(const TargetRegisterInfo *TRI) const {
59  dbgs() << "Max Pressure: ";
60  dumpRegSetPressure(MaxSetPressure, TRI);
61  dbgs() << "Live In: ";
62  for (unsigned i = 0, e = LiveInRegs.size(); i < e; ++i)
63    dbgs() << PrintReg(LiveInRegs[i], TRI) << " ";
64  dbgs() << '\n';
65  dbgs() << "Live Out: ";
66  for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i)
67    dbgs() << PrintReg(LiveOutRegs[i], TRI) << " ";
68  dbgs() << '\n';
69}
70
71LLVM_DUMP_METHOD
72void RegPressureTracker::dump() const {
73  if (!isTopClosed() || !isBottomClosed()) {
74    dbgs() << "Curr Pressure: ";
75    dumpRegSetPressure(CurrSetPressure, TRI);
76  }
77  P.dump(TRI);
78}
79
80/// Increase the current pressure as impacted by these registers and bump
81/// the high water mark if needed.
82void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) {
83  for (unsigned i = 0, e = RegUnits.size(); i != e; ++i) {
84    PSetIterator PSetI = MRI->getPressureSets(RegUnits[i]);
85    unsigned Weight = PSetI.getWeight();
86    for (; PSetI.isValid(); ++PSetI) {
87      CurrSetPressure[*PSetI] += Weight;
88      if (CurrSetPressure[*PSetI] > P.MaxSetPressure[*PSetI]) {
89        P.MaxSetPressure[*PSetI] = CurrSetPressure[*PSetI];
90      }
91    }
92  }
93}
94
95/// Simply decrease the current pressure as impacted by these registers.
96void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) {
97  for (unsigned I = 0, E = RegUnits.size(); I != E; ++I)
98    decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnits[I]));
99}
100
101/// Clear the result so it can be used for another round of pressure tracking.
102void IntervalPressure::reset() {
103  TopIdx = BottomIdx = SlotIndex();
104  MaxSetPressure.clear();
105  LiveInRegs.clear();
106  LiveOutRegs.clear();
107}
108
109/// Clear the result so it can be used for another round of pressure tracking.
110void RegionPressure::reset() {
111  TopPos = BottomPos = MachineBasicBlock::const_iterator();
112  MaxSetPressure.clear();
113  LiveInRegs.clear();
114  LiveOutRegs.clear();
115}
116
117/// If the current top is not less than or equal to the next index, open it.
118/// We happen to need the SlotIndex for the next top for pressure update.
119void IntervalPressure::openTop(SlotIndex NextTop) {
120  if (TopIdx <= NextTop)
121    return;
122  TopIdx = SlotIndex();
123  LiveInRegs.clear();
124}
125
126/// If the current top is the previous instruction (before receding), open it.
127void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
128  if (TopPos != PrevTop)
129    return;
130  TopPos = MachineBasicBlock::const_iterator();
131  LiveInRegs.clear();
132}
133
134/// If the current bottom is not greater than the previous index, open it.
135void IntervalPressure::openBottom(SlotIndex PrevBottom) {
136  if (BottomIdx > PrevBottom)
137    return;
138  BottomIdx = SlotIndex();
139  LiveInRegs.clear();
140}
141
142/// If the current bottom is the previous instr (before advancing), open it.
143void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
144  if (BottomPos != PrevBottom)
145    return;
146  BottomPos = MachineBasicBlock::const_iterator();
147  LiveInRegs.clear();
148}
149
150const LiveRange *RegPressureTracker::getLiveRange(unsigned Reg) const {
151  if (TargetRegisterInfo::isVirtualRegister(Reg))
152    return &LIS->getInterval(Reg);
153  return LIS->getCachedRegUnit(Reg);
154}
155
156void RegPressureTracker::reset() {
157  MBB = nullptr;
158  LIS = nullptr;
159
160  CurrSetPressure.clear();
161  LiveThruPressure.clear();
162  P.MaxSetPressure.clear();
163
164  if (RequireIntervals)
165    static_cast<IntervalPressure&>(P).reset();
166  else
167    static_cast<RegionPressure&>(P).reset();
168
169  LiveRegs.PhysRegs.clear();
170  LiveRegs.VirtRegs.clear();
171  UntiedDefs.clear();
172}
173
174/// Setup the RegPressureTracker.
175///
176/// TODO: Add support for pressure without LiveIntervals.
177void RegPressureTracker::init(const MachineFunction *mf,
178                              const RegisterClassInfo *rci,
179                              const LiveIntervals *lis,
180                              const MachineBasicBlock *mbb,
181                              MachineBasicBlock::const_iterator pos,
182                              bool ShouldTrackUntiedDefs)
183{
184  reset();
185
186  MF = mf;
187  TRI = MF->getSubtarget().getRegisterInfo();
188  RCI = rci;
189  MRI = &MF->getRegInfo();
190  MBB = mbb;
191  TrackUntiedDefs = ShouldTrackUntiedDefs;
192
193  if (RequireIntervals) {
194    assert(lis && "IntervalPressure requires LiveIntervals");
195    LIS = lis;
196  }
197
198  CurrPos = pos;
199  CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
200
201  P.MaxSetPressure = CurrSetPressure;
202
203  LiveRegs.PhysRegs.setUniverse(TRI->getNumRegs());
204  LiveRegs.VirtRegs.setUniverse(MRI->getNumVirtRegs());
205  if (TrackUntiedDefs)
206    UntiedDefs.setUniverse(MRI->getNumVirtRegs());
207}
208
209/// Does this pressure result have a valid top position and live ins.
210bool RegPressureTracker::isTopClosed() const {
211  if (RequireIntervals)
212    return static_cast<IntervalPressure&>(P).TopIdx.isValid();
213  return (static_cast<RegionPressure&>(P).TopPos ==
214          MachineBasicBlock::const_iterator());
215}
216
217/// Does this pressure result have a valid bottom position and live outs.
218bool RegPressureTracker::isBottomClosed() const {
219  if (RequireIntervals)
220    return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
221  return (static_cast<RegionPressure&>(P).BottomPos ==
222          MachineBasicBlock::const_iterator());
223}
224
225
226SlotIndex RegPressureTracker::getCurrSlot() const {
227  MachineBasicBlock::const_iterator IdxPos = CurrPos;
228  while (IdxPos != MBB->end() && IdxPos->isDebugValue())
229    ++IdxPos;
230  if (IdxPos == MBB->end())
231    return LIS->getMBBEndIdx(MBB);
232  return LIS->getInstructionIndex(IdxPos).getRegSlot();
233}
234
235/// Set the boundary for the top of the region and summarize live ins.
236void RegPressureTracker::closeTop() {
237  if (RequireIntervals)
238    static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
239  else
240    static_cast<RegionPressure&>(P).TopPos = CurrPos;
241
242  assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
243  P.LiveInRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
244  P.LiveInRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
245  for (SparseSet<unsigned>::const_iterator I =
246         LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
247    P.LiveInRegs.push_back(*I);
248  std::sort(P.LiveInRegs.begin(), P.LiveInRegs.end());
249  P.LiveInRegs.erase(std::unique(P.LiveInRegs.begin(), P.LiveInRegs.end()),
250                     P.LiveInRegs.end());
251}
252
253/// Set the boundary for the bottom of the region and summarize live outs.
254void RegPressureTracker::closeBottom() {
255  if (RequireIntervals)
256    static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
257  else
258    static_cast<RegionPressure&>(P).BottomPos = CurrPos;
259
260  assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
261  P.LiveOutRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
262  P.LiveOutRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
263  for (SparseSet<unsigned>::const_iterator I =
264         LiveRegs.VirtRegs.begin(), E = LiveRegs.VirtRegs.end(); I != E; ++I)
265    P.LiveOutRegs.push_back(*I);
266  std::sort(P.LiveOutRegs.begin(), P.LiveOutRegs.end());
267  P.LiveOutRegs.erase(std::unique(P.LiveOutRegs.begin(), P.LiveOutRegs.end()),
268                      P.LiveOutRegs.end());
269}
270
271/// Finalize the region boundaries and record live ins and live outs.
272void RegPressureTracker::closeRegion() {
273  if (!isTopClosed() && !isBottomClosed()) {
274    assert(LiveRegs.PhysRegs.empty() && LiveRegs.VirtRegs.empty() &&
275           "no region boundary");
276    return;
277  }
278  if (!isBottomClosed())
279    closeBottom();
280  else if (!isTopClosed())
281    closeTop();
282  // If both top and bottom are closed, do nothing.
283}
284
285/// The register tracker is unaware of global liveness so ignores normal
286/// live-thru ranges. However, two-address or coalesced chains can also lead
287/// to live ranges with no holes. Count these to inform heuristics that we
288/// can never drop below this pressure.
289void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
290  LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
291  assert(isBottomClosed() && "need bottom-up tracking to intialize.");
292  for (unsigned i = 0, e = P.LiveOutRegs.size(); i < e; ++i) {
293    unsigned Reg = P.LiveOutRegs[i];
294    if (TargetRegisterInfo::isVirtualRegister(Reg)
295        && !RPTracker.hasUntiedDef(Reg)) {
296      increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg));
297    }
298  }
299}
300
301/// \brief Convenient wrapper for checking membership in RegisterOperands.
302/// (std::count() doesn't have an early exit).
303static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
304  return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
305}
306
307namespace {
308/// Collect this instruction's unique uses and defs into SmallVectors for
309/// processing defs and uses in order.
310///
311/// FIXME: always ignore tied opers
312class RegisterOperands {
313  const TargetRegisterInfo *TRI;
314  const MachineRegisterInfo *MRI;
315  bool IgnoreDead;
316
317public:
318  SmallVector<unsigned, 8> Uses;
319  SmallVector<unsigned, 8> Defs;
320  SmallVector<unsigned, 8> DeadDefs;
321
322  RegisterOperands(const TargetRegisterInfo *tri,
323                   const MachineRegisterInfo *mri, bool ID = false):
324    TRI(tri), MRI(mri), IgnoreDead(ID) {}
325
326  /// Push this operand's register onto the correct vector.
327  void collect(const MachineOperand &MO) {
328    if (!MO.isReg() || !MO.getReg())
329      return;
330    if (MO.readsReg())
331      pushRegUnits(MO.getReg(), Uses);
332    if (MO.isDef()) {
333      if (MO.isDead()) {
334        if (!IgnoreDead)
335          pushRegUnits(MO.getReg(), DeadDefs);
336      }
337      else
338        pushRegUnits(MO.getReg(), Defs);
339    }
340  }
341
342protected:
343  void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
344    if (TargetRegisterInfo::isVirtualRegister(Reg)) {
345      if (containsReg(RegUnits, Reg))
346        return;
347      RegUnits.push_back(Reg);
348    }
349    else if (MRI->isAllocatable(Reg)) {
350      for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
351        if (containsReg(RegUnits, *Units))
352          continue;
353        RegUnits.push_back(*Units);
354      }
355    }
356  }
357};
358} // namespace
359
360/// Collect physical and virtual register operands.
361static void collectOperands(const MachineInstr *MI,
362                            RegisterOperands &RegOpers) {
363  for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
364    RegOpers.collect(*OperI);
365
366  // Remove redundant physreg dead defs.
367  SmallVectorImpl<unsigned>::iterator I =
368    std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
369                   std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
370  RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
371}
372
373/// Initialize an array of N PressureDiffs.
374void PressureDiffs::init(unsigned N) {
375  Size = N;
376  if (N <= Max) {
377    memset(PDiffArray, 0, N * sizeof(PressureDiff));
378    return;
379  }
380  Max = Size;
381  free(PDiffArray);
382  PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
383}
384
385/// Add a change in pressure to the pressure diff of a given instruction.
386void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
387                                     const MachineRegisterInfo *MRI) {
388  PSetIterator PSetI = MRI->getPressureSets(RegUnit);
389  int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
390  for (; PSetI.isValid(); ++PSetI) {
391    // Find an existing entry in the pressure diff for this PSet.
392    PressureDiff::iterator I = begin(), E = end();
393    for (; I != E && I->isValid(); ++I) {
394      if (I->getPSet() >= *PSetI)
395        break;
396    }
397    // If all pressure sets are more constrained, skip the remaining PSets.
398    if (I == E)
399      break;
400    // Insert this PressureChange.
401    if (!I->isValid() || I->getPSet() != *PSetI) {
402      PressureChange PTmp = PressureChange(*PSetI);
403      for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
404        std::swap(*J,PTmp);
405    }
406    // Update the units for this pressure set.
407    I->setUnitInc(I->getUnitInc() + Weight);
408  }
409}
410
411/// Record the pressure difference induced by the given operand list.
412static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
413                         const MachineRegisterInfo *MRI) {
414  assert(!PDiff.begin()->isValid() && "stale PDiff");
415
416  for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
417    PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
418
419  for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
420    PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
421}
422
423/// Force liveness of registers.
424void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
425  for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
426    if (LiveRegs.insert(Regs[i]))
427      increaseRegPressure(Regs[i]);
428  }
429}
430
431/// Add Reg to the live in set and increase max pressure.
432void RegPressureTracker::discoverLiveIn(unsigned Reg) {
433  assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
434  if (containsReg(P.LiveInRegs, Reg))
435    return;
436
437  // At live in discovery, unconditionally increase the high water mark.
438  P.LiveInRegs.push_back(Reg);
439  increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
440}
441
442/// Add Reg to the live out set and increase max pressure.
443void RegPressureTracker::discoverLiveOut(unsigned Reg) {
444  assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
445  if (containsReg(P.LiveOutRegs, Reg))
446    return;
447
448  // At live out discovery, unconditionally increase the high water mark.
449  P.LiveOutRegs.push_back(Reg);
450  increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
451}
452
453/// Recede across the previous instruction. If LiveUses is provided, record any
454/// RegUnits that are made live by the current instruction's uses. This includes
455/// registers that are both defined and used by the instruction.  If a pressure
456/// difference pointer is provided record the changes is pressure caused by this
457/// instruction independent of liveness.
458bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
459                                PressureDiff *PDiff) {
460  // Check for the top of the analyzable region.
461  if (CurrPos == MBB->begin()) {
462    closeRegion();
463    return false;
464  }
465  if (!isBottomClosed())
466    closeBottom();
467
468  // Open the top of the region using block iterators.
469  if (!RequireIntervals && isTopClosed())
470    static_cast<RegionPressure&>(P).openTop(CurrPos);
471
472  // Find the previous instruction.
473  do
474    --CurrPos;
475  while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
476
477  if (CurrPos->isDebugValue()) {
478    closeRegion();
479    return false;
480  }
481  SlotIndex SlotIdx;
482  if (RequireIntervals)
483    SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
484
485  // Open the top of the region using slot indexes.
486  if (RequireIntervals && isTopClosed())
487    static_cast<IntervalPressure&>(P).openTop(SlotIdx);
488
489  RegisterOperands RegOpers(TRI, MRI);
490  collectOperands(CurrPos, RegOpers);
491
492  if (PDiff)
493    collectPDiff(*PDiff, RegOpers, MRI);
494
495  // Boost pressure for all dead defs together.
496  increaseRegPressure(RegOpers.DeadDefs);
497  decreaseRegPressure(RegOpers.DeadDefs);
498
499  // Kill liveness at live defs.
500  // TODO: consider earlyclobbers?
501  for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
502    unsigned Reg = RegOpers.Defs[i];
503    bool DeadDef = false;
504    if (RequireIntervals) {
505      const LiveRange *LR = getLiveRange(Reg);
506      if (LR) {
507        LiveQueryResult LRQ = LR->Query(SlotIdx);
508        DeadDef = LRQ.isDeadDef();
509      }
510    }
511    if (DeadDef) {
512      // LiveIntervals knows this is a dead even though it's MachineOperand is
513      // not flagged as such. Since this register will not be recorded as
514      // live-out, increase its PDiff value to avoid underflowing pressure.
515      if (PDiff)
516        PDiff->addPressureChange(Reg, false, MRI);
517    } else {
518      if (LiveRegs.erase(Reg))
519        decreaseRegPressure(Reg);
520      else
521        discoverLiveOut(Reg);
522    }
523  }
524
525  // Generate liveness for uses.
526  for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
527    unsigned Reg = RegOpers.Uses[i];
528    if (!LiveRegs.contains(Reg)) {
529      // Adjust liveouts if LiveIntervals are available.
530      if (RequireIntervals) {
531        const LiveRange *LR = getLiveRange(Reg);
532        if (LR) {
533          LiveQueryResult LRQ = LR->Query(SlotIdx);
534          if (!LRQ.isKill() && !LRQ.valueDefined())
535            discoverLiveOut(Reg);
536        }
537      }
538      increaseRegPressure(Reg);
539      LiveRegs.insert(Reg);
540      if (LiveUses && !containsReg(*LiveUses, Reg))
541        LiveUses->push_back(Reg);
542    }
543  }
544  if (TrackUntiedDefs) {
545    for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
546      unsigned Reg = RegOpers.Defs[i];
547      if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
548        UntiedDefs.insert(Reg);
549    }
550  }
551  return true;
552}
553
554/// Advance across the current instruction.
555bool RegPressureTracker::advance() {
556  assert(!TrackUntiedDefs && "unsupported mode");
557
558  // Check for the bottom of the analyzable region.
559  if (CurrPos == MBB->end()) {
560    closeRegion();
561    return false;
562  }
563  if (!isTopClosed())
564    closeTop();
565
566  SlotIndex SlotIdx;
567  if (RequireIntervals)
568    SlotIdx = getCurrSlot();
569
570  // Open the bottom of the region using slot indexes.
571  if (isBottomClosed()) {
572    if (RequireIntervals)
573      static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
574    else
575      static_cast<RegionPressure&>(P).openBottom(CurrPos);
576  }
577
578  RegisterOperands RegOpers(TRI, MRI);
579  collectOperands(CurrPos, RegOpers);
580
581  for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
582    unsigned Reg = RegOpers.Uses[i];
583    // Discover live-ins.
584    bool isLive = LiveRegs.contains(Reg);
585    if (!isLive)
586      discoverLiveIn(Reg);
587    // Kill liveness at last uses.
588    bool lastUse = false;
589    if (RequireIntervals) {
590      const LiveRange *LR = getLiveRange(Reg);
591      lastUse = LR && LR->Query(SlotIdx).isKill();
592    }
593    else {
594      // Allocatable physregs are always single-use before register rewriting.
595      lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
596    }
597    if (lastUse && isLive) {
598      LiveRegs.erase(Reg);
599      decreaseRegPressure(Reg);
600    }
601    else if (!lastUse && !isLive)
602      increaseRegPressure(Reg);
603  }
604
605  // Generate liveness for defs.
606  for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
607    unsigned Reg = RegOpers.Defs[i];
608    if (LiveRegs.insert(Reg))
609      increaseRegPressure(Reg);
610  }
611
612  // Boost pressure for all dead defs together.
613  increaseRegPressure(RegOpers.DeadDefs);
614  decreaseRegPressure(RegOpers.DeadDefs);
615
616  // Find the next instruction.
617  do
618    ++CurrPos;
619  while (CurrPos != MBB->end() && CurrPos->isDebugValue());
620  return true;
621}
622
623/// Find the max change in excess pressure across all sets.
624static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
625                                       ArrayRef<unsigned> NewPressureVec,
626                                       RegPressureDelta &Delta,
627                                       const RegisterClassInfo *RCI,
628                                       ArrayRef<unsigned> LiveThruPressureVec) {
629  Delta.Excess = PressureChange();
630  for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
631    unsigned POld = OldPressureVec[i];
632    unsigned PNew = NewPressureVec[i];
633    int PDiff = (int)PNew - (int)POld;
634    if (!PDiff) // No change in this set in the common case.
635      continue;
636    // Only consider change beyond the limit.
637    unsigned Limit = RCI->getRegPressureSetLimit(i);
638    if (!LiveThruPressureVec.empty())
639      Limit += LiveThruPressureVec[i];
640
641    if (Limit > POld) {
642      if (Limit > PNew)
643        PDiff = 0;            // Under the limit
644      else
645        PDiff = PNew - Limit; // Just exceeded limit.
646    }
647    else if (Limit > PNew)
648      PDiff = Limit - POld;   // Just obeyed limit.
649
650    if (PDiff) {
651      Delta.Excess = PressureChange(i);
652      Delta.Excess.setUnitInc(PDiff);
653      break;
654    }
655  }
656}
657
658/// Find the max change in max pressure that either surpasses a critical PSet
659/// limit or exceeds the current MaxPressureLimit.
660///
661/// FIXME: comparing each element of the old and new MaxPressure vectors here is
662/// silly. It's done now to demonstrate the concept but will go away with a
663/// RegPressureTracker API change to work with pressure differences.
664static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
665                                    ArrayRef<unsigned> NewMaxPressureVec,
666                                    ArrayRef<PressureChange> CriticalPSets,
667                                    ArrayRef<unsigned> MaxPressureLimit,
668                                    RegPressureDelta &Delta) {
669  Delta.CriticalMax = PressureChange();
670  Delta.CurrentMax = PressureChange();
671
672  unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
673  for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
674    unsigned POld = OldMaxPressureVec[i];
675    unsigned PNew = NewMaxPressureVec[i];
676    if (PNew == POld) // No change in this set in the common case.
677      continue;
678
679    if (!Delta.CriticalMax.isValid()) {
680      while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
681        ++CritIdx;
682
683      if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
684        int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
685        if (PDiff > 0) {
686          Delta.CriticalMax = PressureChange(i);
687          Delta.CriticalMax.setUnitInc(PDiff);
688        }
689      }
690    }
691    // Find the first increase above MaxPressureLimit.
692    // (Ignores negative MDiff).
693    if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
694      Delta.CurrentMax = PressureChange(i);
695      Delta.CurrentMax.setUnitInc(PNew - POld);
696      if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
697        break;
698    }
699  }
700}
701
702/// Record the upward impact of a single instruction on current register
703/// pressure. Unlike the advance/recede pressure tracking interface, this does
704/// not discover live in/outs.
705///
706/// This is intended for speculative queries. It leaves pressure inconsistent
707/// with the current position, so must be restored by the caller.
708void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
709  assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
710
711  // Account for register pressure similar to RegPressureTracker::recede().
712  RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
713  collectOperands(MI, RegOpers);
714
715  // Boost max pressure for all dead defs together.
716  // Since CurrSetPressure and MaxSetPressure
717  increaseRegPressure(RegOpers.DeadDefs);
718  decreaseRegPressure(RegOpers.DeadDefs);
719
720  // Kill liveness at live defs.
721  for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
722    unsigned Reg = RegOpers.Defs[i];
723    bool DeadDef = false;
724    if (RequireIntervals) {
725      const LiveRange *LR = getLiveRange(Reg);
726      if (LR) {
727        SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
728        LiveQueryResult LRQ = LR->Query(SlotIdx);
729        DeadDef = LRQ.isDeadDef();
730      }
731    }
732    if (!DeadDef) {
733      if (!containsReg(RegOpers.Uses, Reg))
734        decreaseRegPressure(Reg);
735    }
736  }
737  // Generate liveness for uses.
738  for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
739    unsigned Reg = RegOpers.Uses[i];
740    if (!LiveRegs.contains(Reg))
741      increaseRegPressure(Reg);
742  }
743}
744
745/// Consider the pressure increase caused by traversing this instruction
746/// bottom-up. Find the pressure set with the most change beyond its pressure
747/// limit based on the tracker's current pressure, and return the change in
748/// number of register units of that pressure set introduced by this
749/// instruction.
750///
751/// This assumes that the current LiveOut set is sufficient.
752///
753/// FIXME: This is expensive for an on-the-fly query. We need to cache the
754/// result per-SUnit with enough information to adjust for the current
755/// scheduling position. But this works as a proof of concept.
756void RegPressureTracker::
757getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
758                          RegPressureDelta &Delta,
759                          ArrayRef<PressureChange> CriticalPSets,
760                          ArrayRef<unsigned> MaxPressureLimit) {
761  // Snapshot Pressure.
762  // FIXME: The snapshot heap space should persist. But I'm planning to
763  // summarize the pressure effect so we don't need to snapshot at all.
764  std::vector<unsigned> SavedPressure = CurrSetPressure;
765  std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
766
767  bumpUpwardPressure(MI);
768
769  computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
770                             LiveThruPressure);
771  computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
772                          MaxPressureLimit, Delta);
773  assert(Delta.CriticalMax.getUnitInc() >= 0 &&
774         Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
775
776  // Restore the tracker's state.
777  P.MaxSetPressure.swap(SavedMaxPressure);
778  CurrSetPressure.swap(SavedPressure);
779
780#ifndef NDEBUG
781  if (!PDiff)
782    return;
783
784  // Check if the alternate algorithm yields the same result.
785  RegPressureDelta Delta2;
786  getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
787  if (Delta != Delta2) {
788    dbgs() << "DELTA: " << *MI;
789    if (Delta.Excess.isValid())
790      dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
791             << " " << Delta.Excess.getUnitInc() << "\n";
792    if (Delta.CriticalMax.isValid())
793      dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
794             << " " << Delta.CriticalMax.getUnitInc() << "\n";
795    if (Delta.CurrentMax.isValid())
796      dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
797             << " " << Delta.CurrentMax.getUnitInc() << "\n";
798    if (Delta2.Excess.isValid())
799      dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
800             << " " << Delta2.Excess.getUnitInc() << "\n";
801    if (Delta2.CriticalMax.isValid())
802      dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
803             << " " << Delta2.CriticalMax.getUnitInc() << "\n";
804    if (Delta2.CurrentMax.isValid())
805      dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
806             << " " << Delta2.CurrentMax.getUnitInc() << "\n";
807    llvm_unreachable("RegP Delta Mismatch");
808  }
809#endif
810}
811
812/// This is a prototype of the fast version of querying register pressure that
813/// does not directly depend on current liveness. It's still slow because we
814/// recompute pressure change on-the-fly. This implementation only exists to
815/// prove correctness.
816///
817/// @param Delta captures information needed for heuristics.
818///
819/// @param CriticalPSets Are the pressure sets that are known to exceed some
820/// limit within the region, not necessarily at the current position.
821///
822/// @param MaxPressureLimit Is the max pressure within the region, not
823/// necessarily at the current position.
824void RegPressureTracker::
825getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
826                       RegPressureDelta &Delta,
827                       ArrayRef<PressureChange> CriticalPSets,
828                       ArrayRef<unsigned> MaxPressureLimit) const {
829  unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
830  for (PressureDiff::const_iterator
831         PDiffI = PDiff.begin(), PDiffE = PDiff.end();
832       PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
833
834    unsigned PSetID = PDiffI->getPSet();
835    unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
836    if (!LiveThruPressure.empty())
837      Limit += LiveThruPressure[PSetID];
838
839    unsigned POld = CurrSetPressure[PSetID];
840    unsigned MOld = P.MaxSetPressure[PSetID];
841    unsigned MNew = MOld;
842    // Ignore DeadDefs here because they aren't captured by PressureChange.
843    unsigned PNew = POld + PDiffI->getUnitInc();
844    assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
845    if (PNew > MOld)
846      MNew = PNew;
847    // Check if current pressure has exceeded the limit.
848    if (!Delta.Excess.isValid()) {
849      unsigned ExcessInc = 0;
850      if (PNew > Limit)
851        ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
852      else if (POld > Limit)
853        ExcessInc = Limit - POld;
854      if (ExcessInc) {
855        Delta.Excess = PressureChange(PSetID);
856        Delta.Excess.setUnitInc(ExcessInc);
857      }
858    }
859    // Check if max pressure has exceeded a critical pressure set max.
860    if (MNew == MOld)
861      continue;
862    if (!Delta.CriticalMax.isValid()) {
863      while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
864        ++CritIdx;
865
866      if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
867        int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
868        if (CritInc > 0 && CritInc <= INT16_MAX) {
869          Delta.CriticalMax = PressureChange(PSetID);
870          Delta.CriticalMax.setUnitInc(CritInc);
871        }
872      }
873    }
874    // Check if max pressure has exceeded the current max.
875    if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
876      Delta.CurrentMax = PressureChange(PSetID);
877      Delta.CurrentMax.setUnitInc(MNew - MOld);
878    }
879  }
880}
881
882/// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
883static bool findUseBetween(unsigned Reg,
884                           SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
885                           const MachineRegisterInfo *MRI,
886                           const LiveIntervals *LIS) {
887  for (MachineRegisterInfo::use_instr_nodbg_iterator
888       UI = MRI->use_instr_nodbg_begin(Reg),
889       UE = MRI->use_instr_nodbg_end(); UI != UE; ++UI) {
890      const MachineInstr* MI = &*UI;
891      if (MI->isDebugValue())
892        continue;
893      SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot();
894      if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
895        return true;
896  }
897  return false;
898}
899
900/// Record the downward impact of a single instruction on current register
901/// pressure. Unlike the advance/recede pressure tracking interface, this does
902/// not discover live in/outs.
903///
904/// This is intended for speculative queries. It leaves pressure inconsistent
905/// with the current position, so must be restored by the caller.
906void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
907  assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
908
909  // Account for register pressure similar to RegPressureTracker::recede().
910  RegisterOperands RegOpers(TRI, MRI);
911  collectOperands(MI, RegOpers);
912
913  // Kill liveness at last uses. Assume allocatable physregs are single-use
914  // rather than checking LiveIntervals.
915  SlotIndex SlotIdx;
916  if (RequireIntervals)
917    SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
918
919  for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
920    unsigned Reg = RegOpers.Uses[i];
921    if (RequireIntervals) {
922      // FIXME: allow the caller to pass in the list of vreg uses that remain
923      // to be bottom-scheduled to avoid searching uses at each query.
924      SlotIndex CurrIdx = getCurrSlot();
925      const LiveRange *LR = getLiveRange(Reg);
926      if (LR) {
927        LiveQueryResult LRQ = LR->Query(SlotIdx);
928        if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) {
929          decreaseRegPressure(Reg);
930        }
931      }
932    }
933    else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
934      // Allocatable physregs are always single-use before register rewriting.
935      decreaseRegPressure(Reg);
936    }
937  }
938
939  // Generate liveness for defs.
940  increaseRegPressure(RegOpers.Defs);
941
942  // Boost pressure for all dead defs together.
943  increaseRegPressure(RegOpers.DeadDefs);
944  decreaseRegPressure(RegOpers.DeadDefs);
945}
946
947/// Consider the pressure increase caused by traversing this instruction
948/// top-down. Find the register class with the most change in its pressure limit
949/// based on the tracker's current pressure, and return the number of excess
950/// register units of that pressure set introduced by this instruction.
951///
952/// This assumes that the current LiveIn set is sufficient.
953void RegPressureTracker::
954getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
955                            ArrayRef<PressureChange> CriticalPSets,
956                            ArrayRef<unsigned> MaxPressureLimit) {
957  // Snapshot Pressure.
958  std::vector<unsigned> SavedPressure = CurrSetPressure;
959  std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
960
961  bumpDownwardPressure(MI);
962
963  computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
964                             LiveThruPressure);
965  computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
966                          MaxPressureLimit, Delta);
967  assert(Delta.CriticalMax.getUnitInc() >= 0 &&
968         Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
969
970  // Restore the tracker's state.
971  P.MaxSetPressure.swap(SavedMaxPressure);
972  CurrSetPressure.swap(SavedPressure);
973}
974
975/// Get the pressure of each PSet after traversing this instruction bottom-up.
976void RegPressureTracker::
977getUpwardPressure(const MachineInstr *MI,
978                  std::vector<unsigned> &PressureResult,
979                  std::vector<unsigned> &MaxPressureResult) {
980  // Snapshot pressure.
981  PressureResult = CurrSetPressure;
982  MaxPressureResult = P.MaxSetPressure;
983
984  bumpUpwardPressure(MI);
985
986  // Current pressure becomes the result. Restore current pressure.
987  P.MaxSetPressure.swap(MaxPressureResult);
988  CurrSetPressure.swap(PressureResult);
989}
990
991/// Get the pressure of each PSet after traversing this instruction top-down.
992void RegPressureTracker::
993getDownwardPressure(const MachineInstr *MI,
994                    std::vector<unsigned> &PressureResult,
995                    std::vector<unsigned> &MaxPressureResult) {
996  // Snapshot pressure.
997  PressureResult = CurrSetPressure;
998  MaxPressureResult = P.MaxSetPressure;
999
1000  bumpDownwardPressure(MI);
1001
1002  // Current pressure becomes the result. Restore current pressure.
1003  P.MaxSetPressure.swap(MaxPressureResult);
1004  CurrSetPressure.swap(PressureResult);
1005}
1006