LLVM 24.0.0git
RegisterPressure.cpp
Go to the documentation of this file.
1//===- RegisterPressure.cpp - Dynamic Register Pressure -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the RegisterPressure class which can be used to track
10// MachineInstr level register pressure.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/STLExtras.h"
30#include "llvm/Config/llvm-config.h"
31#include "llvm/MC/LaneBitmask.h"
33#include "llvm/Support/Debug.h"
36#include <algorithm>
37#include <cassert>
38#include <cstdint>
39#include <cstdlib>
40#include <cstring>
41#include <iterator>
42#include <limits>
43#include <utility>
44#include <vector>
45
46using namespace llvm;
47
48/// Increase pressure for each pressure set provided by TargetRegisterInfo.
49static void increaseSetPressure(std::vector<unsigned> &CurrSetPressure,
50 const MachineRegisterInfo &MRI,
51 VirtRegOrUnit VRegOrUnit, LaneBitmask PrevMask,
52 LaneBitmask NewMask) {
53 assert((PrevMask & ~NewMask).none() && "Must not remove bits");
54 if (PrevMask.any() || NewMask.none())
55 return;
56
57 PSetIterator PSetI = MRI.getPressureSets(VRegOrUnit);
58 unsigned Weight = PSetI.getWeight();
59 for (; PSetI.isValid(); ++PSetI)
60 CurrSetPressure[*PSetI] += Weight;
61}
62
63/// Decrease pressure for each pressure set provided by TargetRegisterInfo.
64static void decreaseSetPressure(std::vector<unsigned> &CurrSetPressure,
65 const MachineRegisterInfo &MRI,
66 VirtRegOrUnit VRegOrUnit, LaneBitmask PrevMask,
67 LaneBitmask NewMask) {
68 assert((NewMask & ~PrevMask).none() && "Must not add bits");
69 if (NewMask.any() || PrevMask.none())
70 return;
71
72 PSetIterator PSetI = MRI.getPressureSets(VRegOrUnit);
73 unsigned Weight = PSetI.getWeight();
74 for (; PSetI.isValid(); ++PSetI) {
75 assert(CurrSetPressure[*PSetI] >= Weight && "register pressure underflow");
76 CurrSetPressure[*PSetI] -= Weight;
77 }
78}
79
80#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
83 const TargetRegisterInfo *TRI) {
84 for (unsigned i = 0, e = SetPressure.size(); i < e; ++i) {
85 if (SetPressure[i] != 0) {
86 dbgs() << TRI->getRegPressureSetName(i) << "=" << SetPressure[i] << ' ';
87 }
88 }
89 dbgs() << "\n";
90}
91
94 dbgs() << "Max Pressure: ";
96 dbgs() << "Live In: ";
97 for (const VRegMaskOrUnit &P : LiveInRegs) {
98 dbgs() << printVRegOrUnit(P.VRegOrUnit, TRI);
99 if (!P.LaneMask.all())
100 dbgs() << ':' << PrintLaneMask(P.LaneMask);
101 dbgs() << ' ';
102 }
103 dbgs() << '\n';
104 dbgs() << "Live Out: ";
105 for (const VRegMaskOrUnit &P : LiveOutRegs) {
106 dbgs() << printVRegOrUnit(P.VRegOrUnit, TRI);
107 if (!P.LaneMask.all())
108 dbgs() << ':' << PrintLaneMask(P.LaneMask);
109 dbgs() << ' ';
110 }
111 dbgs() << '\n';
112}
113
116 if (!isTopClosed() || !isBottomClosed()) {
117 dbgs() << "Curr Pressure: ";
118 dumpRegSetPressure(CurrSetPressure, TRI);
119 }
120 P.dump(TRI);
121}
122
125 const char *sep = "";
126 for (const PressureChange &Change : *this) {
127 if (!Change.isValid())
128 break;
129 dbgs() << sep << TRI.getRegPressureSetName(Change.getPSet())
130 << " " << Change.getUnitInc();
131 sep = " ";
132 }
133 dbgs() << '\n';
134}
135
138 dbgs() << "[" << getPSetOrMax() << ", " << getUnitInc() << "]\n";
139}
140
142 dbgs() << "[Excess=";
143 Excess.dump();
144 dbgs() << ", CriticalMax=";
145 CriticalMax.dump();
146 dbgs() << ", CurrentMax=";
147 CurrentMax.dump();
148 dbgs() << "]\n";
149}
150
151#endif
152
154 LaneBitmask PreviousMask,
155 LaneBitmask NewMask) {
156 if (PreviousMask.any() || NewMask.none())
157 return;
158
159 PSetIterator PSetI = MRI->getPressureSets(VRegOrUnit);
160 unsigned Weight = PSetI.getWeight();
161 for (; PSetI.isValid(); ++PSetI) {
162 CurrSetPressure[*PSetI] += Weight;
163 P.MaxSetPressure[*PSetI] =
164 std::max(P.MaxSetPressure[*PSetI], CurrSetPressure[*PSetI]);
165 }
166}
167
169 LaneBitmask PreviousMask,
170 LaneBitmask NewMask) {
171 decreaseSetPressure(CurrSetPressure, *MRI, VRegOrUnit, PreviousMask, NewMask);
172}
173
174/// Clear the result so it can be used for another round of pressure tracking.
177 MaxSetPressure.clear();
178 LiveInRegs.clear();
179 LiveOutRegs.clear();
180}
181
182/// Clear the result so it can be used for another round of pressure tracking.
189
190/// If the current top is not less than or equal to the next index, open it.
191/// We happen to need the SlotIndex for the next top for pressure update.
193 if (TopIdx <= NextTop)
194 return;
195 TopIdx = SlotIndex();
196 LiveInRegs.clear();
197}
198
199/// If the current top is the previous instruction (before receding), open it.
201 if (TopPos != PrevTop)
202 return;
204 LiveInRegs.clear();
205}
206
207/// If the current bottom is not greater than the previous index, open it.
209 if (BottomIdx > PrevBottom)
210 return;
212 LiveInRegs.clear();
213}
214
215/// If the current bottom is the previous instr (before advancing), open it.
217 if (BottomPos != PrevBottom)
218 return;
220 LiveInRegs.clear();
221}
222
225 unsigned NumRegUnits = TRI.getNumRegs();
226 unsigned NumVirtRegs = MRI.getNumVirtRegs();
227 Regs.setUniverse(NumRegUnits + NumVirtRegs);
228 this->NumRegUnits = NumRegUnits;
229}
230
232 Regs.clear();
233}
234
236 MBB = nullptr;
237 LIS = nullptr;
238
239 CurrSetPressure.clear();
240 LiveThruPressure.clear();
241 P.MaxSetPressure.clear();
242
243 if (RequireIntervals)
244 static_cast<IntervalPressure&>(P).reset();
245 else
246 static_cast<RegionPressure&>(P).reset();
247
248 LiveRegs.clear();
249 UntiedDefs.clear();
250}
251
252/// Setup the RegPressureTracker.
253///
254/// TODO: Add support for pressure without LiveIntervals.
256 const RegisterClassInfo *rci,
257 const LiveIntervals *lis,
258 const MachineBasicBlock *mbb,
260 bool TrackLaneMasks, bool TrackUntiedDefs) {
261 reset();
262
263 MF = mf;
264 TRI = MF->getSubtarget().getRegisterInfo();
265 RCI = rci;
266 MRI = &MF->getRegInfo();
267 MBB = mbb;
268 this->TrackUntiedDefs = TrackUntiedDefs;
269 this->TrackLaneMasks = TrackLaneMasks;
270
271 if (RequireIntervals) {
272 assert(lis && "IntervalPressure requires LiveIntervals");
273 LIS = lis;
274 }
275
276 CurrPos = pos;
277 CurrSetPressure.assign(TRI->getNumRegPressureSets(), 0);
278
279 P.MaxSetPressure = CurrSetPressure;
280
281 LiveRegs.init(*MRI);
282 if (TrackUntiedDefs)
283 UntiedDefs.setUniverse(MRI->getNumVirtRegs());
284}
285
286/// Does this pressure result have a valid top position and live ins.
288 if (RequireIntervals)
289 return static_cast<IntervalPressure&>(P).TopIdx.isValid();
290 return (static_cast<RegionPressure&>(P).TopPos ==
292}
293
294/// Does this pressure result have a valid bottom position and live outs.
296 if (RequireIntervals)
297 return static_cast<IntervalPressure&>(P).BottomIdx.isValid();
298 return (static_cast<RegionPressure&>(P).BottomPos ==
300}
301
304 skipDebugInstructionsForward(CurrPos, MBB->end());
305 if (IdxPos == MBB->end())
306 return LIS->getMBBEndIdx(MBB);
307 return LIS->getInstructionIndex(*IdxPos).getRegSlot();
308}
309
310/// Set the boundary for the top of the region and summarize live ins.
312 if (RequireIntervals)
313 static_cast<IntervalPressure&>(P).TopIdx = getCurrSlot();
314 else
315 static_cast<RegionPressure&>(P).TopPos = CurrPos;
316
317 assert(P.LiveInRegs.empty() && "inconsistent max pressure result");
318 P.LiveInRegs.reserve(LiveRegs.size());
319 LiveRegs.appendTo(P.LiveInRegs);
320}
321
322/// Set the boundary for the bottom of the region and summarize live outs.
324 if (RequireIntervals)
325 static_cast<IntervalPressure&>(P).BottomIdx = getCurrSlot();
326 else
327 static_cast<RegionPressure&>(P).BottomPos = CurrPos;
328
329 assert(P.LiveOutRegs.empty() && "inconsistent max pressure result");
330 P.LiveOutRegs.reserve(LiveRegs.size());
331 LiveRegs.appendTo(P.LiveOutRegs);
332}
333
334/// Finalize the region boundaries and record live ins and live outs.
336 if (!isTopClosed() && !isBottomClosed()) {
337 assert(LiveRegs.size() == 0 && "no region boundary");
338 return;
339 }
340 if (!isBottomClosed())
341 closeBottom();
342 else if (!isTopClosed())
343 closeTop();
344 // If both top and bottom are closed, do nothing.
345}
346
347/// The register tracker is unaware of global liveness so ignores normal
348/// live-thru ranges. However, two-address or coalesced chains can also lead
349/// to live ranges with no holes. Count these to inform heuristics that we
350/// can never drop below this pressure.
352 LiveThruPressure.assign(TRI->getNumRegPressureSets(), 0);
353 assert(isBottomClosed() && "need bottom-up tracking to initialize.");
354 for (const VRegMaskOrUnit &Pair : P.LiveOutRegs) {
355 VirtRegOrUnit VRegOrUnit = Pair.VRegOrUnit;
356 if (VRegOrUnit.isVirtualReg() &&
357 !RPTracker.hasUntiedDef(VRegOrUnit.asVirtualReg()))
358 increaseSetPressure(LiveThruPressure, *MRI, VRegOrUnit,
360 }
361}
362
364 VirtRegOrUnit VRegOrUnit) {
365 auto I = llvm::find_if(RegUnits, [VRegOrUnit](const VRegMaskOrUnit Other) {
366 return Other.VRegOrUnit == VRegOrUnit;
367 });
368 if (I == RegUnits.end())
369 return LaneBitmask::getNone();
370 return I->LaneMask;
371}
372
374 VRegMaskOrUnit Pair) {
375 VirtRegOrUnit VRegOrUnit = Pair.VRegOrUnit;
376 assert(Pair.LaneMask.any());
377 auto I = llvm::find_if(RegUnits, [VRegOrUnit](const VRegMaskOrUnit Other) {
378 return Other.VRegOrUnit == VRegOrUnit;
379 });
380 if (I == RegUnits.end()) {
381 RegUnits.push_back(Pair);
382 } else {
383 I->LaneMask |= Pair.LaneMask;
384 }
385}
386
388 VirtRegOrUnit VRegOrUnit) {
389 auto I = llvm::find_if(RegUnits, [VRegOrUnit](const VRegMaskOrUnit Other) {
390 return Other.VRegOrUnit == VRegOrUnit;
391 });
392 if (I == RegUnits.end()) {
393 RegUnits.emplace_back(VRegOrUnit, LaneBitmask::getNone());
394 } else {
395 I->LaneMask = LaneBitmask::getNone();
396 }
397}
398
400 VRegMaskOrUnit Pair) {
401 VirtRegOrUnit VRegOrUnit = Pair.VRegOrUnit;
402 assert(Pair.LaneMask.any());
403 auto I = llvm::find_if(RegUnits, [VRegOrUnit](const VRegMaskOrUnit Other) {
404 return Other.VRegOrUnit == VRegOrUnit;
405 });
406 if (I != RegUnits.end()) {
407 I->LaneMask &= ~Pair.LaneMask;
408 if (I->LaneMask.none())
409 RegUnits.erase(I);
410 }
411}
412
413static LaneBitmask
415 bool TrackLaneMasks, VirtRegOrUnit VRegOrUnit,
416 SlotIndex Pos, LaneBitmask SafeDefault,
417 bool (*Property)(const LiveRange &LR, SlotIndex Pos)) {
418 if (VRegOrUnit.isVirtualReg()) {
419 const LiveInterval &LI = LIS.getInterval(VRegOrUnit.asVirtualReg());
420 LaneBitmask Result;
421 if (TrackLaneMasks && LI.hasSubRanges()) {
422 for (const LiveInterval::SubRange &SR : LI.subranges()) {
423 if (Property(SR, Pos))
424 Result |= SR.LaneMask;
425 }
426 } else if (Property(LI, Pos)) {
427 Result = TrackLaneMasks
428 ? MRI.getMaxLaneMaskForVReg(VRegOrUnit.asVirtualReg())
430 }
431
432 return Result;
433 } else {
434 const LiveRange *LR = LIS.getCachedRegUnit(VRegOrUnit.asMCRegUnit());
435 // Be prepared for missing liveranges: We usually do not compute liveranges
436 // for physical registers on targets with many registers (GPUs).
437 if (LR == nullptr)
438 return SafeDefault;
439 return Property(*LR, Pos) ? LaneBitmask::getAll() : LaneBitmask::getNone();
440 }
441}
442
444 const MachineRegisterInfo &MRI,
445 bool TrackLaneMasks, VirtRegOrUnit VRegOrUnit,
446 SlotIndex Pos) {
448 LIS, MRI, TrackLaneMasks, VRegOrUnit, Pos, LaneBitmask::getAll(),
449 [](const LiveRange &LR, SlotIndex Pos) { return LR.liveAt(Pos); });
450}
451
452namespace {
453
454/// Collect this instruction's unique uses and defs into SmallVectors for
455/// processing defs and uses in order.
456///
457/// FIXME: always ignore tied opers
458class RegisterOperandsCollector {
459 friend class llvm::RegisterOperands;
460
461 RegisterOperands &RegOpers;
462 const TargetRegisterInfo &TRI;
463 const MachineRegisterInfo &MRI;
464 bool IgnoreDead;
465
466 RegisterOperandsCollector(RegisterOperands &RegOpers,
467 const TargetRegisterInfo &TRI,
468 const MachineRegisterInfo &MRI, bool IgnoreDead)
469 : RegOpers(RegOpers), TRI(TRI), MRI(MRI), IgnoreDead(IgnoreDead) {}
470
471 void collectInstr(const MachineInstr &MI) const {
472 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
473 collectOperand(*OperI);
474
475 // Remove redundant physreg dead defs.
476 for (const VRegMaskOrUnit &P : RegOpers.Defs)
477 removeRegLanes(RegOpers.DeadDefs, P);
478 }
479
480 void collectInstrLanes(const MachineInstr &MI) const {
481 for (ConstMIBundleOperands OperI(MI); OperI.isValid(); ++OperI)
482 collectOperandLanes(*OperI);
483
484 // Remove redundant physreg dead defs.
485 for (const VRegMaskOrUnit &P : RegOpers.Defs)
486 removeRegLanes(RegOpers.DeadDefs, P);
487 }
488
489 /// Push this operand's register onto the correct vectors.
490 void collectOperand(const MachineOperand &MO) const {
491 if (!MO.isReg() || !MO.getReg())
492 return;
493 Register Reg = MO.getReg();
494 if (MO.isUse()) {
495 if (!MO.isUndef() && !MO.isInternalRead())
496 pushReg(Reg, RegOpers.Uses);
497 } else {
498 assert(MO.isDef());
499 // Subregister definitions may imply a register read.
500 if (MO.readsReg())
501 pushReg(Reg, RegOpers.Uses);
502
503 if (MO.isDead()) {
504 if (!IgnoreDead)
505 pushReg(Reg, RegOpers.DeadDefs);
506 } else
507 pushReg(Reg, RegOpers.Defs);
508 }
509 }
510
511 void pushReg(Register Reg, SmallVectorImpl<VRegMaskOrUnit> &RegUnits) const {
512 if (Reg.isVirtual()) {
513 addRegLanes(RegUnits,
514 VRegMaskOrUnit(VirtRegOrUnit(Reg), LaneBitmask::getAll()));
515 } else if (MRI.isAllocatable(Reg)) {
516 for (MCRegUnit Unit : TRI.regunits(Reg.asMCReg()))
517 addRegLanes(RegUnits,
518 VRegMaskOrUnit(VirtRegOrUnit(Unit), LaneBitmask::getAll()));
519 }
520 }
521
522 void collectOperandLanes(const MachineOperand &MO) const {
523 if (!MO.isReg() || !MO.getReg())
524 return;
525 Register Reg = MO.getReg();
526 unsigned SubRegIdx = MO.getSubReg();
527 if (MO.isUse()) {
528 if (!MO.isUndef() && !MO.isInternalRead())
529 pushRegLanes(Reg, SubRegIdx, RegOpers.Uses);
530 } else {
531 assert(MO.isDef());
532 // Treat read-undef subreg defs as definitions of the whole register.
533 if (MO.isUndef())
534 SubRegIdx = 0;
535
536 if (MO.isDead()) {
537 if (!IgnoreDead)
538 pushRegLanes(Reg, SubRegIdx, RegOpers.DeadDefs);
539 } else
540 pushRegLanes(Reg, SubRegIdx, RegOpers.Defs);
541 }
542 }
543
544 void pushRegLanes(Register Reg, unsigned SubRegIdx,
545 SmallVectorImpl<VRegMaskOrUnit> &RegUnits) const {
546 if (Reg.isVirtual()) {
547 LaneBitmask LaneMask = SubRegIdx != 0
548 ? TRI.getSubRegIndexLaneMask(SubRegIdx)
550 addRegLanes(RegUnits, VRegMaskOrUnit(VirtRegOrUnit(Reg), LaneMask));
551 } else if (MRI.isAllocatable(Reg)) {
552 for (MCRegUnit Unit : TRI.regunits(Reg.asMCReg()))
553 addRegLanes(RegUnits,
554 VRegMaskOrUnit(VirtRegOrUnit(Unit), LaneBitmask::getAll()));
555 }
556 }
557};
558
559} // end anonymous namespace
560
562 const TargetRegisterInfo &TRI,
563 const MachineRegisterInfo &MRI,
564 bool TrackLaneMasks, bool IgnoreDead) {
565 RegisterOperandsCollector Collector(*this, TRI, MRI, IgnoreDead);
566 if (TrackLaneMasks)
567 Collector.collectInstrLanes(MI);
568 else
569 Collector.collectInstr(MI);
570}
571
573 const LiveIntervals &LIS,
574 const MachineRegisterInfo &MRI) {
575 SlotIndex DeadSlotIdx = LIS.getInstructionIndex(MI).getDeadSlot();
576 for (auto *I = Defs.begin(); I != Defs.end(); /*empty*/) {
577 LaneBitmask LiveAfter = getLiveLanesAt(LIS, MRI, /*TrackLaneMasks=*/false,
578 I->VRegOrUnit, DeadSlotIdx);
579 I = adjustDef(*I, LiveAfter);
580 }
581}
582
584 const MachineRegisterInfo &MRI,
585 SlotIndex Pos) {
586 for (auto *I = Defs.begin(); I != Defs.end(); /*empty*/) {
587 LaneBitmask LiveAfter = getLiveLanesAt(LIS, MRI, /*TrackLaneMasks=*/true,
588 I->VRegOrUnit, Pos.getDeadSlot());
589 I = adjustDef(*I, LiveAfter);
590 }
591 adjustUses(LIS, MRI, Pos.getBaseIndex());
592}
593
595 const MachineRegisterInfo &MRI,
596 MachineInstr &MI) {
598 for (auto *I = Defs.begin(); I != Defs.end(); /*empty*/) {
599 LaneBitmask LiveAfter = getLiveLanesAt(LIS, MRI, /*TrackLaneMasks=*/true,
600 I->VRegOrUnit, Pos.getDeadSlot());
601 // If the def is all that is live after the instruction, then in case
602 // of a subregister def we need a read-undef flag.
603 VirtRegOrUnit VRegOrUnit = I->VRegOrUnit;
604 if (VRegOrUnit.isVirtualReg() && (LiveAfter & ~I->LaneMask).none())
605 MI.setRegisterDefReadUndef(VRegOrUnit.asVirtualReg());
606 I = adjustDef(*I, LiveAfter);
607 }
608
609 adjustUses(LIS, MRI, Pos);
610
612 for (const VRegMaskOrUnit &P : DeadDefs) {
613 VirtRegOrUnit VRegOrUnit = P.VRegOrUnit;
614 if (!VRegOrUnit.isVirtualReg())
615 continue;
616 Register VReg = VRegOrUnit.asVirtualReg();
617 LaneBitmask LiveAfter = getLiveLanesAt(LIS, MRI, /*TrackLaneMasks=*/true,
618 VRegOrUnit, Pos.getDeadSlot());
619 if (!LiveAfter.none())
620 continue;
621 // The register's read value doesn't matter if none of its lanes are live
622 // after the def.
623 MI.setRegisterDefReadUndef(VReg);
624
625 // The register's last definition should be marked dead.
626 const LiveInterval &LI = LIS.getInterval(VReg);
627 if (LI.segments.back().end == Pos.getDeadSlot())
628 MI.addRegisterDead(VReg, TRI, /*AddIfNotFound=*/false);
629 }
630}
631
632VRegMaskOrUnit *RegisterOperands::adjustDef(VRegMaskOrUnit &Def,
633 LaneBitmask LiveAfterDef) {
634 LaneBitmask ActualDef = Def.LaneMask & LiveAfterDef;
635 if (ActualDef.none()) {
636 DeadDefs.push_back(Def);
637 return Defs.erase(&Def);
638 }
639
640 Def.LaneMask = ActualDef;
641 return &Def + 1;
642}
643
644void RegisterOperands::adjustUses(const LiveIntervals &LIS,
645 const MachineRegisterInfo &MRI,
646 SlotIndex Pos) {
647 for (auto &[VRegOrUnit, LaneMask] : Uses) {
648 LaneMask =
649 getLiveLanesAt(LIS, MRI, /*TrackLaneMasks=*/true, VRegOrUnit, Pos);
650 }
651}
652
653/// Initialize an array of N PressureDiffs.
654void PressureDiffs::init(unsigned N) {
655 Size = N;
656 if (N <= Max) {
657 memset(PDiffArray, 0, N * sizeof(PressureDiff));
658 return;
659 }
660 Max = Size;
661 free(PDiffArray);
662 PDiffArray = static_cast<PressureDiff*>(safe_calloc(N, sizeof(PressureDiff)));
663}
664
666 const RegisterOperands &RegOpers,
667 const MachineRegisterInfo &MRI) {
668 PressureDiff &PDiff = (*this)[Idx];
669 assert(!PDiff.begin()->isValid() && "stale PDiff");
670 for (const VRegMaskOrUnit &P : RegOpers.Defs)
671 PDiff.addPressureChange(P.VRegOrUnit, true, &MRI);
672
673 for (const VRegMaskOrUnit &P : RegOpers.Uses)
674 PDiff.addPressureChange(P.VRegOrUnit, false, &MRI);
675}
676
677/// Add a change in pressure to the pressure diff of a given instruction.
679 const MachineRegisterInfo *MRI) {
680 PSetIterator PSetI = MRI->getPressureSets(VRegOrUnit);
681 int Weight = IsDec ? -PSetI.getWeight() : PSetI.getWeight();
682 for (; PSetI.isValid(); ++PSetI) {
683 // Find an existing entry in the pressure diff for this PSet.
684 PressureDiff::iterator I = nonconst_begin(), E = nonconst_end();
685 for (; I != E && I->isValid(); ++I) {
686 if (I->getPSet() >= *PSetI)
687 break;
688 }
689 // If all pressure sets are more constrained, skip the remaining PSets.
690 if (I == E)
691 break;
692 // Insert this PressureChange.
693 if (!I->isValid() || I->getPSet() != *PSetI) {
694 PressureChange PTmp = PressureChange(*PSetI);
695 for (PressureDiff::iterator J = I; J != E && PTmp.isValid(); ++J)
696 std::swap(*J, PTmp);
697 }
698 // Update the units for this pressure set.
699 unsigned NewUnitInc = I->getUnitInc() + Weight;
700 if (NewUnitInc != 0) {
701 I->setUnitInc(NewUnitInc);
702 } else {
703 // Remove entry
704 PressureDiff::iterator J;
705 for (J = std::next(I); J != E && J->isValid(); ++J, ++I)
706 *I = *J;
707 *I = PressureChange();
708 }
709 }
710}
711
712/// Force liveness of registers.
714 for (const VRegMaskOrUnit &P : Regs) {
715 LaneBitmask PrevMask = LiveRegs.insert(P);
716 LaneBitmask NewMask = PrevMask | P.LaneMask;
717 increaseRegPressure(P.VRegOrUnit, PrevMask, NewMask);
718 }
719}
720
723 assert(Pair.LaneMask.any());
724
725 VirtRegOrUnit VRegOrUnit = Pair.VRegOrUnit;
726 auto I = find_if(LiveInOrOut, [VRegOrUnit](const VRegMaskOrUnit &Other) {
727 return Other.VRegOrUnit == VRegOrUnit;
728 });
729 LaneBitmask PrevMask;
730 LaneBitmask NewMask;
731 if (I == LiveInOrOut.end()) {
732 PrevMask = LaneBitmask::getNone();
733 NewMask = Pair.LaneMask;
734 LiveInOrOut.push_back(Pair);
735 } else {
736 PrevMask = I->LaneMask;
737 NewMask = PrevMask | Pair.LaneMask;
738 I->LaneMask = NewMask;
739 }
740 increaseSetPressure(P.MaxSetPressure, *MRI, VRegOrUnit, PrevMask, NewMask);
741}
742
746
750
752 for (const VRegMaskOrUnit &P : DeadDefs) {
753 LaneBitmask LiveMask = LiveRegs.contains(P.VRegOrUnit);
754 LaneBitmask BumpedMask = LiveMask | P.LaneMask;
755 increaseRegPressure(P.VRegOrUnit, LiveMask, BumpedMask);
756 }
757 for (const VRegMaskOrUnit &P : DeadDefs) {
758 LaneBitmask LiveMask = LiveRegs.contains(P.VRegOrUnit);
759 LaneBitmask BumpedMask = LiveMask | P.LaneMask;
760 decreaseRegPressure(P.VRegOrUnit, BumpedMask, LiveMask);
761 }
762}
763
764/// Recede across the previous instruction. If LiveUses is provided, record any
765/// RegUnits that are made live by the current instruction's uses. This includes
766/// registers that are both defined and used by the instruction. If a pressure
767/// difference pointer is provided record the changes is pressure caused by this
768/// instruction independent of liveness.
771 assert(!CurrPos->isDebugOrPseudoInstr());
772
773 // Boost pressure for all dead defs together.
774 bumpDeadDefs(RegOpers.DeadDefs);
775
776 // Kill liveness at live defs.
777 // TODO: consider earlyclobbers?
778 for (const VRegMaskOrUnit &Def : RegOpers.Defs) {
779 VirtRegOrUnit VRegOrUnit = Def.VRegOrUnit;
780
781 LaneBitmask PreviousMask = LiveRegs.erase(Def);
782 LaneBitmask NewMask = PreviousMask & ~Def.LaneMask;
783
784 LaneBitmask LiveOut = Def.LaneMask & ~PreviousMask;
785 if (LiveOut.any()) {
786 discoverLiveOut(VRegMaskOrUnit(VRegOrUnit, LiveOut));
787 // Retroactively model effects on pressure of the live out lanes.
788 increaseSetPressure(CurrSetPressure, *MRI, VRegOrUnit,
789 LaneBitmask::getNone(), LiveOut);
790 PreviousMask = LiveOut;
791 }
792
793 if (NewMask.none()) {
794 // Add a 0 entry to LiveUses as a marker that the complete vreg has become
795 // dead.
796 if (TrackLaneMasks && LiveUses != nullptr)
797 setRegZero(*LiveUses, VRegOrUnit);
798 }
799
800 decreaseRegPressure(VRegOrUnit, PreviousMask, NewMask);
801 }
802
803 SlotIndex SlotIdx;
804 if (RequireIntervals)
805 SlotIdx = LIS->getInstructionIndex(*CurrPos).getRegSlot();
806
807 // Generate liveness for uses.
808 for (const VRegMaskOrUnit &Use : RegOpers.Uses) {
809 VirtRegOrUnit VRegOrUnit = Use.VRegOrUnit;
810 assert(Use.LaneMask.any());
811 LaneBitmask PreviousMask = LiveRegs.insert(Use);
812 LaneBitmask NewMask = PreviousMask | Use.LaneMask;
813 if (NewMask == PreviousMask)
814 continue;
815
816 // Did the register just become live?
817 if (PreviousMask.none()) {
818 if (LiveUses != nullptr) {
819 if (!TrackLaneMasks) {
820 addRegLanes(*LiveUses, VRegMaskOrUnit(VRegOrUnit, NewMask));
821 } else {
822 auto I = find_if(*LiveUses, [VRegOrUnit](const VRegMaskOrUnit Other) {
823 return Other.VRegOrUnit == VRegOrUnit;
824 });
825 bool IsRedef = I != LiveUses->end();
826 if (IsRedef) {
827 // ignore re-defs here...
828 assert(I->LaneMask.none());
829 removeRegLanes(*LiveUses, VRegMaskOrUnit(VRegOrUnit, NewMask));
830 } else {
831 addRegLanes(*LiveUses, VRegMaskOrUnit(VRegOrUnit, NewMask));
832 }
833 }
834 }
835
836 // Discover live outs if this may be the first occurance of this register.
837 if (RequireIntervals) {
838 LaneBitmask LiveOut = getLiveThroughAt(VRegOrUnit, SlotIdx);
839 if (LiveOut.any())
840 discoverLiveOut(VRegMaskOrUnit(VRegOrUnit, LiveOut));
841 }
842 }
843
844 increaseRegPressure(VRegOrUnit, PreviousMask, NewMask);
845 }
846 if (TrackUntiedDefs) {
847 for (const VRegMaskOrUnit &Def : RegOpers.Defs) {
848 VirtRegOrUnit VRegOrUnit = Def.VRegOrUnit;
849 if (VRegOrUnit.isVirtualReg() &&
850 (LiveRegs.contains(VRegOrUnit) & Def.LaneMask).none())
851 UntiedDefs.insert(VRegOrUnit.asVirtualReg());
852 }
853 }
854}
855
857 assert(CurrPos != MBB->begin());
858 if (!isBottomClosed())
859 closeBottom();
860
861 // Open the top of the region using block iterators.
862 if (!RequireIntervals && isTopClosed())
863 static_cast<RegionPressure&>(P).openTop(CurrPos);
864
865 // Find the previous instruction.
866 CurrPos = prev_nodbg(CurrPos, MBB->begin());
867
868 SlotIndex SlotIdx;
869 if (RequireIntervals && !CurrPos->isDebugOrPseudoInstr())
870 SlotIdx = LIS->getInstructionIndex(*CurrPos).getRegSlot();
871
872 // Open the top of the region using slot indexes.
873 if (RequireIntervals && isTopClosed())
874 static_cast<IntervalPressure&>(P).openTop(SlotIdx);
875}
876
879 if (CurrPos->isDebugOrPseudoInstr()) {
880 // It's possible to only have debug_value and pseudo probe instructions and
881 // hit the start of the block.
882 assert(CurrPos == MBB->begin());
883 return;
884 }
885
886 const MachineInstr &MI = *CurrPos;
887 RegisterOperands RegOpers;
888 RegOpers.collect(MI, *TRI, *MRI, TrackLaneMasks, /*IgnoreDead=*/false);
889 if (TrackLaneMasks) {
890 SlotIndex SlotIdx = LIS->getInstructionIndex(*CurrPos).getRegSlot();
891 RegOpers.adjustLaneLiveness(*LIS, *MRI, SlotIdx);
892 } else if (RequireIntervals) {
893 RegOpers.detectDeadDefs(MI, *LIS, *MRI);
894 }
895
896 recede(RegOpers, LiveUses);
897}
898
899/// Advance across the current instruction.
901 assert(!TrackUntiedDefs && "unsupported mode");
902 assert(CurrPos != MBB->end());
903 if (!isTopClosed())
904 closeTop();
905
906 SlotIndex SlotIdx;
907 if (RequireIntervals)
908 SlotIdx = getCurrSlot();
909
910 // Open the bottom of the region using slot indexes.
911 if (isBottomClosed()) {
912 if (RequireIntervals)
913 static_cast<IntervalPressure&>(P).openBottom(SlotIdx);
914 else
915 static_cast<RegionPressure&>(P).openBottom(CurrPos);
916 }
917
918 for (const VRegMaskOrUnit &Use : RegOpers.Uses) {
919 VirtRegOrUnit VRegOrUnit = Use.VRegOrUnit;
920 LaneBitmask LiveMask = LiveRegs.contains(VRegOrUnit);
921 LaneBitmask LiveIn = Use.LaneMask & ~LiveMask;
922 if (LiveIn.any()) {
923 discoverLiveIn(VRegMaskOrUnit(VRegOrUnit, LiveIn));
924 increaseRegPressure(VRegOrUnit, LiveMask, LiveMask | LiveIn);
925 LiveRegs.insert(VRegMaskOrUnit(VRegOrUnit, LiveIn));
926 }
927 // Kill liveness at last uses.
928 if (RequireIntervals) {
929 LaneBitmask LastUseMask = getLastUsedLanes(VRegOrUnit, SlotIdx);
930 if (LastUseMask.any()) {
931 LiveRegs.erase(VRegMaskOrUnit(VRegOrUnit, LastUseMask));
932 decreaseRegPressure(VRegOrUnit, LiveMask, LiveMask & ~LastUseMask);
933 }
934 }
935 }
936
937 // Generate liveness for defs.
938 for (const VRegMaskOrUnit &Def : RegOpers.Defs) {
939 LaneBitmask PreviousMask = LiveRegs.insert(Def);
940 LaneBitmask NewMask = PreviousMask | Def.LaneMask;
941 increaseRegPressure(Def.VRegOrUnit, PreviousMask, NewMask);
942 }
943
944 // Boost pressure for all dead defs together.
945 bumpDeadDefs(RegOpers.DeadDefs);
946
947 // Find the next instruction.
948 CurrPos = next_nodbg(CurrPos, MBB->end());
949}
950
952 const MachineInstr &MI = *CurrPos;
953 RegisterOperands RegOpers;
954 RegOpers.collect(MI, *TRI, *MRI, TrackLaneMasks, false);
955 if (TrackLaneMasks) {
956 SlotIndex SlotIdx = getCurrSlot();
957 RegOpers.adjustLaneLiveness(*LIS, *MRI, SlotIdx);
958 }
959 advance(RegOpers);
960}
961
962/// Find the max change in excess pressure across all sets.
964 ArrayRef<unsigned> NewPressureVec,
965 RegPressureDelta &Delta,
966 const RegisterClassInfo *RCI,
967 ArrayRef<unsigned> LiveThruPressureVec) {
968 Delta.Excess = PressureChange();
969 for (unsigned i = 0, e = OldPressureVec.size(); i < e; ++i) {
970 unsigned POld = OldPressureVec[i];
971 unsigned PNew = NewPressureVec[i];
972 int PDiff = (int)PNew - (int)POld;
973 if (!PDiff) // No change in this set in the common case.
974 continue;
975 // Only consider change beyond the limit.
976 unsigned Limit = RCI->getRegPressureSetLimit(i);
977 if (!LiveThruPressureVec.empty())
978 Limit += LiveThruPressureVec[i];
979
980 if (Limit > POld) {
981 if (Limit > PNew)
982 PDiff = 0; // Under the limit
983 else
984 PDiff = PNew - Limit; // Just exceeded limit.
985 } else if (Limit > PNew)
986 PDiff = Limit - POld; // Just obeyed limit.
987
988 if (PDiff) {
989 Delta.Excess = PressureChange(i);
990 Delta.Excess.setUnitInc(PDiff);
991 break;
992 }
993 }
994}
995
996/// Find the max change in max pressure that either surpasses a critical PSet
997/// limit or exceeds the current MaxPressureLimit.
998///
999/// FIXME: comparing each element of the old and new MaxPressure vectors here is
1000/// silly. It's done now to demonstrate the concept but will go away with a
1001/// RegPressureTracker API change to work with pressure differences.
1002static void computeMaxPressureDelta(ArrayRef<unsigned> OldMaxPressureVec,
1003 ArrayRef<unsigned> NewMaxPressureVec,
1004 ArrayRef<PressureChange> CriticalPSets,
1005 ArrayRef<unsigned> MaxPressureLimit,
1006 RegPressureDelta &Delta) {
1007 Delta.CriticalMax = PressureChange();
1008 Delta.CurrentMax = PressureChange();
1009
1010 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
1011 for (unsigned i = 0, e = OldMaxPressureVec.size(); i < e; ++i) {
1012 unsigned POld = OldMaxPressureVec[i];
1013 unsigned PNew = NewMaxPressureVec[i];
1014 if (PNew == POld) // No change in this set in the common case.
1015 continue;
1016
1017 if (!Delta.CriticalMax.isValid()) {
1018 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < i)
1019 ++CritIdx;
1020
1021 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == i) {
1022 int PDiff = (int)PNew - CriticalPSets[CritIdx].getUnitInc();
1023 if (PDiff > 0) {
1024 Delta.CriticalMax = PressureChange(i);
1025 Delta.CriticalMax.setUnitInc(PDiff);
1026 }
1027 }
1028 }
1029 // Find the first increase above MaxPressureLimit.
1030 // (Ignores negative MDiff).
1031 if (!Delta.CurrentMax.isValid() && PNew > MaxPressureLimit[i]) {
1032 Delta.CurrentMax = PressureChange(i);
1033 Delta.CurrentMax.setUnitInc(PNew - POld);
1034 if (CritIdx == CritEnd || Delta.CriticalMax.isValid())
1035 break;
1036 }
1037 }
1038}
1039
1040/// Record the upward impact of a single instruction on current register
1041/// pressure. Unlike the advance/recede pressure tracking interface, this does
1042/// not discover live in/outs.
1043///
1044/// This is intended for speculative queries. It leaves pressure inconsistent
1045/// with the current position, so must be restored by the caller.
1047 assert(!MI->isDebugOrPseudoInstr() && "Expect a nondebug instruction.");
1048
1049 SlotIndex SlotIdx;
1050 if (RequireIntervals)
1051 SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
1052
1053 // Account for register pressure similar to RegPressureTracker::recede().
1054 RegisterOperands RegOpers;
1055 RegOpers.collect(*MI, *TRI, *MRI, TrackLaneMasks, /*IgnoreDead=*/true);
1056 assert(RegOpers.DeadDefs.empty());
1057 if (TrackLaneMasks)
1058 RegOpers.adjustLaneLiveness(*LIS, *MRI, SlotIdx);
1059 else if (RequireIntervals)
1060 RegOpers.detectDeadDefs(*MI, *LIS, *MRI);
1061
1062 // Boost max pressure for all dead defs together.
1063 // Since CurrSetPressure and MaxSetPressure
1064 bumpDeadDefs(RegOpers.DeadDefs);
1065
1066 // Kill liveness at live defs.
1067 for (const VRegMaskOrUnit &P : RegOpers.Defs) {
1068 LaneBitmask LiveAfter = LiveRegs.contains(P.VRegOrUnit);
1069 LaneBitmask UseLanes = getRegLanes(RegOpers.Uses, P.VRegOrUnit);
1070 LaneBitmask DefLanes = P.LaneMask;
1071 LaneBitmask LiveBefore = (LiveAfter & ~DefLanes) | UseLanes;
1072
1073 // There may be parts of the register that were dead before the
1074 // instruction, but became live afterwards.
1075 decreaseRegPressure(P.VRegOrUnit, LiveAfter, LiveAfter & LiveBefore);
1076 }
1077 // Generate liveness for uses. Also handle any uses which overlap with defs.
1078 for (const VRegMaskOrUnit &P : RegOpers.Uses) {
1079 LaneBitmask LiveAfter = LiveRegs.contains(P.VRegOrUnit);
1080 LaneBitmask LiveBefore = LiveAfter | P.LaneMask;
1081 increaseRegPressure(P.VRegOrUnit, LiveAfter, LiveBefore);
1082 }
1083}
1084
1085/// Consider the pressure increase caused by traversing this instruction
1086/// bottom-up. Find the pressure set with the most change beyond its pressure
1087/// limit based on the tracker's current pressure, and return the change in
1088/// number of register units of that pressure set introduced by this
1089/// instruction.
1090///
1091/// This assumes that the current LiveOut set is sufficient.
1092///
1093/// This is expensive for an on-the-fly query because it calls
1094/// bumpUpwardPressure to recompute the pressure sets based on current
1095/// liveness. This mainly exists to verify correctness, e.g. with
1096/// -verify-misched. getUpwardPressureDelta is the fast version of this query
1097/// that uses the per-SUnit cache of the PressureDiff.
1100 RegPressureDelta &Delta,
1101 ArrayRef<PressureChange> CriticalPSets,
1102 ArrayRef<unsigned> MaxPressureLimit) {
1103 // Snapshot Pressure.
1104 // FIXME: The snapshot heap space should persist. But I'm planning to
1105 // summarize the pressure effect so we don't need to snapshot at all.
1106 std::vector<unsigned> SavedPressure = CurrSetPressure;
1107 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
1108
1110
1111 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
1112 LiveThruPressure);
1113 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
1114 MaxPressureLimit, Delta);
1115 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
1116 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
1117
1118 // Restore the tracker's state.
1119 P.MaxSetPressure.swap(SavedMaxPressure);
1120 CurrSetPressure.swap(SavedPressure);
1121
1122#ifndef NDEBUG
1123 if (!PDiff)
1124 return;
1125
1126 // Check if the alternate algorithm yields the same result.
1127 RegPressureDelta Delta2;
1128 getUpwardPressureDelta(MI, *PDiff, Delta2, CriticalPSets, MaxPressureLimit);
1129 if (Delta != Delta2) {
1130 dbgs() << "PDiff: ";
1131 PDiff->dump(*TRI);
1132 dbgs() << "DELTA: " << *MI;
1133 if (Delta.Excess.isValid())
1134 dbgs() << "Excess1 " << TRI->getRegPressureSetName(Delta.Excess.getPSet())
1135 << " " << Delta.Excess.getUnitInc() << "\n";
1136 if (Delta.CriticalMax.isValid())
1137 dbgs() << "Critic1 " << TRI->getRegPressureSetName(Delta.CriticalMax.getPSet())
1138 << " " << Delta.CriticalMax.getUnitInc() << "\n";
1139 if (Delta.CurrentMax.isValid())
1140 dbgs() << "CurrMx1 " << TRI->getRegPressureSetName(Delta.CurrentMax.getPSet())
1141 << " " << Delta.CurrentMax.getUnitInc() << "\n";
1142 if (Delta2.Excess.isValid())
1143 dbgs() << "Excess2 " << TRI->getRegPressureSetName(Delta2.Excess.getPSet())
1144 << " " << Delta2.Excess.getUnitInc() << "\n";
1145 if (Delta2.CriticalMax.isValid())
1146 dbgs() << "Critic2 " << TRI->getRegPressureSetName(Delta2.CriticalMax.getPSet())
1147 << " " << Delta2.CriticalMax.getUnitInc() << "\n";
1148 if (Delta2.CurrentMax.isValid())
1149 dbgs() << "CurrMx2 " << TRI->getRegPressureSetName(Delta2.CurrentMax.getPSet())
1150 << " " << Delta2.CurrentMax.getUnitInc() << "\n";
1151 llvm_unreachable("RegP Delta Mismatch");
1152 }
1153#endif
1154}
1155
1156/// This is the fast version of querying register pressure that does not
1157/// directly depend on current liveness.
1158///
1159/// @param Delta captures information needed for heuristics.
1160///
1161/// @param CriticalPSets Are the pressure sets that are known to exceed some
1162/// limit within the region, not necessarily at the current position.
1163///
1164/// @param MaxPressureLimit Is the max pressure within the region, not
1165/// necessarily at the current position.
1167getUpwardPressureDelta(const MachineInstr *MI, /*const*/ PressureDiff &PDiff,
1168 RegPressureDelta &Delta,
1169 ArrayRef<PressureChange> CriticalPSets,
1170 ArrayRef<unsigned> MaxPressureLimit) const {
1171 unsigned CritIdx = 0, CritEnd = CriticalPSets.size();
1173 PDiffI = PDiff.begin(), PDiffE = PDiff.end();
1174 PDiffI != PDiffE && PDiffI->isValid(); ++PDiffI) {
1175
1176 unsigned PSetID = PDiffI->getPSet();
1177 unsigned Limit = RCI->getRegPressureSetLimit(PSetID);
1178 if (!LiveThruPressure.empty())
1179 Limit += LiveThruPressure[PSetID];
1180
1181 unsigned POld = CurrSetPressure[PSetID];
1182 unsigned MOld = P.MaxSetPressure[PSetID];
1183 unsigned MNew = MOld;
1184 // Ignore DeadDefs here because they aren't captured by PressureChange.
1185 unsigned PNew = POld + PDiffI->getUnitInc();
1186 assert((PDiffI->getUnitInc() >= 0) == (PNew >= POld)
1187 && "PSet overflow/underflow");
1188 if (PNew > MOld)
1189 MNew = PNew;
1190 // Check if current pressure has exceeded the limit.
1191 if (!Delta.Excess.isValid()) {
1192 unsigned ExcessInc = 0;
1193 if (PNew > Limit)
1194 ExcessInc = POld > Limit ? PNew - POld : PNew - Limit;
1195 else if (POld > Limit)
1196 ExcessInc = Limit - POld;
1197 if (ExcessInc) {
1198 Delta.Excess = PressureChange(PSetID);
1199 Delta.Excess.setUnitInc(ExcessInc);
1200 }
1201 }
1202 // Check if max pressure has exceeded a critical pressure set max.
1203 if (MNew == MOld)
1204 continue;
1205 if (!Delta.CriticalMax.isValid()) {
1206 while (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() < PSetID)
1207 ++CritIdx;
1208
1209 if (CritIdx != CritEnd && CriticalPSets[CritIdx].getPSet() == PSetID) {
1210 int CritInc = (int)MNew - CriticalPSets[CritIdx].getUnitInc();
1211 if (CritInc > 0 && CritInc <= std::numeric_limits<int16_t>::max()) {
1212 Delta.CriticalMax = PressureChange(PSetID);
1213 Delta.CriticalMax.setUnitInc(CritInc);
1214 }
1215 }
1216 }
1217 // Check if max pressure has exceeded the current max.
1218 if (!Delta.CurrentMax.isValid() && MNew > MaxPressureLimit[PSetID]) {
1219 Delta.CurrentMax = PressureChange(PSetID);
1220 Delta.CurrentMax.setUnitInc(MNew - MOld);
1221 }
1222 }
1223}
1224
1225/// Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
1226/// The query starts with a lane bitmask which gets lanes/bits removed for every
1227/// use we find.
1229 LaneBitmask LastUseMask,
1230 SlotIndex PriorUseIdx, SlotIndex NextUseIdx,
1231 const MachineRegisterInfo &MRI,
1232 const LiveIntervals *LIS) {
1234 // FIXME: The static_cast is a bug.
1235 Register Reg =
1236 VRegOrUnit.isVirtualReg()
1237 ? VRegOrUnit.asVirtualReg()
1238 : Register(static_cast<unsigned>(VRegOrUnit.asMCRegUnit()));
1239 for (const MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1240 if (MO.isUndef())
1241 continue;
1242 const MachineInstr *MI = MO.getParent();
1243 SlotIndex InstSlot = LIS->getInstructionIndex(*MI).getRegSlot();
1244 if (InstSlot >= PriorUseIdx && InstSlot < NextUseIdx) {
1245 unsigned SubRegIdx = MO.getSubReg();
1246 LaneBitmask UseMask = TRI.getSubRegIndexLaneMask(SubRegIdx);
1247 LastUseMask &= ~UseMask;
1248 if (LastUseMask.none())
1249 return LaneBitmask::getNone();
1250 }
1251 }
1252 return LastUseMask;
1253}
1254
1256 SlotIndex Pos) const {
1257 assert(RequireIntervals);
1258 return getLanesWithProperty(
1259 *LIS, *MRI, TrackLaneMasks, VRegOrUnit, Pos, LaneBitmask::getAll(),
1260 [](const LiveRange &LR, SlotIndex Pos) { return LR.liveAt(Pos); });
1261}
1262
1264 SlotIndex Pos) const {
1265 assert(RequireIntervals);
1266 return getLanesWithProperty(
1267 *LIS, *MRI, TrackLaneMasks, VRegOrUnit, Pos.getBaseIndex(),
1268 LaneBitmask::getNone(), [](const LiveRange &LR, SlotIndex Pos) {
1269 const LiveRange::Segment *S = LR.getSegmentContaining(Pos);
1270 return S != nullptr && S->end == Pos.getRegSlot();
1271 });
1272}
1273
1275 SlotIndex Pos) const {
1276 assert(RequireIntervals);
1277 return getLanesWithProperty(
1278 *LIS, *MRI, TrackLaneMasks, VRegOrUnit, Pos, LaneBitmask::getNone(),
1279 [](const LiveRange &LR, SlotIndex Pos) {
1280 const LiveRange::Segment *S = LR.getSegmentContaining(Pos);
1281 return S != nullptr && S->start < Pos.getRegSlot(true) &&
1282 S->end != Pos.getDeadSlot();
1283 });
1284}
1285
1286/// Record the downward impact of a single instruction on current register
1287/// pressure. Unlike the advance/recede pressure tracking interface, this does
1288/// not discover live in/outs.
1289///
1290/// This is intended for speculative queries. It leaves pressure inconsistent
1291/// with the current position, so must be restored by the caller.
1293 assert(!MI->isDebugOrPseudoInstr() && "Expect a nondebug instruction.");
1294
1295 SlotIndex SlotIdx;
1296 if (RequireIntervals)
1297 SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
1298
1299 // Account for register pressure similar to RegPressureTracker::advance().
1300 RegisterOperands RegOpers;
1301 RegOpers.collect(*MI, *TRI, *MRI, TrackLaneMasks, /*IgnoreDead=*/false);
1302 if (TrackLaneMasks)
1303 RegOpers.adjustLaneLiveness(*LIS, *MRI, SlotIdx);
1304
1305 if (RequireIntervals) {
1306 for (const VRegMaskOrUnit &Use : RegOpers.Uses) {
1307 VirtRegOrUnit VRegOrUnit = Use.VRegOrUnit;
1308 LaneBitmask LastUseMask = getLastUsedLanes(VRegOrUnit, SlotIdx);
1309 if (LastUseMask.none())
1310 continue;
1311 // The LastUseMask is queried from the liveness information of instruction
1312 // which may be further down the schedule. Some lanes may actually not be
1313 // last uses for the current position.
1314 // FIXME: allow the caller to pass in the list of vreg uses that remain
1315 // to be bottom-scheduled to avoid searching uses at each query.
1316 SlotIndex CurrIdx = getCurrSlot();
1317 LastUseMask =
1318 findUseBetween(VRegOrUnit, LastUseMask, CurrIdx, SlotIdx, *MRI, LIS);
1319 if (LastUseMask.none())
1320 continue;
1321
1322 LaneBitmask LiveMask = LiveRegs.contains(VRegOrUnit);
1323 LaneBitmask NewMask = LiveMask & ~LastUseMask;
1324 decreaseRegPressure(VRegOrUnit, LiveMask, NewMask);
1325 }
1326 }
1327
1328 // Generate liveness for defs.
1329 for (const VRegMaskOrUnit &Def : RegOpers.Defs) {
1330 LaneBitmask LiveMask = LiveRegs.contains(Def.VRegOrUnit);
1331 LaneBitmask NewMask = LiveMask | Def.LaneMask;
1332 increaseRegPressure(Def.VRegOrUnit, LiveMask, NewMask);
1333 }
1334
1335 // Boost pressure for all dead defs together.
1336 bumpDeadDefs(RegOpers.DeadDefs);
1337}
1338
1339/// Consider the pressure increase caused by traversing this instruction
1340/// top-down. Find the register class with the most change in its pressure limit
1341/// based on the tracker's current pressure, and return the number of excess
1342/// register units of that pressure set introduced by this instruction.
1343///
1344/// This assumes that the current LiveIn set is sufficient.
1345///
1346/// This is expensive for an on-the-fly query because it calls
1347/// bumpDownwardPressure to recompute the pressure sets based on current
1348/// liveness. We don't yet have a fast version of downward pressure tracking
1349/// analogous to getUpwardPressureDelta.
1352 ArrayRef<PressureChange> CriticalPSets,
1353 ArrayRef<unsigned> MaxPressureLimit) {
1354 // Snapshot Pressure.
1355 std::vector<unsigned> SavedPressure = CurrSetPressure;
1356 std::vector<unsigned> SavedMaxPressure = P.MaxSetPressure;
1357
1359
1360 computeExcessPressureDelta(SavedPressure, CurrSetPressure, Delta, RCI,
1361 LiveThruPressure);
1362 computeMaxPressureDelta(SavedMaxPressure, P.MaxSetPressure, CriticalPSets,
1363 MaxPressureLimit, Delta);
1364 assert(Delta.CriticalMax.getUnitInc() >= 0 &&
1365 Delta.CurrentMax.getUnitInc() >= 0 && "cannot decrease max pressure");
1366
1367 // Restore the tracker's state.
1368 P.MaxSetPressure.swap(SavedMaxPressure);
1369 CurrSetPressure.swap(SavedPressure);
1370}
1371
1372/// Get the pressure of each PSet after traversing this instruction bottom-up.
1375 std::vector<unsigned> &PressureResult,
1376 std::vector<unsigned> &MaxPressureResult) {
1377 // Snapshot pressure.
1378 PressureResult = CurrSetPressure;
1379 MaxPressureResult = P.MaxSetPressure;
1380
1382
1383 // Current pressure becomes the result. Restore current pressure.
1384 P.MaxSetPressure.swap(MaxPressureResult);
1385 CurrSetPressure.swap(PressureResult);
1386}
1387
1388/// Get the pressure of each PSet after traversing this instruction top-down.
1391 std::vector<unsigned> &PressureResult,
1392 std::vector<unsigned> &MaxPressureResult) {
1393 // Snapshot pressure.
1394 PressureResult = CurrSetPressure;
1395 MaxPressureResult = P.MaxSetPressure;
1396
1398
1399 // Current pressure becomes the result. Restore current pressure.
1400 P.MaxSetPressure.swap(MaxPressureResult);
1401 CurrSetPressure.swap(PressureResult);
1402}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
Register Usage Information Collector
static void computeExcessPressureDelta(ArrayRef< unsigned > OldPressureVec, ArrayRef< unsigned > NewPressureVec, RegPressureDelta &Delta, const RegisterClassInfo *RCI, ArrayRef< unsigned > LiveThruPressureVec)
Find the max change in excess pressure across all sets.
static LaneBitmask getLiveLanesAt(const LiveIntervals &LIS, const MachineRegisterInfo &MRI, bool TrackLaneMasks, VirtRegOrUnit VRegOrUnit, SlotIndex Pos)
static void increaseSetPressure(std::vector< unsigned > &CurrSetPressure, const MachineRegisterInfo &MRI, VirtRegOrUnit VRegOrUnit, LaneBitmask PrevMask, LaneBitmask NewMask)
Increase pressure for each pressure set provided by TargetRegisterInfo.
static LaneBitmask getRegLanes(ArrayRef< VRegMaskOrUnit > RegUnits, VirtRegOrUnit VRegOrUnit)
static void removeRegLanes(SmallVectorImpl< VRegMaskOrUnit > &RegUnits, VRegMaskOrUnit Pair)
static void computeMaxPressureDelta(ArrayRef< unsigned > OldMaxPressureVec, ArrayRef< unsigned > NewMaxPressureVec, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit, RegPressureDelta &Delta)
Find the max change in max pressure that either surpasses a critical PSet limit or exceeds the curren...
static LaneBitmask getLanesWithProperty(const LiveIntervals &LIS, const MachineRegisterInfo &MRI, bool TrackLaneMasks, VirtRegOrUnit VRegOrUnit, SlotIndex Pos, LaneBitmask SafeDefault, bool(*Property)(const LiveRange &LR, SlotIndex Pos))
static void setRegZero(SmallVectorImpl< VRegMaskOrUnit > &RegUnits, VirtRegOrUnit VRegOrUnit)
static LaneBitmask findUseBetween(VirtRegOrUnit VRegOrUnit, LaneBitmask LastUseMask, SlotIndex PriorUseIdx, SlotIndex NextUseIdx, const MachineRegisterInfo &MRI, const LiveIntervals *LIS)
Helper to find a vreg use between two indices [PriorUseIdx, NextUseIdx).
static void addRegLanes(SmallVectorImpl< VRegMaskOrUnit > &RegUnits, VRegMaskOrUnit Pair)
static void decreaseSetPressure(std::vector< unsigned > &CurrSetPressure, const MachineRegisterInfo &MRI, VirtRegOrUnit VRegOrUnit, LaneBitmask PrevMask, LaneBitmask NewMask)
Decrease pressure for each pressure set provided by TargetRegisterInfo.
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
LiveInterval & getInterval(Register Reg)
LiveRange * getCachedRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit if it has already been computed, or nullptr if it hasn't...
This class represents the liveness of a register, stack slot, etc.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
bool liveAt(SlotIndex index) const
LLVM_ABI void clear()
LLVM_ABI void init(const MachineRegisterInfo &MRI)
MachineInstrBundleIterator< const MachineInstr > const_iterator
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
Register getReg() const
getReg - Returns the register number.
bool isInternalRead() const
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
PSetIterator getPressureSets(VirtRegOrUnit VRegOrUnit) const
Get an iterator over the pressure sets affected by the virtual register or register unit.
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
const TargetRegisterInfo * getTargetRegisterInfo() const
LLVM_ABI LaneBitmask getMaxLaneMaskForVReg(Register Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
Iterate over the pressure sets affected by the given physical or virtual register.
unsigned getWeight() const
Capture a change in pressure for a single pressure set.
unsigned getPSetOrMax() const
LLVM_ABI void dump() const
unsigned getPSet() const
List of PressureChanges in order of increasing, unique PSetID.
const PressureChange * const_iterator
LLVM_ABI void dump(const TargetRegisterInfo &TRI) const
const_iterator end() const
LLVM_ABI void addPressureChange(VirtRegOrUnit VRegOrUnit, bool IsDec, const MachineRegisterInfo *MRI)
Add a change in pressure to the pressure diff of a given instruction.
const_iterator begin() const
LLVM_ABI void addInstruction(unsigned Idx, const RegisterOperands &RegOpers, const MachineRegisterInfo &MRI)
Record pressure difference induced by the given operand list to node with index Idx.
LLVM_ABI void init(unsigned N)
Initialize an array of N PressureDiffs.
LLVM_ABI void closeRegion()
Finalize the region boundaries and recored live ins and live outs.
LLVM_ABI void discoverLiveIn(VRegMaskOrUnit Pair)
Add Reg to the live in set and increase max pressure.
LLVM_ABI void closeBottom()
Set the boundary for the bottom of the region and summarize live outs.
LLVM_ABI void recede(SmallVectorImpl< VRegMaskOrUnit > *LiveUses=nullptr)
Recede across the previous instruction.
LLVM_ABI void bumpDownwardPressure(const MachineInstr *MI)
Record the downward impact of a single instruction on current register pressure.
LLVM_ABI void addLiveRegs(ArrayRef< VRegMaskOrUnit > Regs)
Force liveness of virtual registers or physical register units.
LLVM_ABI void recedeSkipDebugValues()
Recede until we find an instruction which is not a DebugValue.
LLVM_ABI void getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction bottom-up.
LLVM_ABI void initLiveThru(const RegPressureTracker &RPTracker)
Initialize the LiveThru pressure set based on the untied defs found in RPTracker.
LLVM_ABI void bumpDeadDefs(ArrayRef< VRegMaskOrUnit > DeadDefs)
RegPressureTracker(IntervalPressure &rp)
LLVM_ABI void dump() const
LLVM_ABI void init(const MachineFunction *mf, const RegisterClassInfo *rci, const LiveIntervals *lis, const MachineBasicBlock *mbb, MachineBasicBlock::const_iterator pos, bool TrackLaneMasks, bool TrackUntiedDefs)
Setup the RegPressureTracker.
LLVM_ABI void discoverLiveInOrOut(VRegMaskOrUnit Pair, SmallVectorImpl< VRegMaskOrUnit > &LiveInOrOut)
LLVM_ABI LaneBitmask getLiveThroughAt(VirtRegOrUnit VRegOrUnit, SlotIndex Pos) const
LLVM_ABI bool isBottomClosed() const
Does this pressure result have a valid bottom position and live outs.
LLVM_ABI LaneBitmask getLiveLanesAt(VirtRegOrUnit VRegOrUnit, SlotIndex Pos) const
bool hasUntiedDef(Register VirtReg) const
LLVM_ABI void closeTop()
Set the boundary for the top of the region and summarize live ins.
LLVM_ABI void getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction top-down.
LLVM_ABI void advance()
Advance across the current instruction.
LLVM_ABI bool isTopClosed() const
Does this pressure result have a valid top position and live ins.
LLVM_ABI void bumpUpwardPressure(const MachineInstr *MI)
Record the upward impact of a single instruction on current register pressure.
LLVM_ABI LaneBitmask getLastUsedLanes(VirtRegOrUnit VRegOrUnit, SlotIndex Pos) const
LLVM_ABI void increaseRegPressure(VirtRegOrUnit VRegOrUnit, LaneBitmask PreviousMask, LaneBitmask NewMask)
LLVM_ABI void getDownwardPressure(const MachineInstr *MI, std::vector< unsigned > &PressureResult, std::vector< unsigned > &MaxPressureResult)
Get the pressure of each PSet after traversing this instruction top-down.
LLVM_ABI SlotIndex getCurrSlot() const
Get the SlotIndex for the first nondebug instruction including or after the current position.
LLVM_ABI void decreaseRegPressure(VirtRegOrUnit VRegOrUnit, LaneBitmask PreviousMask, LaneBitmask NewMask)
LLVM_ABI void getUpwardPressure(const MachineInstr *MI, std::vector< unsigned > &PressureResult, std::vector< unsigned > &MaxPressureResult)
Get the pressure of each PSet after traversing this instruction bottom-up.
LLVM_ABI void discoverLiveOut(VRegMaskOrUnit Pair)
Add Reg to the live out set and increase max pressure.
LLVM_ABI void getUpwardPressureDelta(const MachineInstr *MI, PressureDiff &PDiff, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit) const
This is the fast version of querying register pressure that does not directly depend on current liven...
unsigned getRegPressureSetLimit(unsigned Idx) const
Get the register unit limit for the given pressure set index.
List of registers defined and used by a machine instruction.
LLVM_ABI void detectDeadDefs(const MachineInstr &MI, const LiveIntervals &LIS, const MachineRegisterInfo &MRI)
Use liveness information to find dead defs at MI's dead slot not marked with a dead flag and move the...
LLVM_ABI void adjustLaneLiveness(const LiveIntervals &LIS, const MachineRegisterInfo &MRI, SlotIndex Pos)
Use liveness information to find out which uses/defs are partially undefined/dead at Pos and adjust t...
SmallVector< VRegMaskOrUnit, 8 > Defs
List of virtual registers and register units defined by the instruction which are not dead.
LLVM_ABI void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
SmallVector< VRegMaskOrUnit, 8 > DeadDefs
List of virtual registers and register units defined by the instruction but dead.
SmallVector< VRegMaskOrUnit, 8 > Uses
List of virtual registers and register units read by the instruction.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Wrapper class representing a virtual register or register unit.
Definition Register.h:175
constexpr bool isVirtualReg() const
Definition Register.h:191
constexpr MCRegUnit asMCRegUnit() const
Definition Register.h:195
constexpr Register asVirtualReg() const
Definition Register.h:200
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition LaneBitmask.h:92
LLVM_ATTRIBUTE_RETURNS_NONNULL void * safe_calloc(size_t Count, size_t Sz)
Definition MemAlloc.h:38
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
@ Other
Any other memory.
Definition ModRef.h:68
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
LLVM_ABI void dumpRegSetPressure(ArrayRef< unsigned > SetPressure, const TargetRegisterInfo *TRI)
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
LLVM_ABI Printable printVRegOrUnit(VirtRegOrUnit VRegOrUnit, const TargetRegisterInfo *TRI)
Create Printable object to print virtual registers and physical registers on a raw_ostream.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
RegisterPressure computed within a region of instructions delimited by TopIdx and BottomIdx.
LLVM_ABI void reset()
Clear the result so it can be used for another round of pressure tracking.
LLVM_ABI void openBottom(SlotIndex PrevBottom)
If the current bottom is not greater than the previous index, open it.
SlotIndex TopIdx
Record the boundary of the region being tracked.
LLVM_ABI void openTop(SlotIndex NextTop)
If the current top is not less than or equal to the next index, open it.
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool none() const
Definition LaneBitmask.h:52
constexpr bool any() const
Definition LaneBitmask.h:53
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
This represents a simple continuous liveness interval for a value.
Store the effects of a change in pressure on things that MI scheduler cares about.
LLVM_ABI void dump() const
RegisterPressure computed within a region of instructions delimited by TopPos and BottomPos.
MachineBasicBlock::const_iterator TopPos
Record the boundary of the region being tracked.
MachineBasicBlock::const_iterator BottomPos
LLVM_ABI void openTop(MachineBasicBlock::const_iterator PrevTop)
If the current top is the previous instruction (before receding), open it.
LLVM_ABI void reset()
Clear the result so it can be used for another round of pressure tracking.
LLVM_ABI void openBottom(MachineBasicBlock::const_iterator PrevBottom)
If the current bottom is the previous instr (before advancing), open it.
SmallVector< VRegMaskOrUnit, 8 > LiveOutRegs
SmallVector< VRegMaskOrUnit, 8 > LiveInRegs
List of live in virtual registers or physical register units.
LLVM_ABI void dump(const TargetRegisterInfo *TRI) const
std::vector< unsigned > MaxSetPressure
Map of max reg pressure indexed by pressure set ID, not class ID.