1 //===-- RegisterPressure.cpp - Dynamic Register Pressure ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the RegisterPressure class which can be used to track
11 // MachineInstr level register pressure.
13 //===----------------------------------------------------------------------===//
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"
25 /// Increase pressure for each pressure set provided by TargetRegisterInfo.
26 static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure,
28 unsigned Weight = PSetI.getWeight();
29 for (; PSetI.isValid(); ++PSetI)
30 CurrSetPressure[*PSetI] += Weight;
33 /// Decrease pressure for each pressure set provided by TargetRegisterInfo.
34 static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure,
36 unsigned Weight = PSetI.getWeight();
37 for (; PSetI.isValid(); ++PSetI) {
38 assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow");
39 CurrSetPressure[*PSetI] -= Weight;
44 void llvm::dumpRegSetPressure(ArrayRef<unsigned> SetPressure,
45 const TargetRegisterInfo *TRI) {
47 for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) {
48 if (SetPressure[i] != 0) {
49 dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << '\n';
58 void RegisterPressure::dump(const TargetRegisterInfo *TRI) const {
59 dbgs() << "Max Pressure: ";
60 dumpRegSetPressure(MaxSetPressure, TRI);
61 dbgs() << "Live In: ";
62 for (unsigned Reg : LiveInRegs)
63 dbgs() << PrintVRegOrUnit(Reg, TRI) << " ";
65 dbgs() << "Live Out: ";
66 for (unsigned Reg : LiveOutRegs)
67 dbgs() << PrintVRegOrUnit(Reg, TRI) << " ";
72 void RegPressureTracker::dump() const {
73 if (!isTopClosed() || !isBottomClosed()) {
74 dbgs() << "Curr Pressure: ";
75 dumpRegSetPressure(CurrSetPressure, TRI);
80 void PressureDiff::dump(const TargetRegisterInfo &TRI) const {
82 for (const PressureChange &Change : *this) {
83 if (!Change.isValid())
85 dbgs() << sep << TRI.getRegPressureSetName(Change.getPSet())
86 << " " << Change.getUnitInc();
92 /// Increase the current pressure as impacted by these registers and bump
93 /// the high water mark if needed.
94 void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) {
95 for (unsigned RegUnit : RegUnits) {
96 PSetIterator PSetI = MRI->getPressureSets(RegUnit);
97 unsigned Weight = PSetI.getWeight();
98 for (; PSetI.isValid(); ++PSetI) {
99 CurrSetPressure[*PSetI] += Weight;
100 P.MaxSetPressure[*PSetI] =
101 std::max(P.MaxSetPressure[*PSetI], CurrSetPressure[*PSetI]);
106 /// Simply decrease the current pressure as impacted by these registers.
107 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) {
108 for (unsigned RegUnit : RegUnits)
109 decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnit));
112 /// Clear the result so it can be used for another round of pressure tracking.
113 void IntervalPressure::reset() {
114 TopIdx = BottomIdx = SlotIndex();
115 MaxSetPressure.clear();
120 /// Clear the result so it can be used for another round of pressure tracking.
121 void RegionPressure::reset() {
122 TopPos = BottomPos = MachineBasicBlock::const_iterator();
123 MaxSetPressure.clear();
128 /// If the current top is not less than or equal to the next index, open it.
129 /// We happen to need the SlotIndex for the next top for pressure update.
130 void IntervalPressure::openTop(SlotIndex NextTop) {
131 if (TopIdx <= NextTop)
133 TopIdx = SlotIndex();
137 /// If the current top is the previous instruction (before receding), open it.
138 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
139 if (TopPos != PrevTop)
141 TopPos = MachineBasicBlock::const_iterator();
145 /// If the current bottom is not greater than the previous index, open it.
146 void IntervalPressure::openBottom(SlotIndex PrevBottom) {
147 if (BottomIdx > PrevBottom)
149 BottomIdx = SlotIndex();
153 /// If the current bottom is the previous instr (before advancing), open it.
154 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
155 if (BottomPos != PrevBottom)
157 BottomPos = MachineBasicBlock::const_iterator();
161 void LiveRegSet::init(const MachineRegisterInfo &MRI) {
162 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
163 unsigned NumRegUnits = TRI.getNumRegs();
164 unsigned NumVirtRegs = MRI.getNumVirtRegs();
165 Regs.setUniverse(NumRegUnits + NumVirtRegs);
166 this->NumRegUnits = NumRegUnits;
169 void LiveRegSet::clear() {
173 static const LiveRange *getLiveRange(const LiveIntervals &LIS, unsigned Reg) {
174 if (TargetRegisterInfo::isVirtualRegister(Reg))
175 return &LIS.getInterval(Reg);
176 return LIS.getCachedRegUnit(Reg);
179 void RegPressureTracker::reset() {
183 CurrSetPressure.clear();
184 LiveThruPressure.clear();
185 P.MaxSetPressure.clear();
187 if (RequireIntervals)
188 static_cast<IntervalPressure&>(P).reset();
190 static_cast<RegionPressure&>(P).reset();
196 /// Setup the RegPressureTracker.
198 /// TODO: Add support for pressure without LiveIntervals.
199 void RegPressureTracker::init(const MachineFunction *mf,
200 const RegisterClassInfo *rci,
201 const LiveIntervals *lis,
202 const MachineBasicBlock *mbb,
203 MachineBasicBlock::const_iterator pos,
204 bool ShouldTrackUntiedDefs)
209 TRI = MF->getSubtarget().getRegisterInfo();
211 MRI = &MF->getRegInfo();
213 TrackUntiedDefs = ShouldTrackUntiedDefs;
215 if (RequireIntervals) {
216 assert(lis && "IntervalPressure requires LiveIntervals");
221 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
223 P.MaxSetPressure = CurrSetPressure;
227 UntiedDefs.setUniverse(MRI->getNumVirtRegs());
230 /// Does this pressure result have a valid top position and live ins.
231 bool RegPressureTracker::isTopClosed() const {
232 if (RequireIntervals)
233 return static_cast<IntervalPressure&>(P).TopIdx.isValid();
234 return (static_cast<RegionPressure&>(P).TopPos ==
235 MachineBasicBlock::const_iterator());
238 /// Does this pressure result have a valid bottom position and live outs.
239 bool RegPressureTracker::isBottomClosed() const {
240 if (RequireIntervals)
241 return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
242 return (static_cast<RegionPressure&>(P).BottomPos ==
243 MachineBasicBlock::const_iterator());
247 SlotIndex RegPressureTracker::getCurrSlot() const {
248 MachineBasicBlock::const_iterator IdxPos = CurrPos;
249 while (IdxPos != MBB->end() && IdxPos->isDebugValue())
251 if (IdxPos == MBB->end())
252 return LIS->getMBBEndIdx(MBB);
253 return LIS->getInstructionIndex(IdxPos).getRegSlot();
256 /// Set the boundary for the top of the region and summarize live ins.
257 void RegPressureTracker::closeTop() {
258 if (RequireIntervals)
259 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
261 static_cast<RegionPressure&>(P).TopPos = CurrPos;
263 assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
264 P.LiveInRegs.reserve(LiveRegs.size());
265 LiveRegs.appendTo(P.LiveInRegs);
268 /// Set the boundary for the bottom of the region and summarize live outs.
269 void RegPressureTracker::closeBottom() {
270 if (RequireIntervals)
271 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
273 static_cast<RegionPressure&>(P).BottomPos = CurrPos;
275 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
276 P.LiveOutRegs.reserve(LiveRegs.size());
277 LiveRegs.appendTo(P.LiveOutRegs);
280 /// Finalize the region boundaries and record live ins and live outs.
281 void RegPressureTracker::closeRegion() {
282 if (!isTopClosed() && !isBottomClosed()) {
283 assert(LiveRegs.size() == 0 && "no region boundary");
286 if (!isBottomClosed())
288 else if (!isTopClosed())
290 // If both top and bottom are closed, do nothing.
293 /// The register tracker is unaware of global liveness so ignores normal
294 /// live-thru ranges. However, two-address or coalesced chains can also lead
295 /// to live ranges with no holes. Count these to inform heuristics that we
296 /// can never drop below this pressure.
297 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
298 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
299 assert(isBottomClosed() && "need bottom-up tracking to intialize.");
300 for (unsigned Reg : P.LiveOutRegs) {
301 if (TargetRegisterInfo::isVirtualRegister(Reg)
302 && !RPTracker.hasUntiedDef(Reg)) {
303 increaseSetPressure(LiveThruPressure, MRI->getPressureSets(Reg));
308 /// \brief Convenient wrapper for checking membership in RegisterOperands.
309 /// (std::count() doesn't have an early exit).
310 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
311 return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
316 /// List of register defined and used by a machine instruction.
317 class RegisterOperands {
319 SmallVector<unsigned, 8> Uses;
320 SmallVector<unsigned, 8> Defs;
321 SmallVector<unsigned, 8> DeadDefs;
323 void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI,
324 const MachineRegisterInfo &MRI, bool IgnoreDead = false);
326 /// Use liveness information to find dead defs not marked with a dead flag
327 /// and move them to the DeadDefs vector.
328 void detectDeadDefs(const MachineInstr &MI, const LiveIntervals &LIS);
331 /// Collect this instruction's unique uses and defs into SmallVectors for
332 /// processing defs and uses in order.
334 /// FIXME: always ignore tied opers
335 class RegisterOperandsCollector {
336 RegisterOperands &RegOpers;
337 const TargetRegisterInfo &TRI;
338 const MachineRegisterInfo &MRI;
341 RegisterOperandsCollector(RegisterOperands &RegOpers,
342 const TargetRegisterInfo &TRI,
343 const MachineRegisterInfo &MRI,
345 : RegOpers(RegOpers), TRI(TRI), MRI(MRI), IgnoreDead(IgnoreDead) {}
347 void collectInstr(const MachineInstr &MI) const {
348 for (ConstMIBundleOperands OperI(&MI); OperI.isValid(); ++OperI)
349 collectOperand(*OperI);
351 // Remove redundant physreg dead defs.
352 SmallVectorImpl<unsigned>::iterator I =
353 std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
354 std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
355 RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
358 /// Push this operand's register onto the correct vectors.
359 void collectOperand(const MachineOperand &MO) const {
360 if (!MO.isReg() || !MO.getReg())
362 unsigned Reg = MO.getReg();
364 pushRegUnits(Reg, RegOpers.Uses);
368 pushRegUnits(Reg, RegOpers.DeadDefs);
370 pushRegUnits(Reg, RegOpers.Defs);
374 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) const {
375 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
376 if (containsReg(RegUnits, Reg))
378 RegUnits.push_back(Reg);
379 } else if (MRI.isAllocatable(Reg)) {
380 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) {
381 if (containsReg(RegUnits, *Units))
383 RegUnits.push_back(*Units);
388 friend class RegisterOperands;
391 void RegisterOperands::collect(const MachineInstr &MI,
392 const TargetRegisterInfo &TRI,
393 const MachineRegisterInfo &MRI,
395 RegisterOperandsCollector Collector(*this, TRI, MRI, IgnoreDead);
396 Collector.collectInstr(MI);
399 void RegisterOperands::detectDeadDefs(const MachineInstr &MI,
400 const LiveIntervals &LIS) {
401 SlotIndex SlotIdx = LIS.getInstructionIndex(&MI);
402 for (SmallVectorImpl<unsigned>::iterator RI = Defs.begin();
403 RI != Defs.end(); /*empty*/) {
405 const LiveRange *LR = getLiveRange(LIS, Reg);
407 LiveQueryResult LRQ = LR->Query(SlotIdx);
408 if (LRQ.isDeadDef()) {
409 // LiveIntervals knows this is a dead even though it's MachineOperand is
410 // not flagged as such.
411 DeadDefs.push_back(Reg);
422 /// Initialize an array of N PressureDiffs.
423 void PressureDiffs::init(unsigned N) {
426 memset(PDiffArray, 0, N * sizeof(PressureDiff));
431 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
434 /// Add a change in pressure to the pressure diff of a given instruction.
435 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
436 const MachineRegisterInfo *MRI) {
437 PSetIterator PSetI = MRI->getPressureSets(RegUnit);
438 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
439 for (; PSetI.isValid(); ++PSetI) {
440 // Find an existing entry in the pressure diff for this PSet.
441 PressureDiff::iterator I = nonconst_begin(), E = nonconst_end();
442 for (; I != E && I->isValid(); ++I) {
443 if (I->getPSet() >= *PSetI)
446 // If all pressure sets are more constrained, skip the remaining PSets.
449 // Insert this PressureChange.
450 if (!I->isValid() || I->getPSet() != *PSetI) {
451 PressureChange PTmp = PressureChange(*PSetI);
452 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
455 // Update the units for this pressure set.
456 unsigned NewUnitInc = I->getUnitInc() + Weight;
457 if (NewUnitInc != 0) {
458 I->setUnitInc(NewUnitInc);
461 PressureDiff::iterator J;
462 for (J = std::next(I); J != E && J->isValid(); ++J, ++I)
470 /// Record the pressure difference induced by the given operand list.
471 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
472 const MachineRegisterInfo *MRI) {
473 assert(!PDiff.begin()->isValid() && "stale PDiff");
475 for (unsigned Reg : RegOpers.Defs)
476 PDiff.addPressureChange(Reg, true, MRI);
478 for (unsigned Reg : RegOpers.Uses)
479 PDiff.addPressureChange(Reg, false, MRI);
482 /// Force liveness of registers.
483 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
484 for (unsigned Reg : Regs) {
485 if (LiveRegs.insert(Reg))
486 increaseRegPressure(Reg);
490 /// Add Reg to the live in set and increase max pressure.
491 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
492 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
493 if (containsReg(P.LiveInRegs, Reg))
496 // At live in discovery, unconditionally increase the high water mark.
497 P.LiveInRegs.push_back(Reg);
498 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
501 /// Add Reg to the live out set and increase max pressure.
502 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
503 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
504 if (containsReg(P.LiveOutRegs, Reg))
507 // At live out discovery, unconditionally increase the high water mark.
508 P.LiveOutRegs.push_back(Reg);
509 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
512 /// Recede across the previous instruction. If LiveUses is provided, record any
513 /// RegUnits that are made live by the current instruction's uses. This includes
514 /// registers that are both defined and used by the instruction. If a pressure
515 /// difference pointer is provided record the changes is pressure caused by this
516 /// instruction independent of liveness.
517 void RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
518 PressureDiff *PDiff) {
519 assert(CurrPos != MBB->begin());
520 if (!isBottomClosed())
523 // Open the top of the region using block iterators.
524 if (!RequireIntervals && isTopClosed())
525 static_cast<RegionPressure&>(P).openTop(CurrPos);
527 // Find the previous instruction.
530 while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
531 assert(!CurrPos->isDebugValue());
534 if (RequireIntervals)
535 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
537 // Open the top of the region using slot indexes.
538 if (RequireIntervals && isTopClosed())
539 static_cast<IntervalPressure&>(P).openTop(SlotIdx);
541 const MachineInstr &MI = *CurrPos;
542 RegisterOperands RegOpers;
543 RegOpers.collect(MI, *TRI, *MRI);
544 if (RequireIntervals)
545 RegOpers.detectDeadDefs(MI, *LIS);
548 collectPDiff(*PDiff, RegOpers, MRI);
550 // Boost pressure for all dead defs together.
551 increaseRegPressure(RegOpers.DeadDefs);
552 decreaseRegPressure(RegOpers.DeadDefs);
554 // Kill liveness at live defs.
555 // TODO: consider earlyclobbers?
556 for (unsigned Reg : RegOpers.Defs) {
557 if (LiveRegs.erase(Reg))
558 decreaseRegPressure(Reg);
560 discoverLiveOut(Reg);
563 // Generate liveness for uses.
564 for (unsigned Reg : RegOpers.Uses) {
565 if (!LiveRegs.contains(Reg)) {
566 // Adjust liveouts if LiveIntervals are available.
567 if (RequireIntervals) {
568 const LiveRange *LR = getLiveRange(*LIS, Reg);
570 LiveQueryResult LRQ = LR->Query(SlotIdx);
571 if (!LRQ.isKill() && !LRQ.valueDefined())
572 discoverLiveOut(Reg);
575 increaseRegPressure(Reg);
576 LiveRegs.insert(Reg);
577 if (LiveUses && !containsReg(*LiveUses, Reg))
578 LiveUses->push_back(Reg);
581 if (TrackUntiedDefs) {
582 for (unsigned Reg : RegOpers.Defs) {
583 if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
584 UntiedDefs.insert(Reg);
589 /// Advance across the current instruction.
590 void RegPressureTracker::advance() {
591 assert(!TrackUntiedDefs && "unsupported mode");
593 assert(CurrPos != MBB->end());
598 if (RequireIntervals)
599 SlotIdx = getCurrSlot();
601 // Open the bottom of the region using slot indexes.
602 if (isBottomClosed()) {
603 if (RequireIntervals)
604 static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
606 static_cast<RegionPressure&>(P).openBottom(CurrPos);
609 RegisterOperands RegOpers;
610 RegOpers.collect(*CurrPos, *TRI, *MRI);
612 for (unsigned Reg : RegOpers.Uses) {
613 // Discover live-ins.
614 bool isLive = LiveRegs.contains(Reg);
617 // Kill liveness at last uses.
618 bool lastUse = false;
619 if (RequireIntervals) {
620 const LiveRange *LR = getLiveRange(*LIS, Reg);
621 lastUse = LR && LR->Query(SlotIdx).isKill();
623 // Allocatable physregs are always single-use before register rewriting.
624 lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
626 if (lastUse && isLive) {
628 decreaseRegPressure(Reg);
629 } else if (!lastUse && !isLive)
630 increaseRegPressure(Reg);
633 // Generate liveness for defs.
634 for (unsigned Reg : RegOpers.Defs) {
635 if (LiveRegs.insert(Reg))
636 increaseRegPressure(Reg);
639 // Boost pressure for all dead defs together.
640 increaseRegPressure(RegOpers.DeadDefs);
641 decreaseRegPressure(RegOpers.DeadDefs);
643 // Find the next instruction.
646 while (CurrPos != MBB->end() && CurrPos->isDebugValue());
649 /// Find the max change in excess pressure across all sets.
650 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
651 ArrayRef<unsigned> NewPressureVec,
652 RegPressureDelta &Delta,
653 const RegisterClassInfo *RCI,
654 ArrayRef<unsigned> LiveThruPressureVec) {
655 Delta.Excess = PressureChange();
656 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
657 unsigned POld = OldPressureVec[i];
658 unsigned PNew = NewPressureVec[i];
659 int PDiff = (int)PNew - (int)POld;
660 if (!PDiff) // No change in this set in the common case.
662 // Only consider change beyond the limit.
663 unsigned Limit = RCI->getRegPressureSetLimit(i);
664 if (!LiveThruPressureVec.empty())
665 Limit += LiveThruPressureVec[i];
669 PDiff = 0; // Under the limit
671 PDiff = PNew - Limit; // Just exceeded limit.
672 } else if (Limit > PNew)
673 PDiff = Limit - POld; // Just obeyed limit.
676 Delta.Excess = PressureChange(i);
677 Delta.Excess.setUnitInc(PDiff);
683 /// Find the max change in max pressure that either surpasses a critical PSet
684 /// limit or exceeds the current MaxPressureLimit.
686 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
687 /// silly. It's done now to demonstrate the concept but will go away with a
688 /// RegPressureTracker API change to work with pressure differences.
689 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
690 ArrayRef<unsigned> NewMaxPressureVec,
691 ArrayRef<PressureChange> CriticalPSets,
692 ArrayRef<unsigned> MaxPressureLimit,
693 RegPressureDelta &Delta) {
694 Delta.CriticalMax = PressureChange();
695 Delta.CurrentMax = PressureChange();
697 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
698 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
699 unsigned POld = OldMaxPressureVec[i];
700 unsigned PNew = NewMaxPressureVec[i];
701 if (PNew == POld) // No change in this set in the common case.
704 if (!Delta.CriticalMax.isValid()) {
705 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
708 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
709 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
711 Delta.CriticalMax = PressureChange(i);
712 Delta.CriticalMax.setUnitInc(PDiff);
716 // Find the first increase above MaxPressureLimit.
717 // (Ignores negative MDiff).
718 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
719 Delta.CurrentMax = PressureChange(i);
720 Delta.CurrentMax.setUnitInc(PNew - POld);
721 if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
727 /// Record the upward impact of a single instruction on current register
728 /// pressure. Unlike the advance/recede pressure tracking interface, this does
729 /// not discover live in/outs.
731 /// This is intended for speculative queries. It leaves pressure inconsistent
732 /// with the current position, so must be restored by the caller.
733 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
734 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
736 // Account for register pressure similar to RegPressureTracker::recede().
737 RegisterOperands RegOpers;
738 RegOpers.collect(*MI, *TRI, *MRI, /*IgnoreDead=*/true);
739 assert(RegOpers.DeadDefs.size() == 0);
740 if (RequireIntervals)
741 RegOpers.detectDeadDefs(*MI, *LIS);
743 // Kill liveness at live defs.
744 for (unsigned Reg : RegOpers.Defs) {
745 if (!containsReg(RegOpers.Uses, Reg))
746 decreaseRegPressure(Reg);
748 // Generate liveness for uses.
749 for (unsigned Reg : RegOpers.Uses) {
750 if (!LiveRegs.contains(Reg))
751 increaseRegPressure(Reg);
755 /// Consider the pressure increase caused by traversing this instruction
756 /// bottom-up. Find the pressure set with the most change beyond its pressure
757 /// limit based on the tracker's current pressure, and return the change in
758 /// number of register units of that pressure set introduced by this
761 /// This assumes that the current LiveOut set is sufficient.
763 /// This is expensive for an on-the-fly query because it calls
764 /// bumpUpwardPressure to recompute the pressure sets based on current
765 /// liveness. This mainly exists to verify correctness, e.g. with
766 /// -verify-misched. getUpwardPressureDelta is the fast version of this query
767 /// that uses the per-SUnit cache of the PressureDiff.
768 void RegPressureTracker::
769 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
770 RegPressureDelta &Delta,
771 ArrayRef<PressureChange> CriticalPSets,
772 ArrayRef<unsigned> MaxPressureLimit) {
773 // Snapshot Pressure.
774 // FIXME: The snapshot heap space should persist. But I'm planning to
775 // summarize the pressure effect so we don't need to snapshot at all.
776 std::vector<unsigned> SavedPressure = CurrSetPressure;
777 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
779 bumpUpwardPressure(MI);
781 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
783 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
784 MaxPressureLimit, Delta);
785 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
786 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
788 // Restore the tracker's state.
789 P.MaxSetPressure.swap(SavedMaxPressure);
790 CurrSetPressure.swap(SavedPressure);
796 // Check if the alternate algorithm yields the same result.
797 RegPressureDelta Delta2;
798 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
799 if (Delta != Delta2) {
802 dbgs() << "DELTA: " << *MI;
803 if (Delta.Excess.isValid())
804 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
805 << " " << Delta.Excess.getUnitInc() << "\n";
806 if (Delta.CriticalMax.isValid())
807 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
808 << " " << Delta.CriticalMax.getUnitInc() << "\n";
809 if (Delta.CurrentMax.isValid())
810 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
811 << " " << Delta.CurrentMax.getUnitInc() << "\n";
812 if (Delta2.Excess.isValid())
813 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
814 << " " << Delta2.Excess.getUnitInc() << "\n";
815 if (Delta2.CriticalMax.isValid())
816 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
817 << " " << Delta2.CriticalMax.getUnitInc() << "\n";
818 if (Delta2.CurrentMax.isValid())
819 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
820 << " " << Delta2.CurrentMax.getUnitInc() << "\n";
821 llvm_unreachable("RegP Delta Mismatch");
826 /// This is the fast version of querying register pressure that does not
827 /// directly depend on current liveness.
829 /// @param Delta captures information needed for heuristics.
831 /// @param CriticalPSets Are the pressure sets that are known to exceed some
832 /// limit within the region, not necessarily at the current position.
834 /// @param MaxPressureLimit Is the max pressure within the region, not
835 /// necessarily at the current position.
836 void RegPressureTracker::
837 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
838 RegPressureDelta &Delta,
839 ArrayRef<PressureChange> CriticalPSets,
840 ArrayRef<unsigned> MaxPressureLimit) const {
841 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
842 for (PressureDiff::const_iterator
843 PDiffI = PDiff.begin(), PDiffE = PDiff.end();
844 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
846 unsigned PSetID = PDiffI->getPSet();
847 unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
848 if (!LiveThruPressure.empty())
849 Limit += LiveThruPressure[PSetID];
851 unsigned POld = CurrSetPressure[PSetID];
852 unsigned MOld = P.MaxSetPressure[PSetID];
853 unsigned MNew = MOld;
854 // Ignore DeadDefs here because they aren't captured by PressureChange.
855 unsigned PNew = POld + PDiffI->getUnitInc();
856 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld)
857 && "PSet overflow/underflow");
860 // Check if current pressure has exceeded the limit.
861 if (!Delta.Excess.isValid()) {
862 unsigned ExcessInc = 0;
864 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
865 else if (POld > Limit)
866 ExcessInc = Limit - POld;
868 Delta.Excess = PressureChange(PSetID);
869 Delta.Excess.setUnitInc(ExcessInc);
872 // Check if max pressure has exceeded a critical pressure set max.
875 if (!Delta.CriticalMax.isValid()) {
876 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
879 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
880 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
881 if (CritInc > 0 && CritInc <= INT16_MAX) {
882 Delta.CriticalMax = PressureChange(PSetID);
883 Delta.CriticalMax.setUnitInc(CritInc);
887 // Check if max pressure has exceeded the current max.
888 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
889 Delta.CurrentMax = PressureChange(PSetID);
890 Delta.CurrentMax.setUnitInc(MNew - MOld);
895 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
896 static bool findUseBetween(unsigned Reg, SlotIndex PriorUseIdx,
897 SlotIndex NextUseIdx, const MachineRegisterInfo &MRI,
898 const LiveIntervals *LIS) {
899 for (const MachineInstr &MI : MRI.use_nodbg_instructions(Reg)) {
900 SlotIndex InstSlot = LIS->getInstructionIndex(&MI).getRegSlot();
901 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
907 /// Record the downward impact of a single instruction on current register
908 /// pressure. Unlike the advance/recede pressure tracking interface, this does
909 /// not discover live in/outs.
911 /// This is intended for speculative queries. It leaves pressure inconsistent
912 /// with the current position, so must be restored by the caller.
913 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
914 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
916 // Account for register pressure similar to RegPressureTracker::recede().
917 RegisterOperands RegOpers;
918 RegOpers.collect(*MI, *TRI, *MRI);
920 // Kill liveness at last uses. Assume allocatable physregs are single-use
921 // rather than checking LiveIntervals.
923 if (RequireIntervals)
924 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
926 for (unsigned Reg : RegOpers.Uses) {
927 if (RequireIntervals) {
928 // FIXME: allow the caller to pass in the list of vreg uses that remain
929 // to be bottom-scheduled to avoid searching uses at each query.
930 SlotIndex CurrIdx = getCurrSlot();
931 const LiveRange *LR = getLiveRange(*LIS, Reg);
933 LiveQueryResult LRQ = LR->Query(SlotIdx);
934 if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, *MRI, LIS))
935 decreaseRegPressure(Reg);
937 } else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
938 // Allocatable physregs are always single-use before register rewriting.
939 decreaseRegPressure(Reg);
943 // Generate liveness for defs.
944 increaseRegPressure(RegOpers.Defs);
946 // Boost pressure for all dead defs together.
947 increaseRegPressure(RegOpers.DeadDefs);
948 decreaseRegPressure(RegOpers.DeadDefs);
951 /// Consider the pressure increase caused by traversing this instruction
952 /// top-down. Find the register class with the most change in its pressure limit
953 /// based on the tracker's current pressure, and return the number of excess
954 /// register units of that pressure set introduced by this instruction.
956 /// This assumes that the current LiveIn set is sufficient.
958 /// This is expensive for an on-the-fly query because it calls
959 /// bumpDownwardPressure to recompute the pressure sets based on current
960 /// liveness. We don't yet have a fast version of downward pressure tracking
961 /// analogous to getUpwardPressureDelta.
962 void RegPressureTracker::
963 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
964 ArrayRef<PressureChange> CriticalPSets,
965 ArrayRef<unsigned> MaxPressureLimit) {
966 // Snapshot Pressure.
967 std::vector<unsigned> SavedPressure = CurrSetPressure;
968 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
970 bumpDownwardPressure(MI);
972 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
974 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
975 MaxPressureLimit, Delta);
976 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
977 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
979 // Restore the tracker's state.
980 P.MaxSetPressure.swap(SavedMaxPressure);
981 CurrSetPressure.swap(SavedPressure);
984 /// Get the pressure of each PSet after traversing this instruction bottom-up.
985 void RegPressureTracker::
986 getUpwardPressure(const MachineInstr *MI,
987 std::vector<unsigned> &PressureResult,
988 std::vector<unsigned> &MaxPressureResult) {
989 // Snapshot pressure.
990 PressureResult = CurrSetPressure;
991 MaxPressureResult = P.MaxSetPressure;
993 bumpUpwardPressure(MI);
995 // Current pressure becomes the result. Restore current pressure.
996 P.MaxSetPressure.swap(MaxPressureResult);
997 CurrSetPressure.swap(PressureResult);
1000 /// Get the pressure of each PSet after traversing this instruction top-down.
1001 void RegPressureTracker::
1002 getDownwardPressure(const MachineInstr *MI,
1003 std::vector<unsigned> &PressureResult,
1004 std::vector<unsigned> &MaxPressureResult) {
1005 // Snapshot pressure.
1006 PressureResult = CurrSetPressure;
1007 MaxPressureResult = P.MaxSetPressure;
1009 bumpDownwardPressure(MI);
1011 // Current pressure becomes the result. Restore current pressure.
1012 P.MaxSetPressure.swap(MaxPressureResult);
1013 CurrSetPressure.swap(PressureResult);