46#define DEBUG_TYPE "si-insert-waitcnts"
49 "Force emit s_waitcnt expcnt(0) instrs");
51 "Force emit s_waitcnt lgkmcnt(0) instrs");
53 "Force emit s_waitcnt vmcnt(0) instrs");
57 cl::desc(
"Force all waitcnt instrs to be emitted as "
58 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
62 "amdgpu-waitcnt-load-forcezero",
63 cl::desc(
"Force all waitcnt load counters to wait until 0"),
77 SAMPLE_CNT = NUM_NORMAL_INST_CNTS,
81 NUM_EXTENDED_INST_CNTS,
82 NUM_INST_CNTS = NUM_EXTENDED_INST_CNTS
96auto inst_counter_types(InstCounterType MaxCounter = NUM_INST_CNTS) {
97 return enum_seq(LOAD_CNT, MaxCounter);
100using RegInterval = std::pair<int, int>;
102struct HardwareLimits {
106 unsigned StorecntMax;
107 unsigned SamplecntMax;
113#define AMDGPU_DECLARE_WAIT_EVENTS(DECL) \
115 DECL(VMEM_READ_ACCESS) \
116 DECL(VMEM_SAMPLER_READ_ACCESS) \
117 DECL(VMEM_BVH_READ_ACCESS) \
118 DECL(VMEM_WRITE_ACCESS) \
119 DECL(SCRATCH_WRITE_ACCESS) \
128 DECL(EXP_POS_ACCESS) \
129 DECL(EXP_PARAM_ACCESS) \
134#define AMDGPU_EVENT_ENUM(Name) Name,
139#undef AMDGPU_EVENT_ENUM
141#define AMDGPU_EVENT_NAME(Name) #Name,
145#undef AMDGPU_EVENT_NAME
154enum RegisterMapping {
155 SQ_MAX_PGM_VGPRS = 2048,
157 SQ_MAX_PGM_SGPRS = 128,
163 FIRST_LDS_VGPR = SQ_MAX_PGM_VGPRS,
165 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_LDS_VGPRS,
186static const unsigned instrsForExtendedCounterTypes[NUM_EXTENDED_INST_CNTS] = {
187 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT, AMDGPU::S_WAIT_EXPCNT,
188 AMDGPU::S_WAIT_STORECNT, AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
189 AMDGPU::S_WAIT_KMCNT, AMDGPU::S_WAIT_XCNT};
197static bool isNormalMode(InstCounterType MaxCounter) {
198 return MaxCounter == NUM_NORMAL_INST_CNTS;
203 assert(updateVMCntOnly(Inst));
205 return VMEM_NOSAMPLER;
219 return VMEM_NOSAMPLER;
231 return Wait.StoreCnt;
233 return Wait.SampleCnt;
246 unsigned &WC = getCounterRef(
Wait,
T);
247 WC = std::min(WC,
Count);
251 getCounterRef(
Wait,
T) = ~0
u;
255 return getCounterRef(
Wait,
T);
259InstCounterType eventCounter(
const unsigned *masks, WaitEventType
E) {
260 for (
auto T : inst_counter_types()) {
261 if (masks[
T] & (1 <<
E))
267class WaitcntBrackets;
275class WaitcntGenerator {
277 const GCNSubtarget *ST =
nullptr;
278 const SIInstrInfo *TII =
nullptr;
279 AMDGPU::IsaVersion IV;
280 InstCounterType MaxCounter;
284 WaitcntGenerator() =
default;
285 WaitcntGenerator(
const MachineFunction &MF, InstCounterType MaxCounter)
286 : ST(&MF.getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
293 bool isOptNone()
const {
return OptNone; }
307 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
308 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
312 bool promoteSoftWaitCnt(MachineInstr *Waitcnt)
const;
316 virtual bool createNewWaitcnt(MachineBasicBlock &
Block,
318 AMDGPU::Waitcnt
Wait) = 0;
322 virtual const unsigned *getWaitEventMask()
const = 0;
326 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const = 0;
328 virtual ~WaitcntGenerator() =
default;
331 static constexpr unsigned
332 eventMask(std::initializer_list<WaitEventType> Events) {
334 for (
auto &
E : Events)
341class WaitcntGeneratorPreGFX12 :
public WaitcntGenerator {
343 WaitcntGeneratorPreGFX12() =
default;
344 WaitcntGeneratorPreGFX12(
const MachineFunction &MF)
345 : WaitcntGenerator(MF, NUM_NORMAL_INST_CNTS) {}
348 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
349 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
352 bool createNewWaitcnt(MachineBasicBlock &
Block,
354 AMDGPU::Waitcnt
Wait)
override;
356 const unsigned *getWaitEventMask()
const override {
359 static const unsigned WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
360 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS,
361 VMEM_BVH_READ_ACCESS}),
362 eventMask({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
363 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
364 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
365 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
371 return WaitEventMaskForInstPreGFX12;
374 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
377class WaitcntGeneratorGFX12Plus :
public WaitcntGenerator {
379 WaitcntGeneratorGFX12Plus() =
default;
380 WaitcntGeneratorGFX12Plus(
const MachineFunction &MF,
381 InstCounterType MaxCounter)
382 : WaitcntGenerator(MF, MaxCounter) {}
385 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
386 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
389 bool createNewWaitcnt(MachineBasicBlock &
Block,
391 AMDGPU::Waitcnt
Wait)
override;
393 const unsigned *getWaitEventMask()
const override {
396 static const unsigned WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
397 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS}),
398 eventMask({LDS_ACCESS, GDS_ACCESS}),
399 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
400 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
401 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
402 eventMask({VMEM_SAMPLER_READ_ACCESS}),
403 eventMask({VMEM_BVH_READ_ACCESS}),
404 eventMask({SMEM_ACCESS, SQ_MESSAGE}),
405 eventMask({VMEM_GROUP, SMEM_GROUP})};
407 return WaitEventMaskForInstGFX12Plus;
410 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
413class SIInsertWaitcnts {
415 const GCNSubtarget *ST;
416 InstCounterType SmemAccessCounter;
417 InstCounterType MaxCounter;
418 const unsigned *WaitEventMaskForInst;
421 const SIInstrInfo *TII =
nullptr;
422 const SIRegisterInfo *TRI =
nullptr;
423 const MachineRegisterInfo *MRI =
nullptr;
425 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
426 DenseMap<MachineBasicBlock *, bool> PreheadersToFlush;
427 MachineLoopInfo *MLI;
428 MachinePostDominatorTree *PDT;
432 std::unique_ptr<WaitcntBrackets> Incoming;
436 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
438 bool ForceEmitWaitcnt[NUM_INST_CNTS];
443 WaitcntGeneratorPreGFX12 WCGPreGFX12;
444 WaitcntGeneratorGFX12Plus WCGGFX12Plus;
446 WaitcntGenerator *WCG =
nullptr;
450 DenseSet<MachineInstr *> ReleaseVGPRInsts;
452 HardwareLimits Limits;
455 SIInsertWaitcnts(MachineLoopInfo *MLI, MachinePostDominatorTree *PDT,
457 : MLI(MLI), PDT(PDT), AA(AA) {
458 (void)ForceExpCounter;
459 (void)ForceLgkmCounter;
460 (void)ForceVMCounter;
463 unsigned getWaitCountMax(InstCounterType
T)
const {
466 return Limits.LoadcntMax;
468 return Limits.DscntMax;
470 return Limits.ExpcntMax;
472 return Limits.StorecntMax;
474 return Limits.SamplecntMax;
476 return Limits.BvhcntMax;
478 return Limits.KmcntMax;
480 return Limits.XcntMax;
487 bool shouldFlushVmCnt(MachineLoop *
ML,
const WaitcntBrackets &Brackets);
488 bool isPreheaderToFlush(MachineBasicBlock &
MBB,
489 const WaitcntBrackets &ScoreBrackets);
490 bool isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const;
491 bool run(MachineFunction &MF);
493 bool isForceEmitWaitcnt()
const {
494 for (
auto T : inst_counter_types())
495 if (ForceEmitWaitcnt[
T])
500 void setForceEmitWaitcnt() {
506 ForceEmitWaitcnt[
EXP_CNT] =
true;
508 ForceEmitWaitcnt[
EXP_CNT] =
false;
513 ForceEmitWaitcnt[DS_CNT] =
true;
514 ForceEmitWaitcnt[KM_CNT] =
true;
516 ForceEmitWaitcnt[DS_CNT] =
false;
517 ForceEmitWaitcnt[KM_CNT] =
false;
522 ForceEmitWaitcnt[LOAD_CNT] =
true;
523 ForceEmitWaitcnt[SAMPLE_CNT] =
true;
524 ForceEmitWaitcnt[BVH_CNT] =
true;
526 ForceEmitWaitcnt[LOAD_CNT] =
false;
527 ForceEmitWaitcnt[SAMPLE_CNT] =
false;
528 ForceEmitWaitcnt[BVH_CNT] =
false;
535 WaitEventType getVmemWaitEventType(
const MachineInstr &Inst)
const {
537 case AMDGPU::GLOBAL_INV:
538 return VMEM_READ_ACCESS;
539 case AMDGPU::GLOBAL_WB:
540 case AMDGPU::GLOBAL_WBINV:
541 return VMEM_WRITE_ACCESS;
547 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
548 VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
559 if (TII->mayAccessScratchThroughFlat(Inst))
560 return SCRATCH_WRITE_ACCESS;
561 return VMEM_WRITE_ACCESS;
564 return VMEM_READ_ACCESS;
565 return VmemReadMapping[getVmemType(Inst)];
568 bool hasXcnt()
const {
return ST->hasWaitXCnt(); }
570 bool mayAccessVMEMThroughFlat(
const MachineInstr &
MI)
const;
571 bool mayAccessLDSThroughFlat(
const MachineInstr &
MI)
const;
572 bool isVmemAccess(
const MachineInstr &
MI)
const;
573 bool generateWaitcntInstBefore(MachineInstr &
MI,
574 WaitcntBrackets &ScoreBrackets,
575 MachineInstr *OldWaitcntInstr,
577 bool generateWaitcnt(AMDGPU::Waitcnt
Wait,
579 MachineBasicBlock &
Block, WaitcntBrackets &ScoreBrackets,
580 MachineInstr *OldWaitcntInstr);
581 void updateEventWaitcntAfter(MachineInstr &Inst,
582 WaitcntBrackets *ScoreBrackets);
584 MachineBasicBlock *
Block)
const;
585 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &
Block,
586 WaitcntBrackets &ScoreBrackets);
587 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &
Block,
588 WaitcntBrackets &ScoreBrackets);
599class WaitcntBrackets {
601 WaitcntBrackets(
const SIInsertWaitcnts *Context) : Context(Context) {}
603 bool isSmemCounter(InstCounterType
T)
const {
604 return T == Context->SmemAccessCounter ||
T == X_CNT;
607 unsigned getSgprScoresIdx(InstCounterType
T)
const {
608 assert(isSmemCounter(
T) &&
"Invalid SMEM counter");
609 return T == X_CNT ? 1 : 0;
612 unsigned getScoreLB(InstCounterType
T)
const {
617 unsigned getScoreUB(InstCounterType
T)
const {
622 unsigned getScoreRange(InstCounterType
T)
const {
623 return getScoreUB(
T) - getScoreLB(
T);
626 unsigned getRegScore(
int GprNo, InstCounterType
T)
const {
627 if (GprNo < NUM_ALL_VGPRS)
628 return VgprScores[
T][GprNo];
629 return SgprScores[getSgprScoresIdx(
T)][GprNo - NUM_ALL_VGPRS];
634 RegInterval getRegInterval(
const MachineInstr *
MI,
635 const MachineRegisterInfo *
MRI,
636 const SIRegisterInfo *
TRI,
637 const MachineOperand &
Op)
const;
639 bool counterOutOfOrder(InstCounterType
T)
const;
640 void simplifyWaitcnt(AMDGPU::Waitcnt &
Wait)
const;
641 void simplifyWaitcnt(InstCounterType
T,
unsigned &
Count)
const;
643 void determineWait(InstCounterType
T, RegInterval
Interval,
644 AMDGPU::Waitcnt &
Wait)
const;
645 void determineWait(InstCounterType
T,
int RegNo,
646 AMDGPU::Waitcnt &
Wait)
const {
647 determineWait(
T, {RegNo, RegNo + 1},
Wait);
650 void applyWaitcnt(
const AMDGPU::Waitcnt &
Wait);
651 void applyWaitcnt(InstCounterType
T,
unsigned Count);
652 void applyXcnt(
const AMDGPU::Waitcnt &
Wait);
653 void updateByEvent(
const SIInstrInfo *
TII,
const SIRegisterInfo *
TRI,
654 const MachineRegisterInfo *
MRI, WaitEventType
E,
657 unsigned hasPendingEvent()
const {
return PendingEvents; }
658 unsigned hasPendingEvent(WaitEventType
E)
const {
659 return PendingEvents & (1 <<
E);
661 unsigned hasPendingEvent(InstCounterType
T)
const {
662 unsigned HasPending = PendingEvents & Context->WaitEventMaskForInst[
T];
663 assert((HasPending != 0) == (getScoreRange(
T) != 0));
667 bool hasMixedPendingEvents(InstCounterType
T)
const {
668 unsigned Events = hasPendingEvent(
T);
670 return Events & (Events - 1);
673 bool hasPendingFlat()
const {
674 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
675 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
676 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
677 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
680 void setPendingFlat() {
681 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
682 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
685 bool hasPendingGDS()
const {
686 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
689 unsigned getPendingGDSWait()
const {
690 return std::min(getScoreUB(DS_CNT) - LastGDS,
691 Context->getWaitCountMax(DS_CNT) - 1);
694 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
698 bool hasOtherPendingVmemTypes(RegInterval
Interval, VmemType V)
const {
700 assert(RegNo < NUM_ALL_VGPRS);
701 if (VgprVmemTypes[RegNo] & ~(1 << V))
707 void clearVgprVmemTypes(RegInterval
Interval) {
709 assert(RegNo < NUM_ALL_VGPRS);
710 VgprVmemTypes[RegNo] = 0;
714 void setStateOnFunctionEntryOrReturn() {
715 setScoreUB(STORE_CNT,
716 getScoreUB(STORE_CNT) + Context->getWaitCountMax(STORE_CNT));
717 PendingEvents |= Context->WaitEventMaskForInst[STORE_CNT];
720 ArrayRef<const MachineInstr *> getLDSDMAStores()
const {
724 bool hasPointSampleAccel(
const MachineInstr &
MI)
const;
725 bool hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
728 void print(raw_ostream &)
const;
738 static bool mergeScore(
const MergeInfo &M,
unsigned &Score,
739 unsigned OtherScore);
741 void setScoreLB(InstCounterType
T,
unsigned Val) {
746 void setScoreUB(InstCounterType
T,
unsigned Val) {
753 if (getScoreRange(EXP_CNT) > Context->getWaitCountMax(EXP_CNT))
754 ScoreLBs[
EXP_CNT] = ScoreUBs[
EXP_CNT] - Context->getWaitCountMax(EXP_CNT);
757 void setRegScore(
int GprNo, InstCounterType
T,
unsigned Val) {
758 setScoreByInterval({GprNo, GprNo + 1},
T, Val);
761 void setScoreByInterval(RegInterval
Interval, InstCounterType CntTy,
764 void setScoreByOperand(
const MachineInstr *
MI,
const SIRegisterInfo *
TRI,
765 const MachineRegisterInfo *
MRI,
766 const MachineOperand &
Op, InstCounterType CntTy,
769 const SIInsertWaitcnts *Context;
771 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
772 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
773 unsigned PendingEvents = 0;
775 unsigned LastFlat[NUM_INST_CNTS] = {0};
777 unsigned LastGDS = 0;
782 unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}};
787 unsigned SgprScores[2][SQ_MAX_PGM_SGPRS] = {{0}};
790 unsigned char VgprVmemTypes[NUM_ALL_VGPRS] = {0};
793 SmallVector<
const MachineInstr *, NUM_LDS_VGPRS - 1> LDSDMAStores;
799 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
801 bool runOnMachineFunction(MachineFunction &MF)
override;
803 StringRef getPassName()
const override {
804 return "SI insert wait instructions";
807 void getAnalysisUsage(AnalysisUsage &AU)
const override {
810 AU.
addRequired<MachinePostDominatorTreeWrapperPass>();
819RegInterval WaitcntBrackets::getRegInterval(
const MachineInstr *
MI,
823 if (!
TRI->isInAllocatableClass(
Op.getReg()))
833 unsigned RegIdx =
TRI->getHWRegIndex(MCReg);
835 const TargetRegisterClass *RC =
TRI->getPhysRegBaseClass(
Op.getReg());
836 unsigned Size =
TRI->getRegSizeInBits(*RC);
839 if (
TRI->isVectorRegister(*
MRI,
Op.getReg())) {
844 Result.first += AGPR_OFFSET;
848 }
else if (
TRI->isSGPRReg(*
MRI,
Op.getReg()) && RegIdx < SQ_MAX_PGM_SGPRS) {
851 Result.first = RegIdx + NUM_ALL_VGPRS;
860void WaitcntBrackets::setScoreByInterval(RegInterval
Interval,
861 InstCounterType CntTy,
864 if (RegNo < NUM_ALL_VGPRS) {
865 VgprUB = std::max(VgprUB, RegNo);
866 VgprScores[CntTy][RegNo] = Score;
868 SgprUB = std::max(SgprUB, RegNo - NUM_ALL_VGPRS);
869 SgprScores[getSgprScoresIdx(CntTy)][RegNo - NUM_ALL_VGPRS] = Score;
874void WaitcntBrackets::setScoreByOperand(
const MachineInstr *
MI,
875 const SIRegisterInfo *
TRI,
876 const MachineRegisterInfo *
MRI,
877 const MachineOperand &
Op,
878 InstCounterType CntTy,
unsigned Score) {
880 setScoreByInterval(
Interval, CntTy, Score);
888bool WaitcntBrackets::hasPointSampleAccel(
const MachineInstr &
MI)
const {
893 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
903bool WaitcntBrackets::hasPointSamplePendingVmemTypes(
904 const MachineInstr &
MI, RegInterval
Interval)
const {
905 if (!hasPointSampleAccel(
MI))
908 return hasOtherPendingVmemTypes(
Interval, VMEM_NOSAMPLER);
911void WaitcntBrackets::updateByEvent(
const SIInstrInfo *
TII,
912 const SIRegisterInfo *
TRI,
913 const MachineRegisterInfo *
MRI,
914 WaitEventType
E, MachineInstr &Inst) {
915 InstCounterType
T = eventCounter(
Context->WaitEventMaskForInst,
E);
917 unsigned UB = getScoreUB(
T);
918 unsigned CurrScore = UB + 1;
924 PendingEvents |= 1 <<
E;
925 setScoreUB(
T, CurrScore);
933 if (
const auto *AddrOp =
TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
934 setScoreByOperand(&Inst,
TRI,
MRI, *AddrOp, EXP_CNT, CurrScore);
937 if (
const auto *Data0 =
938 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
939 setScoreByOperand(&Inst,
TRI,
MRI, *Data0, EXP_CNT, CurrScore);
940 if (
const auto *Data1 =
941 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
942 setScoreByOperand(&Inst,
TRI,
MRI, *Data1, EXP_CNT, CurrScore);
945 Inst.
getOpcode() != AMDGPU::DS_CONSUME &&
946 Inst.
getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
947 for (
const MachineOperand &
Op : Inst.
all_uses()) {
948 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
949 setScoreByOperand(&Inst,
TRI,
MRI,
Op, EXP_CNT, CurrScore);
952 }
else if (
TII->isFLAT(Inst)) {
954 setScoreByOperand(&Inst,
TRI,
MRI,
955 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
958 setScoreByOperand(&Inst,
TRI,
MRI,
959 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
962 }
else if (
TII->isMIMG(Inst)) {
967 setScoreByOperand(&Inst,
TRI,
MRI,
968 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
971 }
else if (
TII->isMTBUF(Inst)) {
975 }
else if (
TII->isMUBUF(Inst)) {
980 setScoreByOperand(&Inst,
TRI,
MRI,
981 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
984 }
else if (
TII->isLDSDIR(Inst)) {
986 setScoreByOperand(&Inst,
TRI,
MRI,
987 *
TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
990 if (
TII->isEXP(Inst)) {
995 for (MachineOperand &DefMO : Inst.
all_defs()) {
996 if (
TRI->isVGPR(*
MRI, DefMO.getReg())) {
997 setScoreByOperand(&Inst,
TRI,
MRI, DefMO, EXP_CNT, CurrScore);
1001 for (
const MachineOperand &
Op : Inst.
all_uses()) {
1002 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1003 setScoreByOperand(&Inst,
TRI,
MRI,
Op, EXP_CNT, CurrScore);
1006 }
else if (
T == X_CNT) {
1007 for (
const MachineOperand &
Op : Inst.
all_uses())
1008 setScoreByOperand(&Inst,
TRI,
MRI,
Op,
T, CurrScore);
1019 for (
const MachineOperand &
Op : Inst.
defs()) {
1021 if (
T == LOAD_CNT ||
T == SAMPLE_CNT ||
T == BVH_CNT) {
1022 if (
Interval.first >= NUM_ALL_VGPRS)
1024 if (updateVMCntOnly(Inst)) {
1029 VmemType
V = getVmemType(Inst);
1030 unsigned char TypesMask = 1 <<
V;
1033 if (hasPointSampleAccel(Inst))
1034 TypesMask |= 1 << VMEM_NOSAMPLER;
1036 VgprVmemTypes[RegNo] |= TypesMask;
1039 setScoreByInterval(
Interval,
T, CurrScore);
1042 (
TII->isDS(Inst) ||
TII->mayWriteLDSThroughDMA(Inst))) {
1047 if (!MemOp->isStore() ||
1052 auto AAI = MemOp->getAAInfo();
1060 if (!AAI || !AAI.Scope)
1062 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E && !Slot; ++
I) {
1063 for (
const auto *MemOp : LDSDMAStores[
I]->memoperands()) {
1064 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1070 if (Slot || LDSDMAStores.size() == NUM_LDS_VGPRS - 1)
1072 LDSDMAStores.push_back(&Inst);
1073 Slot = LDSDMAStores.size();
1076 setRegScore(FIRST_LDS_VGPR + Slot,
T, CurrScore);
1078 setRegScore(FIRST_LDS_VGPR,
T, CurrScore);
1083void WaitcntBrackets::print(raw_ostream &OS)
const {
1087 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
1088 unsigned SR = getScoreRange(
T);
1092 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"LOAD" :
"VM") <<
"_CNT("
1096 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"DS" :
"LGKM") <<
"_CNT("
1100 OS <<
" EXP_CNT(" << SR <<
"): ";
1103 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"STORE" :
"VS") <<
"_CNT("
1107 OS <<
" SAMPLE_CNT(" << SR <<
"): ";
1110 OS <<
" BVH_CNT(" << SR <<
"): ";
1113 OS <<
" KM_CNT(" << SR <<
"): ";
1116 OS <<
" X_CNT(" << SR <<
"): ";
1119 OS <<
" UNKNOWN(" << SR <<
"): ";
1125 unsigned LB = getScoreLB(
T);
1127 for (
int J = 0; J <= VgprUB; J++) {
1128 unsigned RegScore = getRegScore(J,
T);
1131 unsigned RelScore = RegScore - LB - 1;
1132 if (J < FIRST_LDS_VGPR) {
1133 OS << RelScore <<
":v" << J <<
" ";
1135 OS << RelScore <<
":ds ";
1139 if (isSmemCounter(
T)) {
1140 for (
int J = 0; J <= SgprUB; J++) {
1141 unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS,
T);
1144 unsigned RelScore = RegScore - LB - 1;
1145 OS << RelScore <<
":s" << J <<
" ";
1152 OS <<
"Pending Events: ";
1153 if (hasPendingEvent()) {
1155 for (
unsigned I = 0;
I != NUM_WAIT_EVENTS; ++
I) {
1156 if (hasPendingEvent((WaitEventType)
I)) {
1157 OS <<
LS << WaitEventTypeName[
I];
1170void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &
Wait)
const {
1171 simplifyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1172 simplifyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1173 simplifyWaitcnt(DS_CNT,
Wait.DsCnt);
1174 simplifyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1175 simplifyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1176 simplifyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1177 simplifyWaitcnt(KM_CNT,
Wait.KmCnt);
1178 simplifyWaitcnt(X_CNT,
Wait.XCnt);
1181void WaitcntBrackets::simplifyWaitcnt(InstCounterType
T,
1182 unsigned &
Count)
const {
1186 if (
Count >= getScoreRange(
T))
1190void WaitcntBrackets::determineWait(InstCounterType
T, RegInterval
Interval,
1191 AMDGPU::Waitcnt &
Wait)
const {
1192 const unsigned LB = getScoreLB(
T);
1193 const unsigned UB = getScoreUB(
T);
1195 unsigned ScoreToWait = getRegScore(RegNo,
T);
1199 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1200 if ((
T == LOAD_CNT ||
T == DS_CNT) && hasPendingFlat() &&
1201 !
Context->ST->hasFlatLgkmVMemCountInOrder()) {
1205 addWait(
Wait,
T, 0);
1206 }
else if (counterOutOfOrder(
T)) {
1210 addWait(
Wait,
T, 0);
1214 unsigned NeededWait =
1215 std::min(UB - ScoreToWait,
Context->getWaitCountMax(
T) - 1);
1216 addWait(
Wait,
T, NeededWait);
1222void WaitcntBrackets::applyWaitcnt(
const AMDGPU::Waitcnt &
Wait) {
1223 applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1224 applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1225 applyWaitcnt(DS_CNT,
Wait.DsCnt);
1226 applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1227 applyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1228 applyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1229 applyWaitcnt(KM_CNT,
Wait.KmCnt);
1233void WaitcntBrackets::applyWaitcnt(InstCounterType
T,
unsigned Count) {
1234 const unsigned UB = getScoreUB(
T);
1238 if (counterOutOfOrder(
T))
1240 setScoreLB(
T, std::max(getScoreLB(
T), UB -
Count));
1243 PendingEvents &= ~Context->WaitEventMaskForInst[
T];
1247void WaitcntBrackets::applyXcnt(
const AMDGPU::Waitcnt &
Wait) {
1251 if (
Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP))
1252 return applyWaitcnt(X_CNT, 0);
1257 if (
Wait.LoadCnt != ~0u && hasPendingEvent(VMEM_GROUP) &&
1258 !hasPendingEvent(STORE_CNT))
1259 return applyWaitcnt(X_CNT, std::min(
Wait.XCnt,
Wait.LoadCnt));
1261 applyWaitcnt(X_CNT,
Wait.XCnt);
1266bool WaitcntBrackets::counterOutOfOrder(InstCounterType
T)
const {
1268 if ((
T ==
Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1269 (
T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1271 return hasMixedPendingEvents(
T);
1281char SIInsertWaitcntsLegacy::
ID = 0;
1286 return new SIInsertWaitcntsLegacy();
1291 int OpIdx = AMDGPU::getNamedOperandIdx(
MI.getOpcode(),
OpName);
1296 if (NewEnc == MO.
getImm())
1307 case AMDGPU::S_WAIT_LOADCNT:
1309 case AMDGPU::S_WAIT_EXPCNT:
1311 case AMDGPU::S_WAIT_STORECNT:
1313 case AMDGPU::S_WAIT_SAMPLECNT:
1315 case AMDGPU::S_WAIT_BVHCNT:
1317 case AMDGPU::S_WAIT_DSCNT:
1319 case AMDGPU::S_WAIT_KMCNT:
1321 case AMDGPU::S_WAIT_XCNT:
1328bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt)
const {
1342bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1343 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1346 assert(isNormalMode(MaxCounter));
1349 MachineInstr *WaitcntInstr =
nullptr;
1350 MachineInstr *WaitcntVsCntInstr =
nullptr;
1353 dbgs() <<
"PreGFX12::applyPreexistingWaitcnt at: ";
1355 dbgs() <<
"end of block\n";
1363 if (
II.isMetaInstruction()) {
1369 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1373 if (Opcode == AMDGPU::S_WAITCNT) {
1374 unsigned IEnc =
II.getOperand(0).getImm();
1377 ScoreBrackets.simplifyWaitcnt(OldWait);
1381 if (WaitcntInstr || (!
Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1382 II.eraseFromParent();
1386 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1389 <<
"Before: " <<
Wait.LoadCnt <<
'\n';);
1390 ScoreBrackets.determineWait(LOAD_CNT, FIRST_LDS_VGPR,
Wait);
1399 II.eraseFromParent();
1401 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1402 assert(
II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1405 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1407 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1408 Wait.StoreCnt = std::min(
Wait.StoreCnt, OldVSCnt);
1410 if (WaitcntVsCntInstr || (!
Wait.hasWaitStoreCnt() && TrySimplify)) {
1411 II.eraseFromParent();
1414 WaitcntVsCntInstr = &
II;
1421 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1423 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1424 ScoreBrackets.applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1425 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1432 <<
"applied pre-existing waitcnt\n"
1433 <<
"New Instr at block end: " << *WaitcntInstr <<
'\n'
1434 :
dbgs() <<
"applied pre-existing waitcnt\n"
1435 <<
"Old Instr: " << *It
1436 <<
"New Instr: " << *WaitcntInstr <<
'\n');
1439 if (WaitcntVsCntInstr) {
1441 AMDGPU::OpName::simm16,
Wait.StoreCnt);
1442 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1444 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1445 Wait.StoreCnt = ~0
u;
1448 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1449 <<
"New Instr at block end: " << *WaitcntVsCntInstr
1451 :
dbgs() <<
"applied pre-existing waitcnt\n"
1452 <<
"Old Instr: " << *It
1453 <<
"New Instr: " << *WaitcntVsCntInstr <<
'\n');
1461bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1463 AMDGPU::Waitcnt
Wait) {
1465 assert(isNormalMode(MaxCounter));
1472 if (
Wait.hasWaitExceptStoreCnt()) {
1474 [[maybe_unused]]
auto SWaitInst =
1479 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1480 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1483 if (
Wait.hasWaitStoreCnt()) {
1486 [[maybe_unused]]
auto SWaitInst =
1493 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1494 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1501WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1502 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt &&
ST->hasVscnt() ? 0 : ~0u);
1506WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1507 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1515bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1516 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1519 assert(!isNormalMode(MaxCounter));
1522 MachineInstr *CombinedLoadDsCntInstr =
nullptr;
1523 MachineInstr *CombinedStoreDsCntInstr =
nullptr;
1524 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1527 dbgs() <<
"GFX12Plus::applyPreexistingWaitcnt at: ";
1529 dbgs() <<
"end of block\n";
1537 if (
II.isMetaInstruction()) {
1542 MachineInstr **UpdatableInstr;
1548 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1552 if (Opcode == AMDGPU::S_WAITCNT)
1555 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1557 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1560 ScoreBrackets.simplifyWaitcnt(OldWait);
1562 UpdatableInstr = &CombinedLoadDsCntInstr;
1563 }
else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1565 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1568 ScoreBrackets.simplifyWaitcnt(OldWait);
1570 UpdatableInstr = &CombinedStoreDsCntInstr;
1571 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1574 II.eraseFromParent();
1580 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1582 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1583 addWait(
Wait, CT.value(), OldCnt);
1584 UpdatableInstr = &WaitInstrs[CT.value()];
1588 if (!*UpdatableInstr) {
1589 *UpdatableInstr = &
II;
1591 II.eraseFromParent();
1596 if (CombinedLoadDsCntInstr) {
1604 if (
Wait.LoadCnt != ~0u &&
Wait.DsCnt != ~0u) {
1607 AMDGPU::OpName::simm16, NewEnc);
1608 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1609 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1610 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1615 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1616 <<
"New Instr at block end: "
1617 << *CombinedLoadDsCntInstr <<
'\n'
1618 :
dbgs() <<
"applied pre-existing waitcnt\n"
1619 <<
"Old Instr: " << *It <<
"New Instr: "
1620 << *CombinedLoadDsCntInstr <<
'\n');
1627 if (CombinedStoreDsCntInstr) {
1629 if (
Wait.StoreCnt != ~0u &&
Wait.DsCnt != ~0u) {
1632 AMDGPU::OpName::simm16, NewEnc);
1633 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1634 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1635 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1636 Wait.StoreCnt = ~0
u;
1640 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1641 <<
"New Instr at block end: "
1642 << *CombinedStoreDsCntInstr <<
'\n'
1643 :
dbgs() <<
"applied pre-existing waitcnt\n"
1644 <<
"Old Instr: " << *It <<
"New Instr: "
1645 << *CombinedStoreDsCntInstr <<
'\n');
1658 if (
Wait.DsCnt != ~0u) {
1667 if (
Wait.LoadCnt != ~0u) {
1668 WaitsToErase.
push_back(&WaitInstrs[LOAD_CNT]);
1669 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1670 }
else if (
Wait.StoreCnt != ~0u) {
1671 WaitsToErase.
push_back(&WaitInstrs[STORE_CNT]);
1672 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1675 for (MachineInstr **WI : WaitsToErase) {
1679 (*WI)->eraseFromParent();
1685 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1686 if (!WaitInstrs[CT])
1689 unsigned NewCnt = getWait(
Wait, CT);
1690 if (NewCnt != ~0u) {
1692 AMDGPU::OpName::simm16, NewCnt);
1693 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1695 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1696 setNoWait(
Wait, CT);
1699 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1700 <<
"New Instr at block end: " << *WaitInstrs[CT]
1702 :
dbgs() <<
"applied pre-existing waitcnt\n"
1703 <<
"Old Instr: " << *It
1704 <<
"New Instr: " << *WaitInstrs[CT] <<
'\n');
1715bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1717 AMDGPU::Waitcnt
Wait) {
1719 assert(!isNormalMode(MaxCounter));
1725 if (
Wait.DsCnt != ~0u) {
1726 MachineInstr *SWaitInst =
nullptr;
1728 if (
Wait.LoadCnt != ~0u) {
1736 }
else if (
Wait.StoreCnt != ~0u) {
1743 Wait.StoreCnt = ~0
u;
1751 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1752 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1759 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1764 [[maybe_unused]]
auto SWaitInst =
1771 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1772 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1779 unsigned Opc =
MI.getOpcode();
1780 return (
Opc == AMDGPU::S_CBRANCH_VCCNZ ||
Opc == AMDGPU::S_CBRANCH_VCCZ) &&
1781 !
MI.getOperand(1).isUndef();
1809bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &
MI,
1810 WaitcntBrackets &ScoreBrackets,
1811 MachineInstr *OldWaitcntInstr,
1813 setForceEmitWaitcnt();
1817 AMDGPU::Waitcnt
Wait;
1823 if (
MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
1824 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
1825 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL ||
1826 MI.getOpcode() == AMDGPU::BUFFER_GL0_INV ||
1827 MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) {
1834 if (
MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
1835 MI.getOpcode() == AMDGPU::SI_RETURN ||
1836 MI.getOpcode() == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1837 MI.getOpcode() == AMDGPU::S_SETPC_B64_return ||
1839 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
false));
1849 else if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
1850 MI.getOpcode() == AMDGPU::S_ENDPGM_SAVED) {
1851 if (!WCG->isOptNone() &&
1852 (
MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1853 (
ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1854 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1855 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1859 else if ((
MI.getOpcode() == AMDGPU::S_SENDMSG ||
1860 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
1861 ST->hasLegacyGeometry() &&
1872 if (
MI.modifiesRegister(AMDGPU::EXEC,
TRI)) {
1875 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1876 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1877 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1878 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1885 if (
TII->isAlwaysGDS(
MI.getOpcode()) && ScoreBrackets.hasPendingGDS())
1886 addWait(
Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
1892 Wait = AMDGPU::Waitcnt();
1894 const auto &CallAddrOp = *
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
1895 if (CallAddrOp.isReg()) {
1896 RegInterval CallAddrOpInterval =
1897 ScoreBrackets.getRegInterval(&
MI,
MRI,
TRI, CallAddrOp);
1899 ScoreBrackets.determineWait(SmemAccessCounter, CallAddrOpInterval,
1902 if (
const auto *RtnAddrOp =
1903 TII->getNamedOperand(
MI, AMDGPU::OpName::dst)) {
1904 RegInterval RtnAddrOpInterval =
1905 ScoreBrackets.getRegInterval(&
MI,
MRI,
TRI, *RtnAddrOp);
1907 ScoreBrackets.determineWait(SmemAccessCounter, RtnAddrOpInterval,
1926 for (
const MachineMemOperand *Memop :
MI.memoperands()) {
1927 const Value *
Ptr = Memop->getValue();
1928 if (Memop->isStore()) {
1929 if (
auto It = SLoadAddresses.
find(
Ptr); It != SLoadAddresses.
end()) {
1930 addWait(
Wait, SmemAccessCounter, 0);
1932 SLoadAddresses.
erase(It);
1935 unsigned AS = Memop->getAddrSpace();
1939 if (
TII->mayWriteLDSThroughDMA(
MI))
1943 unsigned RegNo = FIRST_LDS_VGPR;
1950 if (
Ptr && Memop->getAAInfo() && Memop->getAAInfo().Scope) {
1951 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
1952 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E; ++
I) {
1953 if (
MI.mayAlias(AA, *LDSDMAStores[
I],
true))
1954 ScoreBrackets.determineWait(LOAD_CNT, RegNo +
I + 1,
Wait);
1957 ScoreBrackets.determineWait(LOAD_CNT, RegNo,
Wait);
1959 if (Memop->isStore()) {
1960 ScoreBrackets.determineWait(EXP_CNT, RegNo,
Wait);
1965 for (
const MachineOperand &
Op :
MI.operands()) {
1970 if (
Op.isTied() &&
Op.isUse() &&
TII->doesNotReadTiedSource(
MI))
1975 const bool IsVGPR =
TRI->isVectorRegister(*
MRI,
Op.getReg());
1982 if (
Op.isImplicit() &&
MI.mayLoadOrStore())
1991 if (
Op.isUse() || !updateVMCntOnly(
MI) ||
1992 ScoreBrackets.hasOtherPendingVmemTypes(
Interval,
1994 ScoreBrackets.hasPointSamplePendingVmemTypes(
MI,
Interval) ||
1995 !
ST->hasVmemWriteVgprInOrder()) {
1997 ScoreBrackets.determineWait(SAMPLE_CNT,
Interval,
Wait);
1999 ScoreBrackets.clearVgprVmemTypes(
Interval);
2002 if (
Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2007 ScoreBrackets.determineWait(SmemAccessCounter,
Interval,
Wait);
2010 if (hasXcnt() &&
Op.isDef())
2028 if (
MI.getOpcode() == AMDGPU::S_BARRIER &&
2029 !
ST->hasAutoWaitcntBeforeBarrier() && !
ST->supportsBackOffBarrier()) {
2030 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
true));
2037 if (ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2043 ScoreBrackets.simplifyWaitcnt(
Wait);
2048 Wait = WCG->getAllZeroWaitcnt(
false);
2050 if (ForceEmitWaitcnt[LOAD_CNT])
2052 if (ForceEmitWaitcnt[EXP_CNT])
2054 if (ForceEmitWaitcnt[DS_CNT])
2056 if (ForceEmitWaitcnt[SAMPLE_CNT])
2058 if (ForceEmitWaitcnt[BVH_CNT])
2060 if (ForceEmitWaitcnt[KM_CNT])
2062 if (ForceEmitWaitcnt[X_CNT])
2066 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2068 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2070 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2077 return generateWaitcnt(
Wait,
MI.getIterator(), *
MI.getParent(), ScoreBrackets,
2081bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt
Wait,
2083 MachineBasicBlock &
Block,
2084 WaitcntBrackets &ScoreBrackets,
2085 MachineInstr *OldWaitcntInstr) {
2088 if (OldWaitcntInstr)
2092 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr,
Wait, It);
2096 ScoreBrackets.applyWaitcnt(
Wait);
2099 if (
Wait.ExpCnt != ~0u && It !=
Block.instr_end() &&
2101 MachineOperand *WaitExp =
2102 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2110 <<
"Update Instr: " << *It);
2114 if (
Wait.KmCnt == 0 &&
Wait.XCnt != ~0u &&
2115 !ScoreBrackets.hasPendingEvent(SMEM_GROUP))
2118 if (
Wait.LoadCnt == 0 &&
Wait.XCnt != ~0u &&
2119 !ScoreBrackets.hasPendingEvent(VMEM_GROUP))
2125 if (
Wait.XCnt != ~0u && isVmemAccess(*It))
2128 if (WCG->createNewWaitcnt(
Block, It,
Wait))
2137bool SIInsertWaitcnts::mayAccessVMEMThroughFlat(
const MachineInstr &
MI)
const {
2141 if (!
TII->usesVM_CNT(
MI))
2146 if (
MI.memoperands_empty())
2154 for (
const MachineMemOperand *Memop :
MI.memoperands()) {
2155 unsigned AS = Memop->getAddrSpace();
2166bool SIInsertWaitcnts::mayAccessLDSThroughFlat(
const MachineInstr &
MI)
const {
2170 if (!
TII->usesLGKM_CNT(
MI))
2174 if (
ST->isTgSplitEnabled())
2179 if (
MI.memoperands_empty())
2183 for (
const MachineMemOperand *Memop :
MI.memoperands()) {
2184 unsigned AS = Memop->getAddrSpace();
2192bool SIInsertWaitcnts::isVmemAccess(
const MachineInstr &
MI)
const {
2193 return (
TII->isFLAT(
MI) && mayAccessVMEMThroughFlat(
MI)) ||
2199 return Opc == AMDGPU::GLOBAL_INV ||
Opc == AMDGPU::GLOBAL_WB ||
2200 Opc == AMDGPU::GLOBAL_WBINV;
2206 MachineBasicBlock *
Block)
const {
2207 auto BlockEnd =
Block->getParent()->end();
2208 auto BlockIter =
Block->getIterator();
2212 if (++BlockIter != BlockEnd) {
2213 It = BlockIter->instr_begin();
2220 if (!It->isMetaInstruction())
2228 return It->getOpcode() == AMDGPU::S_ENDPGM;
2232bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2233 MachineBasicBlock &
Block,
2234 WaitcntBrackets &ScoreBrackets) {
2235 AMDGPU::Waitcnt
Wait;
2236 bool NeedsEndPGMCheck =
false;
2244 NeedsEndPGMCheck =
true;
2247 ScoreBrackets.simplifyWaitcnt(
Wait);
2250 bool Result = generateWaitcnt(
Wait, SuccessorIt,
Block, ScoreBrackets,
2253 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &
Block)) {
2261void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2262 WaitcntBrackets *ScoreBrackets) {
2268 bool IsVMEMAccess =
false;
2269 bool IsSMEMAccess =
false;
2270 if (
TII->isDS(Inst) &&
TII->usesLGKM_CNT(Inst)) {
2272 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2273 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, GDS_ACCESS, Inst);
2274 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, GDS_GPR_LOCK, Inst);
2275 ScoreBrackets->setPendingGDS();
2277 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, LDS_ACCESS, Inst);
2279 }
else if (
TII->isFLAT(Inst)) {
2281 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, getVmemWaitEventType(Inst),
2288 int FlatASCount = 0;
2290 if (mayAccessVMEMThroughFlat(Inst)) {
2292 IsVMEMAccess =
true;
2293 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, getVmemWaitEventType(Inst),
2297 if (mayAccessLDSThroughFlat(Inst)) {
2299 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, LDS_ACCESS, Inst);
2305 if (FlatASCount > 1)
2306 ScoreBrackets->setPendingFlat();
2309 IsVMEMAccess =
true;
2310 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, getVmemWaitEventType(Inst),
2313 if (
ST->vmemWriteNeedsExpWaitcnt() &&
2315 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, VMW_GPR_LOCK, Inst);
2317 }
else if (
TII->isSMRD(Inst)) {
2318 IsSMEMAccess =
true;
2319 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, SMEM_ACCESS, Inst);
2320 }
else if (Inst.
isCall()) {
2323 ScoreBrackets->applyWaitcnt(
2324 WCG->getAllZeroWaitcnt(
false));
2325 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2328 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2331 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, EXP_LDS_ACCESS, Inst);
2332 }
else if (
TII->isVINTERP(Inst)) {
2333 int64_t
Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2334 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2336 unsigned Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2338 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, EXP_PARAM_ACCESS, Inst);
2340 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, EXP_POS_ACCESS, Inst);
2342 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, EXP_GPR_LOCK, Inst);
2345 case AMDGPU::S_SENDMSG:
2346 case AMDGPU::S_SENDMSG_RTN_B32:
2347 case AMDGPU::S_SENDMSG_RTN_B64:
2348 case AMDGPU::S_SENDMSGHALT:
2349 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, SQ_MESSAGE, Inst);
2351 case AMDGPU::S_MEMTIME:
2352 case AMDGPU::S_MEMREALTIME:
2353 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_M0:
2354 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM:
2355 case AMDGPU::S_BARRIER_LEAVE:
2356 case AMDGPU::S_GET_BARRIER_STATE_M0:
2357 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2358 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, SMEM_ACCESS, Inst);
2367 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, VMEM_GROUP, Inst);
2370 ScoreBrackets->updateByEvent(
TII,
TRI,
MRI, SMEM_GROUP, Inst);
2373bool WaitcntBrackets::mergeScore(
const MergeInfo &M,
unsigned &Score,
2374 unsigned OtherScore) {
2375 unsigned MyShifted = Score <=
M.OldLB ? 0 : Score +
M.MyShift;
2376 unsigned OtherShifted =
2377 OtherScore <=
M.OtherLB ? 0 : OtherScore +
M.OtherShift;
2378 Score = std::max(MyShifted, OtherShifted);
2379 return OtherShifted > MyShifted;
2387bool WaitcntBrackets::merge(
const WaitcntBrackets &
Other) {
2388 bool StrictDom =
false;
2390 VgprUB = std::max(VgprUB,
Other.VgprUB);
2391 SgprUB = std::max(SgprUB,
Other.SgprUB);
2393 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
2395 const unsigned *WaitEventMaskForInst =
Context->WaitEventMaskForInst;
2396 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[
T];
2397 const unsigned OtherEvents =
Other.PendingEvents & WaitEventMaskForInst[
T];
2398 if (OtherEvents & ~OldEvents)
2400 PendingEvents |= OtherEvents;
2403 const unsigned MyPending = ScoreUBs[
T] - ScoreLBs[
T];
2404 const unsigned OtherPending =
Other.ScoreUBs[
T] -
Other.ScoreLBs[
T];
2405 const unsigned NewUB = ScoreLBs[
T] + std::max(MyPending, OtherPending);
2406 if (NewUB < ScoreLBs[
T])
2410 M.OldLB = ScoreLBs[
T];
2411 M.OtherLB =
Other.ScoreLBs[
T];
2412 M.MyShift = NewUB - ScoreUBs[
T];
2413 M.OtherShift = NewUB -
Other.ScoreUBs[
T];
2415 ScoreUBs[
T] = NewUB;
2417 StrictDom |= mergeScore(M, LastFlat[
T],
Other.LastFlat[
T]);
2420 StrictDom |= mergeScore(M, LastGDS,
Other.LastGDS);
2422 for (
int J = 0; J <= VgprUB; J++)
2423 StrictDom |= mergeScore(M, VgprScores[
T][J],
Other.VgprScores[
T][J]);
2425 if (isSmemCounter(
T)) {
2426 unsigned Idx = getSgprScoresIdx(
T);
2427 for (
int J = 0; J <= SgprUB; J++)
2429 mergeScore(M, SgprScores[Idx][J],
Other.SgprScores[Idx][J]);
2433 for (
int J = 0; J <= VgprUB; J++) {
2434 unsigned char NewVmemTypes = VgprVmemTypes[J] |
Other.VgprVmemTypes[J];
2435 StrictDom |= NewVmemTypes != VgprVmemTypes[J];
2436 VgprVmemTypes[J] = NewVmemTypes;
2444 return Opcode == AMDGPU::S_WAITCNT ||
2447 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2448 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2449 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2454bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2455 MachineBasicBlock &
Block,
2456 WaitcntBrackets &ScoreBrackets) {
2460 dbgs() <<
"*** Begin Block: ";
2462 ScoreBrackets.dump();
2468 bool VCCZCorrect =
true;
2469 if (
ST->hasReadVCCZBug()) {
2472 VCCZCorrect =
false;
2473 }
else if (!
ST->partialVCCWritesUpdateVCCZ()) {
2476 VCCZCorrect =
false;
2480 MachineInstr *OldWaitcntInstr =
nullptr;
2485 MachineInstr &Inst = *Iter;
2494 if (!OldWaitcntInstr)
2495 OldWaitcntInstr = &Inst;
2500 bool FlushVmCnt =
Block.getFirstTerminator() == Inst &&
2501 isPreheaderToFlush(
Block, ScoreBrackets);
2504 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2506 OldWaitcntInstr =
nullptr;
2509 bool RestoreVCCZ = !VCCZCorrect &&
readsVCCZ(Inst);
2512 if (
ST->hasReadVCCZBug() || !
ST->partialVCCWritesUpdateVCCZ()) {
2516 if (!
ST->partialVCCWritesUpdateVCCZ())
2517 VCCZCorrect =
false;
2526 if (
ST->hasReadVCCZBug() &&
2527 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2530 VCCZCorrect =
false;
2538 if (
TII->isSMRD(Inst)) {
2539 for (
const MachineMemOperand *Memop : Inst.
memoperands()) {
2542 if (!Memop->isInvariant()) {
2543 const Value *
Ptr = Memop->getValue();
2547 if (
ST->hasReadVCCZBug()) {
2549 VCCZCorrect =
false;
2553 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2555 Modified |= insertForcedWaitAfter(Inst,
Block, ScoreBrackets);
2559 ScoreBrackets.dump();
2569 TII->get(
ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2581 AMDGPU::Waitcnt
Wait;
2582 if (
Block.getFirstTerminator() ==
Block.end() &&
2583 isPreheaderToFlush(
Block, ScoreBrackets)) {
2584 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2586 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2588 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2597 dbgs() <<
"*** End Block: ";
2599 ScoreBrackets.dump();
2607bool SIInsertWaitcnts::isPreheaderToFlush(
2608 MachineBasicBlock &
MBB,
const WaitcntBrackets &ScoreBrackets) {
2609 auto [Iterator, IsInserted] = PreheadersToFlush.
try_emplace(&
MBB,
false);
2611 return Iterator->second;
2622 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2623 Iterator->second =
true;
2630bool SIInsertWaitcnts::isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const {
2632 return mayAccessVMEMThroughFlat(
MI);
2644bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *
ML,
2645 const WaitcntBrackets &Brackets) {
2646 bool HasVMemLoad =
false;
2647 bool HasVMemStore =
false;
2648 bool UsesVgprLoadedOutside =
false;
2649 DenseSet<Register> VgprUse;
2650 DenseSet<Register> VgprDef;
2652 for (MachineBasicBlock *
MBB :
ML->blocks()) {
2653 for (MachineInstr &
MI : *
MBB) {
2654 if (isVMEMOrFlatVMEM(
MI)) {
2658 HasVMemStore =
true;
2660 for (
const MachineOperand &
Op :
MI.all_uses()) {
2661 if (!
TRI->isVectorRegister(*
MRI,
Op.getReg()))
2673 if (Brackets.getRegScore(RegNo, LOAD_CNT) >
2674 Brackets.getScoreLB(LOAD_CNT) ||
2675 Brackets.getRegScore(RegNo, SAMPLE_CNT) >
2676 Brackets.getScoreLB(SAMPLE_CNT) ||
2677 Brackets.getRegScore(RegNo, BVH_CNT) >
2678 Brackets.getScoreLB(BVH_CNT)) {
2679 UsesVgprLoadedOutside =
true;
2686 if (isVMEMOrFlatVMEM(
MI) &&
MI.mayLoad()) {
2687 for (
const MachineOperand &
Op :
MI.all_defs()) {
2700 if (!
ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2702 return HasVMemLoad && UsesVgprLoadedOutside &&
ST->hasVmemWriteVgprInOrder();
2705bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2706 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2708 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2710 if (
auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2711 AA = &AAR->getAAResults();
2713 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2725 if (!SIInsertWaitcnts(MLI, PDT,
AA).
run(MF))
2730 .preserve<AAManager>();
2735 TII = ST->getInstrInfo();
2736 TRI = &
TII->getRegisterInfo();
2742 if (ST->hasExtendedWaitCounts()) {
2743 MaxCounter = NUM_EXTENDED_INST_CNTS;
2744 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2745 WCG = &WCGGFX12Plus;
2747 MaxCounter = NUM_NORMAL_INST_CNTS;
2748 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF);
2752 for (
auto T : inst_counter_types())
2753 ForceEmitWaitcnt[
T] =
false;
2755 WaitEventMaskForInst = WCG->getWaitEventMask();
2757 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2759 if (
ST->hasExtendedWaitCounts()) {
2773 [[maybe_unused]]
unsigned NumVGPRsMax =
2775 [[maybe_unused]]
unsigned NumSGPRsMax =
ST->getAddressableNumSGPRs();
2776 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
2777 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
2782 MachineBasicBlock &EntryBB = MF.
front();
2793 I !=
E && (
I->isPHI() ||
I->isMetaInstruction()); ++
I)
2796 if (
ST->hasExtendedWaitCounts()) {
2799 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2800 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2803 if (!
ST->hasImageInsts() &&
2804 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2808 TII->get(instrsForExtendedCounterTypes[CT]))
2815 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(
this);
2816 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2817 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2824 for (
auto *
MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2827 std::unique_ptr<WaitcntBrackets> Brackets;
2832 for (
auto BII = BlockInfos.
begin(), BIE = BlockInfos.
end(); BII != BIE;
2834 MachineBasicBlock *
MBB = BII->first;
2835 BlockInfo &BI = BII->second;
2841 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2843 *Brackets = *BI.Incoming;
2846 Brackets = std::make_unique<WaitcntBrackets>(
this);
2851 Brackets->~WaitcntBrackets();
2852 new (Brackets.get()) WaitcntBrackets(
this);
2856 Modified |= insertWaitcntInBlock(MF, *
MBB, *Brackets);
2859 if (Brackets->hasPendingEvent()) {
2860 BlockInfo *MoveBracketsToSucc =
nullptr;
2862 auto *SuccBII = BlockInfos.
find(Succ);
2863 BlockInfo &SuccBI = SuccBII->second;
2864 if (!SuccBI.Incoming) {
2865 SuccBI.Dirty =
true;
2866 if (SuccBII <= BII) {
2870 if (!MoveBracketsToSucc) {
2871 MoveBracketsToSucc = &SuccBI;
2873 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2875 }
else if (SuccBI.Incoming->merge(*Brackets)) {
2876 SuccBI.Dirty =
true;
2877 if (SuccBII <= BII) {
2883 if (MoveBracketsToSucc)
2884 MoveBracketsToSucc->Incoming = std::move(Brackets);
2889 if (
ST->hasScalarStores()) {
2890 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2891 bool HaveScalarStores =
false;
2893 for (MachineBasicBlock &
MBB : MF) {
2894 for (MachineInstr &
MI :
MBB) {
2895 if (!HaveScalarStores &&
TII->isScalarStore(
MI))
2896 HaveScalarStores =
true;
2898 if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
2899 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2904 if (HaveScalarStores) {
2913 for (MachineBasicBlock *
MBB : EndPgmBlocks) {
2914 bool SeenDCacheWB =
false;
2918 if (
I->getOpcode() == AMDGPU::S_DCACHE_WB)
2919 SeenDCacheWB =
true;
2920 else if (
TII->isScalarStore(*
I))
2921 SeenDCacheWB =
false;
2924 if ((
I->getOpcode() == AMDGPU::S_ENDPGM ||
2925 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2941 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2943 TII->get(AMDGPU::S_ALLOC_VGPR))
2948 if (!ReleaseVGPRInsts.empty() &&
2949 (MF.getFrameInfo().hasCalls() ||
2950 ST->getOccupancyWithNumVGPRs(
2951 TRI->getNumUsedPhysRegs(*
MRI, AMDGPU::VGPR_32RegClass),
2954 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2955 if (
ST->requiresNopBeforeDeallocVGPRs()) {
2957 TII->get(AMDGPU::S_NOP))
2961 TII->get(AMDGPU::S_SENDMSG))
2967 ReleaseVGPRInsts.clear();
2968 PreheadersToFlush.
clear();
2969 SLoadAddresses.
clear();
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
static bool isOptNone(const MachineFunction &MF)
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
std::pair< uint64_t, uint64_t > Interval
static bool isReg(const MCInst &MI, unsigned OpNo)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static cl::opt< bool > ForceEmitZeroLoadFlag("amdgpu-waitcnt-load-forcezero", cl::desc("Force all waitcnt load counters to wait until 0"), cl::init(false), cl::Hidden)
static bool callWaitsOnFunctionReturn(const MachineInstr &MI)
#define AMDGPU_EVENT_NAME(Name)
static bool callWaitsOnFunctionEntry(const MachineInstr &MI)
static bool updateOperandIfDifferent(MachineInstr &MI, AMDGPU::OpName OpName, unsigned NewEnc)
static bool isGFX12CacheInvOrWBInst(MachineInstr &Inst)
static bool isWaitInstr(MachineInstr &Inst)
static std::optional< InstCounterType > counterTypeForInstr(unsigned Opcode)
Determine if MI is a gfx12+ single-counter S_WAIT_*CNT instruction, and if so, which counter it is wa...
static bool readsVCCZ(const MachineInstr &MI)
static cl::opt< bool > ForceEmitZeroFlag("amdgpu-waitcnt-forcezero", cl::desc("Force all waitcnt instrs to be emitted as " "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"), cl::init(false), cl::Hidden)
#define AMDGPU_DECLARE_WAIT_EVENTS(DECL)
#define AMDGPU_EVENT_ENUM(Name)
Provides some synthesis utilities to produce sequences of values.
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
static const uint32_t IV[8]
A manager for alias analyses.
bool isEntryFunction() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Represents analyses that only rely on functions' control flow.
static bool isCounterSet(unsigned ID)
static bool shouldExecute(unsigned CounterName)
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool erase(const KeyT &Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
FunctionPass class - This class is used to implement most global optimizations.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI const MachineBasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
Instructions::iterator instr_iterator
instr_iterator instr_end()
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool isCall(QueryType Type=AnyInBundle) const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
const MachineOperand & getOperand(unsigned i) const
bool isMetaInstruction(QueryType Type=IgnoreBundle) const
Return true if this instruction doesn't produce any output in the form of executable instructions.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator find(const KeyT &Key)
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static bool isVMEM(const MachineInstr &MI)
static bool isFLATScratch(const MachineInstr &MI)
static bool isEXP(const MachineInstr &MI)
static bool mayWriteLDSThroughDMA(const MachineInstr &MI)
static bool isLDSDIR(const MachineInstr &MI)
static bool isGWS(const MachineInstr &MI)
static bool isFLATGlobal(const MachineInstr &MI)
static bool isVSAMPLE(const MachineInstr &MI)
static bool isAtomicRet(const MachineInstr &MI)
static bool isImage(const MachineInstr &MI)
static unsigned getNonSoftWaitcntOpcode(unsigned Opcode)
static bool isVINTERP(const MachineInstr &MI)
static bool isMIMG(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
static bool isAtomicNoRet(const MachineInstr &MI)
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
unsigned getDynamicVGPRBlockSize() const
bool isDynamicVGPREnabled() const
void push_back(const T &Elt)
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ FLAT_ADDRESS
Address space for flat memory.
unsigned getMaxWavesPerEU(const MCSubtargetInfo *STI)
@ ID_DEALLOC_VGPRS_GFX11Plus
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
void decodeWaitcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned &Vmcnt, unsigned &Expcnt, unsigned &Lgkmcnt)
Decodes Vmcnt, Expcnt and Lgkmcnt from given Waitcnt for given isa Version, and writes decoded values...
MCRegister getMCReg(MCRegister Reg, const MCSubtargetInfo &STI)
If Reg is a pseudo reg, return the correct hardware register given STI otherwise return Reg.
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
unsigned getStorecntBitMask(const IsaVersion &Version)
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
unsigned encodeWaitcnt(const IsaVersion &Version, unsigned Vmcnt, unsigned Expcnt, unsigned Lgkmcnt)
Encodes Vmcnt, Expcnt and Lgkmcnt into Waitcnt for given isa Version.
unsigned getSamplecntBitMask(const IsaVersion &Version)
unsigned getKmcntBitMask(const IsaVersion &Version)
unsigned getVmcntBitMask(const IsaVersion &Version)
unsigned getXcntBitMask(const IsaVersion &Version)
Waitcnt decodeStorecntDscnt(const IsaVersion &Version, unsigned StorecntDscnt)
unsigned getLgkmcntBitMask(const IsaVersion &Version)
unsigned getBvhcntBitMask(const IsaVersion &Version)
unsigned getExpcntBitMask(const IsaVersion &Version)
Waitcnt decodeLoadcntDscnt(const IsaVersion &Version, unsigned LoadcntDscnt)
static unsigned encodeStorecntDscnt(const IsaVersion &Version, unsigned Storecnt, unsigned Dscnt)
bool getMUBUFIsBufferInv(unsigned Opc)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
unsigned getLoadcntBitMask(const IsaVersion &Version)
static unsigned encodeLoadcntDscnt(const IsaVersion &Version, unsigned Loadcnt, unsigned Dscnt)
unsigned getDscntBitMask(const IsaVersion &Version)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ Undef
Value of the register doesn't matter.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto enum_seq(EnumT Begin, EnumT End)
Iterate over an enum type from Begin up to - but not including - End.
static StringRef getCPU(StringRef CPU)
Processes a CPU name.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
char & SIInsertWaitcntsID
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
FunctionAddr VTableAddr Count
CodeGenOptLevel
Code generation optimization level.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
DWARFExpression::Operation Op
FunctionPass * createSIInsertWaitcntsPass()
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
Instruction set architecture version.
Represents the counter values to wait for in an s_waitcnt instruction.
static constexpr bool is_iterable