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() || Change.getUnitInc() == 0)
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 const LiveRange *RegPressureTracker::getLiveRange(unsigned Reg) const {
161 if (TargetRegisterInfo::isVirtualRegister(Reg))
162 return &LIS->getInterval(Reg);
163 return LIS->getCachedRegUnit(Reg);
166 void RegPressureTracker::reset() {
170 CurrSetPressure.clear();
171 LiveThruPressure.clear();
172 P.MaxSetPressure.clear();
174 if (RequireIntervals)
175 static_cast<IntervalPressure&>(P).reset();
177 static_cast<RegionPressure&>(P).reset();
179 LiveRegs.PhysRegs.clear();
180 LiveRegs.VirtRegs.clear();
184 /// Setup the RegPressureTracker.
186 /// TODO: Add support for pressure without LiveIntervals.
187 void RegPressureTracker::init(const MachineFunction *mf,
188 const RegisterClassInfo *rci,
189 const LiveIntervals *lis,
190 const MachineBasicBlock *mbb,
191 MachineBasicBlock::const_iterator pos,
192 bool ShouldTrackUntiedDefs)
197 TRI = MF->getSubtarget().getRegisterInfo();
199 MRI = &MF->getRegInfo();
201 TrackUntiedDefs = ShouldTrackUntiedDefs;
203 if (RequireIntervals) {
204 assert(lis && "IntervalPressure requires LiveIntervals");
209 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
211 P.MaxSetPressure = CurrSetPressure;
213 LiveRegs.PhysRegs.setUniverse(TRI->getNumRegUnits());
214 LiveRegs.VirtRegs.setUniverse(MRI->getNumVirtRegs());
216 UntiedDefs.setUniverse(MRI->getNumVirtRegs());
219 /// Does this pressure result have a valid top position and live ins.
220 bool RegPressureTracker::isTopClosed() const {
221 if (RequireIntervals)
222 return static_cast<IntervalPressure&>(P).TopIdx.isValid();
223 return (static_cast<RegionPressure&>(P).TopPos ==
224 MachineBasicBlock::const_iterator());
227 /// Does this pressure result have a valid bottom position and live outs.
228 bool RegPressureTracker::isBottomClosed() const {
229 if (RequireIntervals)
230 return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
231 return (static_cast<RegionPressure&>(P).BottomPos ==
232 MachineBasicBlock::const_iterator());
236 SlotIndex RegPressureTracker::getCurrSlot() const {
237 MachineBasicBlock::const_iterator IdxPos = CurrPos;
238 while (IdxPos != MBB->end() && IdxPos->isDebugValue())
240 if (IdxPos == MBB->end())
241 return LIS->getMBBEndIdx(MBB);
242 return LIS->getInstructionIndex(IdxPos).getRegSlot();
245 /// Set the boundary for the top of the region and summarize live ins.
246 void RegPressureTracker::closeTop() {
247 if (RequireIntervals)
248 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
250 static_cast<RegionPressure&>(P).TopPos = CurrPos;
252 assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
253 P.LiveInRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
254 P.LiveInRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
255 P.LiveInRegs.append(LiveRegs.VirtRegs.begin(), LiveRegs.VirtRegs.end());
258 /// Set the boundary for the bottom of the region and summarize live outs.
259 void RegPressureTracker::closeBottom() {
260 if (RequireIntervals)
261 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
263 static_cast<RegionPressure&>(P).BottomPos = CurrPos;
265 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
266 P.LiveOutRegs.reserve(LiveRegs.PhysRegs.size() + LiveRegs.VirtRegs.size());
267 P.LiveOutRegs.append(LiveRegs.PhysRegs.begin(), LiveRegs.PhysRegs.end());
268 P.LiveOutRegs.append(LiveRegs.VirtRegs.begin(), LiveRegs.VirtRegs.end());
271 /// Finalize the region boundaries and record live ins and live outs.
272 void RegPressureTracker::closeRegion() {
273 if (!isTopClosed() && !isBottomClosed()) {
274 assert(LiveRegs.PhysRegs.empty() && LiveRegs.VirtRegs.empty() &&
275 "no region boundary");
278 if (!isBottomClosed())
280 else if (!isTopClosed())
282 // If both top and bottom are closed, do nothing.
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.
289 void 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));
301 /// \brief Convenient wrapper for checking membership in RegisterOperands.
302 /// (std::count() doesn't have an early exit).
303 static bool containsReg(ArrayRef<unsigned> RegUnits, unsigned RegUnit) {
304 return std::find(RegUnits.begin(), RegUnits.end(), RegUnit) != RegUnits.end();
308 /// Collect this instruction's unique uses and defs into SmallVectors for
309 /// processing defs and uses in order.
311 /// FIXME: always ignore tied opers
312 class RegisterOperands {
313 const TargetRegisterInfo *TRI;
314 const MachineRegisterInfo *MRI;
318 SmallVector<unsigned, 8> Uses;
319 SmallVector<unsigned, 8> Defs;
320 SmallVector<unsigned, 8> DeadDefs;
322 RegisterOperands(const TargetRegisterInfo *tri,
323 const MachineRegisterInfo *mri, bool ID = false):
324 TRI(tri), MRI(mri), IgnoreDead(ID) {}
326 /// Push this operand's register onto the correct vector.
327 void collect(const MachineOperand &MO) {
328 if (!MO.isReg() || !MO.getReg())
331 pushRegUnits(MO.getReg(), Uses);
335 pushRegUnits(MO.getReg(), DeadDefs);
338 pushRegUnits(MO.getReg(), Defs);
343 void pushRegUnits(unsigned Reg, SmallVectorImpl<unsigned> &RegUnits) {
344 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
345 if (containsReg(RegUnits, Reg))
347 RegUnits.push_back(Reg);
349 else if (MRI->isAllocatable(Reg)) {
350 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
351 if (containsReg(RegUnits, *Units))
353 RegUnits.push_back(*Units);
360 /// Collect physical and virtual register operands.
361 static void collectOperands(const MachineInstr *MI,
362 RegisterOperands &RegOpers) {
363 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
364 RegOpers.collect(*OperI);
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());
373 /// Initialize an array of N PressureDiffs.
374 void PressureDiffs::init(unsigned N) {
377 memset(PDiffArray, 0, N * sizeof(PressureDiff));
382 PDiffArray = reinterpret_cast<PressureDiff*>(calloc(N, sizeof(PressureDiff)));
385 /// Add a change in pressure to the pressure diff of a given instruction.
386 void 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)
397 // If all pressure sets are more constrained, skip the remaining PSets.
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)
406 // Update the units for this pressure set.
407 I->setUnitInc(I->getUnitInc() + Weight);
411 /// Record the pressure difference induced by the given operand list.
412 static void collectPDiff(PressureDiff &PDiff, RegisterOperands &RegOpers,
413 const MachineRegisterInfo *MRI) {
414 assert(!PDiff.begin()->isValid() && "stale PDiff");
416 for (unsigned i = 0, e = RegOpers.Defs.size(); i != e; ++i)
417 PDiff.addPressureChange(RegOpers.Defs[i], true, MRI);
419 for (unsigned i = 0, e = RegOpers.Uses.size(); i != e; ++i)
420 PDiff.addPressureChange(RegOpers.Uses[i], false, MRI);
423 /// Force liveness of registers.
424 void 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]);
431 /// Add Reg to the live in set and increase max pressure.
432 void RegPressureTracker::discoverLiveIn(unsigned Reg) {
433 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
434 if (containsReg(P.LiveInRegs, Reg))
437 // At live in discovery, unconditionally increase the high water mark.
438 P.LiveInRegs.push_back(Reg);
439 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
442 /// Add Reg to the live out set and increase max pressure.
443 void RegPressureTracker::discoverLiveOut(unsigned Reg) {
444 assert(!LiveRegs.contains(Reg) && "avoid bumping max pressure twice");
445 if (containsReg(P.LiveOutRegs, Reg))
448 // At live out discovery, unconditionally increase the high water mark.
449 P.LiveOutRegs.push_back(Reg);
450 increaseSetPressure(P.MaxSetPressure, MRI->getPressureSets(Reg));
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.
458 bool RegPressureTracker::recede(SmallVectorImpl<unsigned> *LiveUses,
459 PressureDiff *PDiff) {
460 // Check for the top of the analyzable region.
461 if (CurrPos == MBB->begin()) {
465 if (!isBottomClosed())
468 // Open the top of the region using block iterators.
469 if (!RequireIntervals && isTopClosed())
470 static_cast<RegionPressure&>(P).openTop(CurrPos);
472 // Find the previous instruction.
475 while (CurrPos != MBB->begin() && CurrPos->isDebugValue());
477 if (CurrPos->isDebugValue()) {
482 if (RequireIntervals)
483 SlotIdx = LIS->getInstructionIndex(CurrPos).getRegSlot();
485 // Open the top of the region using slot indexes.
486 if (RequireIntervals && isTopClosed())
487 static_cast<IntervalPressure&>(P).openTop(SlotIdx);
489 RegisterOperands RegOpers(TRI, MRI);
490 collectOperands(CurrPos, RegOpers);
493 collectPDiff(*PDiff, RegOpers, MRI);
495 // Boost pressure for all dead defs together.
496 increaseRegPressure(RegOpers.DeadDefs);
497 decreaseRegPressure(RegOpers.DeadDefs);
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);
507 LiveQueryResult LRQ = LR->Query(SlotIdx);
508 DeadDef = LRQ.isDeadDef();
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.
516 PDiff->addPressureChange(Reg, false, MRI);
518 if (LiveRegs.erase(Reg))
519 decreaseRegPressure(Reg);
521 discoverLiveOut(Reg);
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);
533 LiveQueryResult LRQ = LR->Query(SlotIdx);
534 if (!LRQ.isKill() && !LRQ.valueDefined())
535 discoverLiveOut(Reg);
538 increaseRegPressure(Reg);
539 LiveRegs.insert(Reg);
540 if (LiveUses && !containsReg(*LiveUses, Reg))
541 LiveUses->push_back(Reg);
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);
554 /// Advance across the current instruction.
555 bool RegPressureTracker::advance() {
556 assert(!TrackUntiedDefs && "unsupported mode");
558 // Check for the bottom of the analyzable region.
559 if (CurrPos == MBB->end()) {
567 if (RequireIntervals)
568 SlotIdx = getCurrSlot();
570 // Open the bottom of the region using slot indexes.
571 if (isBottomClosed()) {
572 if (RequireIntervals)
573 static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
575 static_cast<RegionPressure&>(P).openBottom(CurrPos);
578 RegisterOperands RegOpers(TRI, MRI);
579 collectOperands(CurrPos, RegOpers);
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);
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();
594 // Allocatable physregs are always single-use before register rewriting.
595 lastUse = !TargetRegisterInfo::isVirtualRegister(Reg);
597 if (lastUse && isLive) {
599 decreaseRegPressure(Reg);
601 else if (!lastUse && !isLive)
602 increaseRegPressure(Reg);
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);
612 // Boost pressure for all dead defs together.
613 increaseRegPressure(RegOpers.DeadDefs);
614 decreaseRegPressure(RegOpers.DeadDefs);
616 // Find the next instruction.
619 while (CurrPos != MBB->end() && CurrPos->isDebugValue());
623 /// Find the max change in excess pressure across all sets.
624 static 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.
636 // Only consider change beyond the limit.
637 unsigned Limit = RCI->getRegPressureSetLimit(i);
638 if (!LiveThruPressureVec.empty())
639 Limit += LiveThruPressureVec[i];
643 PDiff = 0; // Under the limit
645 PDiff = PNew - Limit; // Just exceeded limit.
647 else if (Limit > PNew)
648 PDiff = Limit - POld; // Just obeyed limit.
651 Delta.Excess = PressureChange(i);
652 Delta.Excess.setUnitInc(PDiff);
658 /// Find the max change in max pressure that either surpasses a critical PSet
659 /// limit or exceeds the current MaxPressureLimit.
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.
664 static 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();
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.
679 if (!Delta.CriticalMax.isValid()) {
680 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
683 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
684 int PDiff = (int)PNew - (int)CriticalPSets[CritIdx].getUnitInc();
686 Delta.CriticalMax = PressureChange(i);
687 Delta.CriticalMax.setUnitInc(PDiff);
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())
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.
706 /// This is intended for speculative queries. It leaves pressure inconsistent
707 /// with the current position, so must be restored by the caller.
708 void RegPressureTracker::bumpUpwardPressure(const MachineInstr *MI) {
709 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
711 // Account for register pressure similar to RegPressureTracker::recede().
712 RegisterOperands RegOpers(TRI, MRI, /*IgnoreDead=*/true);
713 collectOperands(MI, RegOpers);
715 // Boost max pressure for all dead defs together.
716 // Since CurrSetPressure and MaxSetPressure
717 increaseRegPressure(RegOpers.DeadDefs);
718 decreaseRegPressure(RegOpers.DeadDefs);
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);
727 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
728 LiveQueryResult LRQ = LR->Query(SlotIdx);
729 DeadDef = LRQ.isDeadDef();
733 if (!containsReg(RegOpers.Uses, Reg))
734 decreaseRegPressure(Reg);
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);
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
751 /// This assumes that the current LiveOut set is sufficient.
753 /// This is expensive for an on-the-fly query because it calls
754 /// bumpUpwardPressure to recompute the pressure sets based on current
755 /// liveness. This mainly exists to verify correctness, e.g. with
756 /// -verify-misched. getUpwardPressureDelta is the fast version of this query
757 /// that uses the per-SUnit cache of the PressureDiff.
758 void RegPressureTracker::
759 getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff,
760 RegPressureDelta &Delta,
761 ArrayRef<PressureChange> CriticalPSets,
762 ArrayRef<unsigned> MaxPressureLimit) {
763 // Snapshot Pressure.
764 // FIXME: The snapshot heap space should persist. But I'm planning to
765 // summarize the pressure effect so we don't need to snapshot at all.
766 std::vector<unsigned> SavedPressure = CurrSetPressure;
767 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
769 bumpUpwardPressure(MI);
771 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
773 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
774 MaxPressureLimit, Delta);
775 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
776 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
778 // Restore the tracker's state.
779 P.MaxSetPressure.swap(SavedMaxPressure);
780 CurrSetPressure.swap(SavedPressure);
786 // Check if the alternate algorithm yields the same result.
787 RegPressureDelta Delta2;
788 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
789 if (Delta != Delta2) {
792 dbgs() << "DELTA: " << *MI;
793 if (Delta.Excess.isValid())
794 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
795 << " " << Delta.Excess.getUnitInc() << "\n";
796 if (Delta.CriticalMax.isValid())
797 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
798 << " " << Delta.CriticalMax.getUnitInc() << "\n";
799 if (Delta.CurrentMax.isValid())
800 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
801 << " " << Delta.CurrentMax.getUnitInc() << "\n";
802 if (Delta2.Excess.isValid())
803 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
804 << " " << Delta2.Excess.getUnitInc() << "\n";
805 if (Delta2.CriticalMax.isValid())
806 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
807 << " " << Delta2.CriticalMax.getUnitInc() << "\n";
808 if (Delta2.CurrentMax.isValid())
809 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
810 << " " << Delta2.CurrentMax.getUnitInc() << "\n";
811 llvm_unreachable("RegP Delta Mismatch");
816 /// This is the fast version of querying register pressure that does not
817 /// directly depend on current liveness.
819 /// @param Delta captures information needed for heuristics.
821 /// @param CriticalPSets Are the pressure sets that are known to exceed some
822 /// limit within the region, not necessarily at the current position.
824 /// @param MaxPressureLimit Is the max pressure within the region, not
825 /// necessarily at the current position.
826 void RegPressureTracker::
827 getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
828 RegPressureDelta &Delta,
829 ArrayRef<PressureChange> CriticalPSets,
830 ArrayRef<unsigned> MaxPressureLimit) const {
831 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
832 for (PressureDiff::const_iterator
833 PDiffI = PDiff.begin(), PDiffE = PDiff.end();
834 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
836 unsigned PSetID = PDiffI->getPSet();
837 unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
838 if (!LiveThruPressure.empty())
839 Limit += LiveThruPressure[PSetID];
841 unsigned POld = CurrSetPressure[PSetID];
842 unsigned MOld = P.MaxSetPressure[PSetID];
843 unsigned MNew = MOld;
844 // Ignore DeadDefs here because they aren't captured by PressureChange.
845 unsigned PNew = POld + PDiffI->getUnitInc();
846 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld) && "PSet overflow");
849 // Check if current pressure has exceeded the limit.
850 if (!Delta.Excess.isValid()) {
851 unsigned ExcessInc = 0;
853 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
854 else if (POld > Limit)
855 ExcessInc = Limit - POld;
857 Delta.Excess = PressureChange(PSetID);
858 Delta.Excess.setUnitInc(ExcessInc);
861 // Check if max pressure has exceeded a critical pressure set max.
864 if (!Delta.CriticalMax.isValid()) {
865 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
868 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
869 int CritInc = (int)MNew - (int)CriticalPSets[CritIdx].getUnitInc();
870 if (CritInc > 0 && CritInc <= INT16_MAX) {
871 Delta.CriticalMax = PressureChange(PSetID);
872 Delta.CriticalMax.setUnitInc(CritInc);
876 // Check if max pressure has exceeded the current max.
877 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
878 Delta.CurrentMax = PressureChange(PSetID);
879 Delta.CurrentMax.setUnitInc(MNew - MOld);
884 /// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
885 static bool findUseBetween(unsigned Reg,
886 SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
887 const MachineRegisterInfo *MRI,
888 const LiveIntervals *LIS) {
889 for (MachineRegisterInfo::use_instr_nodbg_iterator
890 UI = MRI->use_instr_nodbg_begin(Reg),
891 UE = MRI->use_instr_nodbg_end(); UI != UE; ++UI) {
892 const MachineInstr* MI = &*UI;
893 if (MI->isDebugValue())
895 SlotIndex InstSlot = LIS->getInstructionIndex(MI).getRegSlot();
896 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx)
902 /// Record the downward impact of a single instruction on current register
903 /// pressure. Unlike the advance/recede pressure tracking interface, this does
904 /// not discover live in/outs.
906 /// This is intended for speculative queries. It leaves pressure inconsistent
907 /// with the current position, so must be restored by the caller.
908 void RegPressureTracker::bumpDownwardPressure(const MachineInstr *MI) {
909 assert(!MI->isDebugValue() && "Expect a nondebug instruction.");
911 // Account for register pressure similar to RegPressureTracker::recede().
912 RegisterOperands RegOpers(TRI, MRI);
913 collectOperands(MI, RegOpers);
915 // Kill liveness at last uses. Assume allocatable physregs are single-use
916 // rather than checking LiveIntervals.
918 if (RequireIntervals)
919 SlotIdx = LIS->getInstructionIndex(MI).getRegSlot();
921 for (unsigned i = 0, e = RegOpers.Uses.size(); i < e; ++i) {
922 unsigned Reg = RegOpers.Uses[i];
923 if (RequireIntervals) {
924 // FIXME: allow the caller to pass in the list of vreg uses that remain
925 // to be bottom-scheduled to avoid searching uses at each query.
926 SlotIndex CurrIdx = getCurrSlot();
927 const LiveRange *LR = getLiveRange(Reg);
929 LiveQueryResult LRQ = LR->Query(SlotIdx);
930 if (LRQ.isKill() && !findUseBetween(Reg, CurrIdx, SlotIdx, MRI, LIS)) {
931 decreaseRegPressure(Reg);
935 else if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
936 // Allocatable physregs are always single-use before register rewriting.
937 decreaseRegPressure(Reg);
941 // Generate liveness for defs.
942 increaseRegPressure(RegOpers.Defs);
944 // Boost pressure for all dead defs together.
945 increaseRegPressure(RegOpers.DeadDefs);
946 decreaseRegPressure(RegOpers.DeadDefs);
949 /// Consider the pressure increase caused by traversing this instruction
950 /// top-down. Find the register class with the most change in its pressure limit
951 /// based on the tracker's current pressure, and return the number of excess
952 /// register units of that pressure set introduced by this instruction.
954 /// This assumes that the current LiveIn set is sufficient.
956 /// This is expensive for an on-the-fly query because it calls
957 /// bumpDownwardPressure to recompute the pressure sets based on current
958 /// liveness. We don't yet have a fast version of downward pressure tracking
959 /// analogous to getUpwardPressureDelta.
960 void RegPressureTracker::
961 getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta,
962 ArrayRef<PressureChange> CriticalPSets,
963 ArrayRef<unsigned> MaxPressureLimit) {
964 // Snapshot Pressure.
965 std::vector<unsigned> SavedPressure = CurrSetPressure;
966 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
968 bumpDownwardPressure(MI);
970 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
972 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
973 MaxPressureLimit, Delta);
974 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
975 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
977 // Restore the tracker's state.
978 P.MaxSetPressure.swap(SavedMaxPressure);
979 CurrSetPressure.swap(SavedPressure);
982 /// Get the pressure of each PSet after traversing this instruction bottom-up.
983 void RegPressureTracker::
984 getUpwardPressure(const MachineInstr *MI,
985 std::vector<unsigned> &PressureResult,
986 std::vector<unsigned> &MaxPressureResult) {
987 // Snapshot pressure.
988 PressureResult = CurrSetPressure;
989 MaxPressureResult = P.MaxSetPressure;
991 bumpUpwardPressure(MI);
993 // Current pressure becomes the result. Restore current pressure.
994 P.MaxSetPressure.swap(MaxPressureResult);
995 CurrSetPressure.swap(PressureResult);
998 /// Get the pressure of each PSet after traversing this instruction top-down.
999 void RegPressureTracker::
1000 getDownwardPressure(const MachineInstr *MI,
1001 std::vector<unsigned> &PressureResult,
1002 std::vector<unsigned> &MaxPressureResult) {
1003 // Snapshot pressure.
1004 PressureResult = CurrSetPressure;
1005 MaxPressureResult = P.MaxSetPressure;
1007 bumpDownwardPressure(MI);
1009 // Current pressure becomes the result. Restore current pressure.
1010 P.MaxSetPressure.swap(MaxPressureResult);
1011 CurrSetPressure.swap(PressureResult);