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 i = 0, e = LiveInRegs.size(); i < e; ++i)
63 dbgs() << PrintVRegOrUnit(LiveInRegs[i], TRI) << " ";
65 dbgs() << "Live Out: ";
66 for (unsigned i = 0, e = LiveOutRegs.size(); i < e; ++i)
67 dbgs() << PrintVRegOrUnit(LiveOutRegs[i], 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 {
81 for (const PressureChange &Change : *this) {
82 if (!Change.isValid())
84 dbgs() << " " << TRI.getRegPressureSetName(Change.getPSet())
85 << " " << Change.getUnitInc();
90 /// Increase the current pressure as impacted by these registers and bump
91 /// the high water mark if needed.
92 void RegPressureTracker::increaseRegPressure(ArrayRef<unsigned> RegUnits) {
93 for (unsigned i = 0, e = RegUnits.size(); i != e; ++i) {
94 PSetIterator PSetI = MRI->getPressureSets(RegUnits[i]);
95 unsigned Weight = PSetI.getWeight();
96 for (; PSetI.isValid(); ++PSetI) {
97 CurrSetPressure[*PSetI] += Weight;
98 if (CurrSetPressure[*PSetI] > P.MaxSetPressure[*PSetI]) {
99 P.MaxSetPressure[*PSetI] = CurrSetPressure[*PSetI];
105 /// Simply decrease the current pressure as impacted by these registers.
106 void RegPressureTracker::decreaseRegPressure(ArrayRef<unsigned> RegUnits) {
107 for (unsigned I = 0, E = RegUnits.size(); I != E; ++I)
108 decreaseSetPressure(CurrSetPressure, MRI->getPressureSets(RegUnits[I]));
111 /// Clear the result so it can be used for another round of pressure tracking.
112 void IntervalPressure::reset() {
113 TopIdx = BottomIdx = SlotIndex();
114 MaxSetPressure.clear();
119 /// Clear the result so it can be used for another round of pressure tracking.
120 void RegionPressure::reset() {
121 TopPos = BottomPos = MachineBasicBlock::const_iterator();
122 MaxSetPressure.clear();
127 /// If the current top is not less than or equal to the next index, open it.
128 /// We happen to need the SlotIndex for the next top for pressure update.
129 void IntervalPressure::openTop(SlotIndex NextTop) {
130 if (TopIdx <= NextTop)
132 TopIdx = SlotIndex();
136 /// If the current top is the previous instruction (before receding), open it.
137 void RegionPressure::openTop(MachineBasicBlock::const_iterator PrevTop) {
138 if (TopPos != PrevTop)
140 TopPos = MachineBasicBlock::const_iterator();
144 /// If the current bottom is not greater than the previous index, open it.
145 void IntervalPressure::openBottom(SlotIndex PrevBottom) {
146 if (BottomIdx > PrevBottom)
148 BottomIdx = SlotIndex();
152 /// If the current bottom is the previous instr (before advancing), open it.
153 void RegionPressure::openBottom(MachineBasicBlock::const_iterator PrevBottom) {
154 if (BottomPos != PrevBottom)
156 BottomPos = MachineBasicBlock::const_iterator();
160 void LiveRegSet::init(const MachineRegisterInfo &MRI) {
161 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
162 unsigned NumRegUnits = TRI.getNumRegs();
163 unsigned NumVirtRegs = MRI.getNumVirtRegs();
164 Regs.setUniverse(NumRegUnits + NumVirtRegs);
165 this->NumRegUnits = NumRegUnits;
168 void LiveRegSet::clear() {
172 const LiveRange *RegPressureTracker::getLiveRange(unsigned Reg) const {
173 if (TargetRegisterInfo::isVirtualRegister(Reg))
174 return &LIS->getInterval(Reg);
175 return LIS->getCachedRegUnit(Reg);
178 void RegPressureTracker::reset() {
182 CurrSetPressure.clear();
183 LiveThruPressure.clear();
184 P.MaxSetPressure.clear();
186 if (RequireIntervals)
187 static_cast<IntervalPressure&>(P).reset();
189 static_cast<RegionPressure&>(P).reset();
195 /// Setup the RegPressureTracker.
197 /// TODO: Add support for pressure without LiveIntervals.
198 void RegPressureTracker::init(const MachineFunction *mf,
199 const RegisterClassInfo *rci,
200 const LiveIntervals *lis,
201 const MachineBasicBlock *mbb,
202 MachineBasicBlock::const_iterator pos,
203 bool ShouldTrackUntiedDefs)
208 TRI = MF->getSubtarget().getRegisterInfo();
210 MRI = &MF->getRegInfo();
212 TrackUntiedDefs = ShouldTrackUntiedDefs;
214 if (RequireIntervals) {
215 assert(lis && "IntervalPressure requires LiveIntervals");
220 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
222 P.MaxSetPressure = CurrSetPressure;
226 UntiedDefs.setUniverse(MRI->getNumVirtRegs());
229 /// Does this pressure result have a valid top position and live ins.
230 bool RegPressureTracker::isTopClosed() const {
231 if (RequireIntervals)
232 return static_cast<IntervalPressure&>(P).TopIdx.isValid();
233 return (static_cast<RegionPressure&>(P).TopPos ==
234 MachineBasicBlock::const_iterator());
237 /// Does this pressure result have a valid bottom position and live outs.
238 bool RegPressureTracker::isBottomClosed() const {
239 if (RequireIntervals)
240 return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
241 return (static_cast<RegionPressure&>(P).BottomPos ==
242 MachineBasicBlock::const_iterator());
246 SlotIndex RegPressureTracker::getCurrSlot() const {
247 MachineBasicBlock::const_iterator IdxPos = CurrPos;
248 while (IdxPos != MBB->end() && IdxPos->isDebugValue())
250 if (IdxPos == MBB->end())
251 return LIS->getMBBEndIdx(MBB);
252 return LIS->getInstructionIndex(IdxPos).getRegSlot();
255 /// Set the boundary for the top of the region and summarize live ins.
256 void RegPressureTracker::closeTop() {
257 if (RequireIntervals)
258 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
260 static_cast<RegionPressure&>(P).TopPos = CurrPos;
262 assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
263 P.LiveInRegs.reserve(LiveRegs.size());
264 LiveRegs.appendTo(P.LiveInRegs);
267 /// Set the boundary for the bottom of the region and summarize live outs.
268 void RegPressureTracker::closeBottom() {
269 if (RequireIntervals)
270 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
272 static_cast<RegionPressure&>(P).BottomPos = CurrPos;
274 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
275 P.LiveOutRegs.reserve(LiveRegs.size());
276 LiveRegs.appendTo(P.LiveOutRegs);
279 /// Finalize the region boundaries and record live ins and live outs.
280 void RegPressureTracker::closeRegion() {
281 if (!isTopClosed() && !isBottomClosed()) {
282 assert(LiveRegs.size() == 0 && "no region boundary");
285 if (!isBottomClosed())
287 else if (!isTopClosed())
289 // If both top and bottom are closed, do nothing.
292 /// The register tracker is unaware of global liveness so ignores normal
293 /// live-thru ranges. However, two-address or coalesced chains can also lead
294 /// to live ranges with no holes. Count these to inform heuristics that we
295 /// can never drop below this pressure.
296 void RegPressureTracker::initLiveThru(const RegPressureTracker &RPTracker) {
297 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
298 assert(isBottomClosed() && "need bottom-up tracking to intialize.");
299 for (unsigned i = 0, e = P.LiveOutRegs.size(); i < e; ++i) {
300 unsigned Reg = P.LiveOutRegs[i];
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();
315 /// Collect this instruction's unique uses and defs into SmallVectors for
316 /// processing defs and uses in order.
318 /// FIXME: always ignore tied opers
319 class RegisterOperands {
320 const TargetRegisterInfo *TRI;
321 const MachineRegisterInfo *MRI;
325 SmallVector<unsigned, 8> Uses;
326 SmallVector<unsigned, 8> Defs;
327 SmallVector<unsigned, 8> DeadDefs;
329 RegisterOperands(const TargetRegisterInfo *tri,
330 const MachineRegisterInfo *mri, bool ID = false):
331 TRI(tri), MRI(mri), IgnoreDead(ID) {}
333 /// Push this operand's register onto the correct vector.
334 void collect(const MachineOperand &MO) {
335 if (!MO.isReg() || !MO.getReg())
338 pushRegUnits(MO.getReg(), Uses);
342 pushRegUnits(MO.getReg(), DeadDefs);
345 pushRegUnits(MO.getReg(), Defs);
350 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
351 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
352 if (containsReg(RegUnits, Reg))
354 RegUnits.push_back(Reg);
356 else if (MRI->isAllocatable(Reg)) {
357 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
358 if (containsReg(RegUnits, *Units))
360 RegUnits.push_back(*Units);
367 /// Collect physical and virtual register operands.
368 static void collectOperands(const MachineInstr *MI,
369 RegisterOperands &RegOpers) {
370 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
371 RegOpers.collect(*OperI);
373 // Remove redundant physreg dead defs.
374 SmallVectorImpl<unsigned>::iterator I =
375 std::remove_if(RegOpers.DeadDefs.begin(), RegOpers.DeadDefs.end(),
376 std::bind1st(std::ptr_fun(containsReg), RegOpers.Defs));
377 RegOpers.DeadDefs.erase(I, RegOpers.DeadDefs.end());
380 /// Initialize an array of N PressureDiffs.
381 void PressureDiffs::init(unsigned N) {
384 memset(PDiffArray, 0, N * sizeof(PressureDiff));
389 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
392 /// Add a change in pressure to the pressure diff of a given instruction.
393 void PressureDiff::addPressureChange(unsigned RegUnit, bool IsDec,
394 const MachineRegisterInfo *MRI) {
395 PSetIterator PSetI = MRI->getPressureSets(RegUnit);
396 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
397 for (; PSetI.isValid(); ++PSetI) {
398 // Find an existing entry in the pressure diff for this PSet.
399 PressureDiff::iterator I = nonconst_begin(), E = nonconst_end();
400 for (; I != E && I->isValid(); ++I) {
401 if (I->getPSet() >= *PSetI)
404 // If all pressure sets are more constrained, skip the remaining PSets.
407 // Insert this PressureChange.
408 if (!I->isValid() || I->getPSet() != *PSetI) {
409 PressureChange PTmp = PressureChange(*PSetI);
410 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
413 // Update the units for this pressure set.
414 unsigned NewUnitInc = I->getUnitInc() + Weight;
415 if (NewUnitInc != 0) {
416 I->setUnitInc(NewUnitInc);
419 PressureDiff::iterator J;
420 for (J = std::next(I); J != E && J->isValid(); ++J, ++I)
428 /// Record the pressure difference induced by the given operand list.
429 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
430 const MachineRegisterInfo *MRI) {
431 assert(!PDiff.begin()->isValid() && "stale PDiff");
433 for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
434 PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
436 for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
437 PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
440 /// Force liveness of registers.
441 void RegPressureTracker::addLiveRegs(ArrayRef<unsigned> Regs) {
442 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
443 if (LiveRegs.insert(Regs[i]))
444 increaseRegPressure(Regs[i]);
448 /// Add Reg to the live in set and increase max pressure.
449 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
450 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
451 if (containsReg(P.LiveInRegs, Reg))
454 // At live in discovery, unconditionally increase the high water mark.
455 P.LiveInRegs.push_back(Reg);
456 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
459 /// Add Reg to the live out set and increase max pressure.
460 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
461 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
462 if (containsReg(P.LiveOutRegs, Reg))
465 // At live out discovery, unconditionally increase the high water mark.
466 P.LiveOutRegs.push_back(Reg);
467 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
470 /// Recede across the previous instruction. If LiveUses is provided, record any
471 /// RegUnits that are made live by the current instruction's uses. This includes
472 /// registers that are both defined and used by the instruction. If a pressure
473 /// difference pointer is provided record the changes is pressure caused by this
474 /// instruction independent of liveness.
475 bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
476 PressureDiff *PDiff) {
477 // Check for the top of the analyzable region.
478 if (CurrPos == MBB->begin()) {
482 if (!isBottomClosed())
485 // Open the top of the region using block iterators.
486 if (!RequireIntervals && isTopClosed())
487 static_cast<RegionPressure&>(P).openTop(CurrPos);
489 // Find the previous instruction.
492 while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
494 if (CurrPos->isDebugValue()) {
499 if (RequireIntervals)
500 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
502 // Open the top of the region using slot indexes.
503 if (RequireIntervals && isTopClosed())
504 static_cast<IntervalPressure&>(P).openTop(SlotIdx);
506 RegisterOperands RegOpers(TRI, MRI);
507 collectOperands(CurrPos, RegOpers);
510 collectPDiff(*PDiff, RegOpers, MRI);
512 // Boost pressure for all dead defs together.
513 increaseRegPressure(RegOpers.DeadDefs);
514 decreaseRegPressure(RegOpers.DeadDefs);
516 // Kill liveness at live defs.
517 // TODO: consider earlyclobbers?
518 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
519 unsigned Reg = RegOpers.Defs[i];
520 bool DeadDef = false;
521 if (RequireIntervals) {
522 const LiveRange *LR = getLiveRange(Reg);
524 LiveQueryResult LRQ = LR->Query(SlotIdx);
525 DeadDef = LRQ.isDeadDef();
529 // LiveIntervals knows this is a dead even though it's MachineOperand is
530 // not flagged as such. Since this register will not be recorded as
531 // live-out, increase its PDiff value to avoid underflowing pressure.
533 PDiff->addPressureChange(Reg, false, MRI);
535 if (LiveRegs.erase(Reg))
536 decreaseRegPressure(Reg);
538 discoverLiveOut(Reg);
542 // Generate liveness for uses.
543 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
544 unsigned Reg = RegOpers.Uses[i];
545 if (!LiveRegs.contains(Reg)) {
546 // Adjust liveouts if LiveIntervals are available.
547 if (RequireIntervals) {
548 const LiveRange *LR = getLiveRange(Reg);
550 LiveQueryResult LRQ = LR->Query(SlotIdx);
551 if (!LRQ.isKill() && !LRQ.valueDefined())
552 discoverLiveOut(Reg);
555 increaseRegPressure(Reg);
556 LiveRegs.insert(Reg);
557 if (LiveUses && !containsReg(*LiveUses, Reg))
558 LiveUses->push_back(Reg);
561 if (TrackUntiedDefs) {
562 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
563 unsigned Reg = RegOpers.Defs[i];
564 if (TargetRegisterInfo::isVirtualRegister(Reg) && !LiveRegs.contains(Reg))
565 UntiedDefs.insert(Reg);
571 /// Advance across the current instruction.
572 bool RegPressureTracker::advance() {
573 assert(!TrackUntiedDefs && "unsupported mode");
575 // Check for the bottom of the analyzable region.
576 if (CurrPos == MBB->end()) {
584 if (RequireIntervals)
585 SlotIdx = getCurrSlot();
587 // Open the bottom of the region using slot indexes.
588 if (isBottomClosed()) {
589 if (RequireIntervals)
590 static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
592 static_cast<RegionPressure&>(P).openBottom(CurrPos);
595 RegisterOperands RegOpers(TRI, MRI);
596 collectOperands(CurrPos, RegOpers);
598 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
599 unsigned Reg = RegOpers.Uses[i];
600 // Discover live-ins.
601 bool isLive = LiveRegs.contains(Reg);
604 // Kill liveness at last uses.
605 bool lastUse = false;
606 if (RequireIntervals) {
607 const LiveRange *LR = getLiveRange(Reg);
608 lastUse = LR && LR->Query(SlotIdx).isKill();
611 // Allocatable physregs are always single-use before register rewriting.
612 lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
614 if (lastUse && isLive) {
616 decreaseRegPressure(Reg);
618 else if (!lastUse && !isLive)
619 increaseRegPressure(Reg);
622 // Generate liveness for defs.
623 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
624 unsigned Reg = RegOpers.Defs[i];
625 if (LiveRegs.insert(Reg))
626 increaseRegPressure(Reg);
629 // Boost pressure for all dead defs together.
630 increaseRegPressure(RegOpers.DeadDefs);
631 decreaseRegPressure(RegOpers.DeadDefs);
633 // Find the next instruction.
636 while (CurrPos != MBB->end() && CurrPos->isDebugValue());
640 /// Find the max change in excess pressure across all sets.
641 static void computeExcessPressureDelta(ArrayRef<unsigned> OldPressureVec,
642 ArrayRef<unsigned> NewPressureVec,
643 RegPressureDelta &Delta,
644 const RegisterClassInfo *RCI,
645 ArrayRef<unsigned> LiveThruPressureVec) {
646 Delta.Excess = PressureChange();
647 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
648 unsigned POld = OldPressureVec[i];
649 unsigned PNew = NewPressureVec[i];
650 int PDiff = (int)PNew - (int)POld;
651 if (!PDiff) // No change in this set in the common case.
653 // Only consider change beyond the limit.
654 unsigned Limit = RCI->getRegPressureSetLimit(i);
655 if (!LiveThruPressureVec.empty())
656 Limit += LiveThruPressureVec[i];
660 PDiff = 0; // Under the limit
662 PDiff = PNew - Limit; // Just exceeded limit.
664 else if (Limit > PNew)
665 PDiff = Limit - POld; // Just obeyed limit.
668 Delta.Excess = PressureChange(i);
669 Delta.Excess.setUnitInc(PDiff);
675 /// Find the max change in max pressure that either surpasses a critical PSet
676 /// limit or exceeds the current MaxPressureLimit.
678 /// FIXME: comparing each element of the old and new MaxPressure vectors here is
679 /// silly. It's done now to demonstrate the concept but will go away with a
680 /// RegPressureTracker API change to work with pressure differences.
681 static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
682 ArrayRef<unsigned> NewMaxPressureVec,
683 ArrayRef<PressureChange> CriticalPSets,
684 ArrayRef<unsigned> MaxPressureLimit,
685 RegPressureDelta &Delta) {
686 Delta.CriticalMax = PressureChange();
687 Delta.CurrentMax = PressureChange();
689 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
690 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
691 unsigned POld = OldMaxPressureVec[i];
692 unsigned PNew = NewMaxPressureVec[i];
693 if (PNew == POld) // No change in this set in the common case.
696 if (!Delta.CriticalMax.isValid()) {
697 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
700 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
701 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
703 Delta.CriticalMax = PressureChange(i);
704 Delta.CriticalMax.setUnitInc(PDiff);
708 // Find the first increase above MaxPressureLimit.
709 // (Ignores negative MDiff).
710 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
711 Delta.CurrentMax = PressureChange(i);
712 Delta.CurrentMax.setUnitInc(PNew - POld);
713 if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
719 /// Record the upward impact of a single instruction on current register
720 /// pressure. Unlike the advance/recede pressure tracking interface, this does
721 /// not discover live in/outs.
723 /// This is intended for speculative queries. It leaves pressure inconsistent
724 /// with the current position, so must be restored by the caller.
725 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
726 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
728 // Account for register pressure similar to RegPressureTracker::recede().
729 RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
730 collectOperands(MI, RegOpers);
732 // Boost max pressure for all dead defs together.
733 // Since CurrSetPressure and MaxSetPressure
734 increaseRegPressure(RegOpers.DeadDefs);
735 decreaseRegPressure(RegOpers.DeadDefs);
737 // Kill liveness at live defs.
738 for (unsigned i = 0, e = RegOpers.Defs.size(); i < e; ++i) {
739 unsigned Reg = RegOpers.Defs[i];
740 bool DeadDef = false;
741 if (RequireIntervals) {
742 const LiveRange *LR = getLiveRange(Reg);
744 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
745 LiveQueryResult LRQ = LR->Query(SlotIdx);
746 DeadDef = LRQ.isDeadDef();
750 if (!containsReg(RegOpers.Uses, Reg))
751 decreaseRegPressure(Reg);
754 // Generate liveness for uses.
755 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
756 unsigned Reg = RegOpers.Uses[i];
757 if (!LiveRegs.contains(Reg))
758 increaseRegPressure(Reg);
762 /// Consider the pressure increase caused by traversing this instruction
763 /// bottom-up. Find the pressure set with the most change beyond its pressure
764 /// limit based on the tracker's current pressure, and return the change in
765 /// number of register units of that pressure set introduced by this
768 /// This assumes that the current LiveOut set is sufficient.
770 /// This is expensive for an on-the-fly query because it calls
771 /// bumpUpwardPressure to recompute the pressure sets based on current
772 /// liveness. This mainly exists to verify correctness, e.g. with
773 /// -verify-misched. getUpwardPressureDelta is the fast version of this query
774 /// that uses the per-SUnit cache of the PressureDiff.
775 void RegPressureTracker::
776 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
777 RegPressureDelta &Delta,
778 ArrayRef<PressureChange> CriticalPSets,
779 ArrayRef<unsigned> MaxPressureLimit) {
780 // Snapshot Pressure.
781 // FIXME: The snapshot heap space should persist. But I'm planning to
782 // summarize the pressure effect so we don't need to snapshot at all.
783 std::vector<unsigned> SavedPressure = CurrSetPressure;
784 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
786 bumpUpwardPressure(MI);
788 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
790 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
791 MaxPressureLimit, Delta);
792 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
793 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
795 // Restore the tracker's state.
796 P.MaxSetPressure.swap(SavedMaxPressure);
797 CurrSetPressure.swap(SavedPressure);
803 // Check if the alternate algorithm yields the same result.
804 RegPressureDelta Delta2;
805 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
806 if (Delta != Delta2) {
809 dbgs() << "DELTA: " << *MI;
810 if (Delta.Excess.isValid())
811 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
812 << " " << Delta.Excess.getUnitInc() << "\n";
813 if (Delta.CriticalMax.isValid())
814 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
815 << " " << Delta.CriticalMax.getUnitInc() << "\n";
816 if (Delta.CurrentMax.isValid())
817 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
818 << " " << Delta.CurrentMax.getUnitInc() << "\n";
819 if (Delta2.Excess.isValid())
820 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
821 << " " << Delta2.Excess.getUnitInc() << "\n";
822 if (Delta2.CriticalMax.isValid())
823 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
824 << " " << Delta2.CriticalMax.getUnitInc() << "\n";
825 if (Delta2.CurrentMax.isValid())
826 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
827 << " " << Delta2.CurrentMax.getUnitInc() << "\n";
828 llvm_unreachable("RegP Delta Mismatch");
833 /// This is the fast version of querying register pressure that does not
834 /// directly depend on current liveness.
836 /// @param Delta captures information needed for heuristics.
838 /// @param CriticalPSets Are the pressure sets that are known to exceed some
839 /// limit within the region, not necessarily at the current position.
841 /// @param MaxPressureLimit Is the max pressure within the region, not
842 /// necessarily at the current position.
843 void RegPressureTracker::
844 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
845 RegPressureDelta &Delta,
846 ArrayRef<PressureChange> CriticalPSets,
847 ArrayRef<unsigned> MaxPressureLimit) const {
848 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
849 for (PressureDiff::const_iterator
850 PDiffI = PDiff.begin(), PDiffE = PDiff.end();
851 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
853 unsigned PSetID = PDiffI->getPSet();
854 unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
855 if (!LiveThruPressure.empty())
856 Limit += LiveThruPressure[PSetID];
858 unsigned POld = CurrSetPressure[PSetID];
859 unsigned MOld = P.MaxSetPressure[PSetID];
860 unsigned MNew = MOld;
861 // Ignore DeadDefs here because they aren't captured by PressureChange.
862 unsigned PNew = POld + PDiffI->getUnitInc();
863 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
866 // Check if current pressure has exceeded the limit.
867 if (!Delta.Excess.isValid()) {
868 unsigned ExcessInc = 0;
870 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
871 else if (POld > Limit)
872 ExcessInc = Limit - POld;
874 Delta.Excess = PressureChange(PSetID);
875 Delta.Excess.setUnitInc(ExcessInc);
878 // Check if max pressure has exceeded a critical pressure set max.
881 if (!Delta.CriticalMax.isValid()) {
882 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
885 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
886 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
887 if (CritInc > 0 && CritInc <= INT16_MAX) {
888 Delta.CriticalMax = PressureChange(PSetID);
889 Delta.CriticalMax.setUnitInc(CritInc);
893 // Check if max pressure has exceeded the current max.
894 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
895 Delta.CurrentMax = PressureChange(PSetID);
896 Delta.CurrentMax.setUnitInc(MNew - MOld);
901 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
902 static bool findUseBetween(unsigned Reg, SlotIndex PriorUseIdx,
903 SlotIndex NextUseIdx, const MachineRegisterInfo &MRI,
904 const LiveIntervals *LIS) {
905 for (const MachineInstr &MI : MRI.use_nodbg_instructions(Reg)) {
906 SlotIndex InstSlot = LIS->getInstructionIndex(&MI).getRegSlot();
907 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
913 /// Record the downward impact of a single instruction on current register
914 /// pressure. Unlike the advance/recede pressure tracking interface, this does
915 /// not discover live in/outs.
917 /// This is intended for speculative queries. It leaves pressure inconsistent
918 /// with the current position, so must be restored by the caller.
919 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
920 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
922 // Account for register pressure similar to RegPressureTracker::recede().
923 RegisterOperands RegOpers(TRI, MRI);
924 collectOperands(MI, RegOpers);
926 // Kill liveness at last uses. Assume allocatable physregs are single-use
927 // rather than checking LiveIntervals.
929 if (RequireIntervals)
930 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
932 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
933 unsigned Reg = RegOpers.Uses[i];
934 if (RequireIntervals) {
935 // FIXME: allow the caller to pass in the list of vreg uses that remain
936 // to be bottom-scheduled to avoid searching uses at each query.
937 SlotIndex CurrIdx = getCurrSlot();
938 const LiveRange *LR = getLiveRange(Reg);
940 LiveQueryResult LRQ = LR->Query(SlotIdx);
941 if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, *MRI, LIS))
942 decreaseRegPressure(Reg);
945 else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
946 // Allocatable physregs are always single-use before register rewriting.
947 decreaseRegPressure(Reg);
951 // Generate liveness for defs.
952 increaseRegPressure(RegOpers.Defs);
954 // Boost pressure for all dead defs together.
955 increaseRegPressure(RegOpers.DeadDefs);
956 decreaseRegPressure(RegOpers.DeadDefs);
959 /// Consider the pressure increase caused by traversing this instruction
960 /// top-down. Find the register class with the most change in its pressure limit
961 /// based on the tracker's current pressure, and return the number of excess
962 /// register units of that pressure set introduced by this instruction.
964 /// This assumes that the current LiveIn set is sufficient.
966 /// This is expensive for an on-the-fly query because it calls
967 /// bumpDownwardPressure to recompute the pressure sets based on current
968 /// liveness. We don't yet have a fast version of downward pressure tracking
969 /// analogous to getUpwardPressureDelta.
970 void RegPressureTracker::
971 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
972 ArrayRef<PressureChange> CriticalPSets,
973 ArrayRef<unsigned> MaxPressureLimit) {
974 // Snapshot Pressure.
975 std::vector<unsigned> SavedPressure = CurrSetPressure;
976 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
978 bumpDownwardPressure(MI);
980 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
982 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
983 MaxPressureLimit, Delta);
984 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
985 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
987 // Restore the tracker's state.
988 P.MaxSetPressure.swap(SavedMaxPressure);
989 CurrSetPressure.swap(SavedPressure);
992 /// Get the pressure of each PSet after traversing this instruction bottom-up.
993 void RegPressureTracker::
994 getUpwardPressure(const MachineInstr *MI,
995 std::vector<unsigned> &PressureResult,
996 std::vector<unsigned> &MaxPressureResult) {
997 // Snapshot pressure.
998 PressureResult = CurrSetPressure;
999 MaxPressureResult = P.MaxSetPressure;
1001 bumpUpwardPressure(MI);
1003 // Current pressure becomes the result. Restore current pressure.
1004 P.MaxSetPressure.swap(MaxPressureResult);
1005 CurrSetPressure.swap(PressureResult);
1008 /// Get the pressure of each PSet after traversing this instruction top-down.
1009 void RegPressureTracker::
1010 getDownwardPressure(const MachineInstr *MI,
1011 std::vector<unsigned> &PressureResult,
1012 std::vector<unsigned> &MaxPressureResult) {
1013 // Snapshot pressure.
1014 PressureResult = CurrSetPressure;
1015 MaxPressureResult = P.MaxSetPressure;
1017 bumpDownwardPressure(MI);
1019 // Current pressure becomes the result. Restore current pressure.
1020 P.MaxSetPressure.swap(MaxPressureResult);
1021 CurrSetPressure.swap(PressureResult);