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);
115 TRACKINGID_RANGE_LEN = (1 << 16),
120 REGUNITS_END = REGUNITS_BEGIN + TRACKINGID_RANGE_LEN,
125 NUM_LDSDMA = TRACKINGID_RANGE_LEN,
126 LDSDMA_BEGIN = REGUNITS_END,
127 LDSDMA_END = LDSDMA_BEGIN + NUM_LDSDMA,
131static constexpr VMEMID toVMEMID(MCRegUnit RU) {
132 return static_cast<unsigned>(RU);
135struct HardwareLimits {
139 unsigned StorecntMax;
140 unsigned SamplecntMax;
146#define AMDGPU_DECLARE_WAIT_EVENTS(DECL) \
148 DECL(VMEM_SAMPLER_READ_ACCESS) \
149 DECL(VMEM_BVH_READ_ACCESS) \
150 DECL(VMEM_WRITE_ACCESS) \
151 DECL(SCRATCH_WRITE_ACCESS) \
161 DECL(EXP_POS_ACCESS) \
162 DECL(EXP_PARAM_ACCESS) \
167#define AMDGPU_EVENT_ENUM(Name) Name,
172#undef AMDGPU_EVENT_ENUM
174#define AMDGPU_EVENT_NAME(Name) #Name,
178#undef AMDGPU_EVENT_NAME
199static const unsigned instrsForExtendedCounterTypes[NUM_EXTENDED_INST_CNTS] = {
200 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT, AMDGPU::S_WAIT_EXPCNT,
201 AMDGPU::S_WAIT_STORECNT, AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
202 AMDGPU::S_WAIT_KMCNT, AMDGPU::S_WAIT_XCNT};
210static bool isNormalMode(InstCounterType MaxCounter) {
211 return MaxCounter == NUM_NORMAL_INST_CNTS;
216 assert(updateVMCntOnly(Inst));
218 return VMEM_NOSAMPLER;
232 return VMEM_NOSAMPLER;
244 return Wait.StoreCnt;
246 return Wait.SampleCnt;
259 unsigned &WC = getCounterRef(
Wait,
T);
260 WC = std::min(WC,
Count);
264 getCounterRef(
Wait,
T) = ~0
u;
268 return getCounterRef(
Wait,
T);
272InstCounterType eventCounter(
const unsigned *masks, WaitEventType
E) {
273 for (
auto T : inst_counter_types()) {
274 if (masks[
T] & (1 <<
E))
280class WaitcntBrackets;
288class WaitcntGenerator {
290 const GCNSubtarget *ST =
nullptr;
291 const SIInstrInfo *TII =
nullptr;
292 AMDGPU::IsaVersion IV;
293 InstCounterType MaxCounter;
297 WaitcntGenerator() =
default;
298 WaitcntGenerator(
const MachineFunction &MF, InstCounterType MaxCounter)
299 : ST(&MF.getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
306 bool isOptNone()
const {
return OptNone; }
320 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
321 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
325 bool promoteSoftWaitCnt(MachineInstr *Waitcnt)
const;
329 virtual bool createNewWaitcnt(MachineBasicBlock &
Block,
331 AMDGPU::Waitcnt
Wait) = 0;
335 virtual const unsigned *getWaitEventMask()
const = 0;
339 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const = 0;
341 virtual ~WaitcntGenerator() =
default;
344 static constexpr unsigned
345 eventMask(std::initializer_list<WaitEventType> Events) {
347 for (
auto &
E : Events)
354class WaitcntGeneratorPreGFX12 :
public WaitcntGenerator {
356 using WaitcntGenerator::WaitcntGenerator;
359 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
360 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
363 bool createNewWaitcnt(MachineBasicBlock &
Block,
365 AMDGPU::Waitcnt
Wait)
override;
367 const unsigned *getWaitEventMask()
const override {
370 static const unsigned WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
372 {VMEM_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS}),
373 eventMask({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
374 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
375 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
376 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
382 return WaitEventMaskForInstPreGFX12;
385 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
388class WaitcntGeneratorGFX12Plus :
public WaitcntGenerator {
390 using WaitcntGenerator::WaitcntGenerator;
393 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
394 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
397 bool createNewWaitcnt(MachineBasicBlock &
Block,
399 AMDGPU::Waitcnt
Wait)
override;
401 const unsigned *getWaitEventMask()
const override {
404 static const unsigned WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
405 eventMask({VMEM_ACCESS}),
406 eventMask({LDS_ACCESS, GDS_ACCESS}),
407 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
408 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
409 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
410 eventMask({VMEM_SAMPLER_READ_ACCESS}),
411 eventMask({VMEM_BVH_READ_ACCESS}),
412 eventMask({SMEM_ACCESS, SQ_MESSAGE, SCC_WRITE}),
413 eventMask({VMEM_GROUP, SMEM_GROUP})};
415 return WaitEventMaskForInstGFX12Plus;
418 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
421class SIInsertWaitcnts {
423 const GCNSubtarget *ST;
424 const SIInstrInfo *TII =
nullptr;
425 const SIRegisterInfo *TRI =
nullptr;
426 const MachineRegisterInfo *MRI =
nullptr;
427 InstCounterType SmemAccessCounter;
428 InstCounterType MaxCounter;
429 const unsigned *WaitEventMaskForInst;
432 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
433 DenseMap<MachineBasicBlock *, bool> PreheadersToFlush;
434 MachineLoopInfo *MLI;
435 MachinePostDominatorTree *PDT;
439 std::unique_ptr<WaitcntBrackets> Incoming;
443 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
445 bool ForceEmitWaitcnt[NUM_INST_CNTS];
450 WaitcntGeneratorPreGFX12 WCGPreGFX12;
451 WaitcntGeneratorGFX12Plus WCGGFX12Plus;
453 WaitcntGenerator *WCG =
nullptr;
457 DenseSet<MachineInstr *> ReleaseVGPRInsts;
459 HardwareLimits Limits;
462 SIInsertWaitcnts(MachineLoopInfo *MLI, MachinePostDominatorTree *PDT,
464 : MLI(MLI), PDT(PDT), AA(AA) {
465 (void)ForceExpCounter;
466 (void)ForceLgkmCounter;
467 (void)ForceVMCounter;
470 unsigned getWaitCountMax(InstCounterType
T)
const {
473 return Limits.LoadcntMax;
475 return Limits.DscntMax;
477 return Limits.ExpcntMax;
479 return Limits.StorecntMax;
481 return Limits.SamplecntMax;
483 return Limits.BvhcntMax;
485 return Limits.KmcntMax;
487 return Limits.XcntMax;
494 bool shouldFlushVmCnt(MachineLoop *
ML,
const WaitcntBrackets &Brackets);
495 bool isPreheaderToFlush(MachineBasicBlock &
MBB,
496 const WaitcntBrackets &ScoreBrackets);
497 bool isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const;
498 bool run(MachineFunction &MF);
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 {
538 case AMDGPU::GLOBAL_INV:
540 case AMDGPU::GLOBAL_WB:
541 case AMDGPU::GLOBAL_WBINV:
542 return VMEM_WRITE_ACCESS;
548 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
549 VMEM_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
558 if (TII->mayAccessScratch(Inst))
559 return SCRATCH_WRITE_ACCESS;
560 return VMEM_WRITE_ACCESS;
564 return VmemReadMapping[getVmemType(Inst)];
567 bool isVmemAccess(
const MachineInstr &
MI)
const;
568 bool generateWaitcntInstBefore(MachineInstr &
MI,
569 WaitcntBrackets &ScoreBrackets,
570 MachineInstr *OldWaitcntInstr,
572 bool generateWaitcnt(AMDGPU::Waitcnt
Wait,
574 MachineBasicBlock &
Block, WaitcntBrackets &ScoreBrackets,
575 MachineInstr *OldWaitcntInstr);
576 void updateEventWaitcntAfter(MachineInstr &Inst,
577 WaitcntBrackets *ScoreBrackets);
579 MachineBasicBlock *
Block)
const;
580 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &
Block,
581 WaitcntBrackets &ScoreBrackets);
582 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &
Block,
583 WaitcntBrackets &ScoreBrackets);
594class WaitcntBrackets {
596 WaitcntBrackets(
const SIInsertWaitcnts *Context) : Context(Context) {
597 assert(Context->TRI->getNumRegUnits() < REGUNITS_END);
602 unsigned NumUnusedVmem = 0, NumUnusedSGPRs = 0;
603 for (
auto &[
ID, Val] : VMem) {
607 for (
auto &[
ID, Val] : SGPRs) {
612 if (NumUnusedVmem || NumUnusedSGPRs) {
613 errs() <<
"WaitcntBracket had unused entries at destruction time: "
614 << NumUnusedVmem <<
" VMem and " << NumUnusedSGPRs
615 <<
" SGPR unused entries\n";
621 bool isSmemCounter(InstCounterType
T)
const {
622 return T == Context->SmemAccessCounter ||
T == X_CNT;
625 unsigned getSgprScoresIdx(InstCounterType
T)
const {
626 assert(isSmemCounter(
T) &&
"Invalid SMEM counter");
627 return T == X_CNT ? 1 : 0;
630 unsigned getScoreLB(InstCounterType
T)
const {
635 unsigned getScoreUB(InstCounterType
T)
const {
640 unsigned getScoreRange(InstCounterType
T)
const {
641 return getScoreUB(
T) - getScoreLB(
T);
644 unsigned getSGPRScore(MCRegUnit RU, InstCounterType
T)
const {
645 auto It = SGPRs.find(RU);
646 return It != SGPRs.end() ? It->second.Scores[getSgprScoresIdx(
T)] : 0;
649 unsigned getVMemScore(VMEMID TID, InstCounterType
T)
const {
650 auto It = VMem.find(TID);
651 return It != VMem.end() ? It->second.Scores[
T] : 0;
656 bool counterOutOfOrder(InstCounterType
T)
const;
657 void simplifyWaitcnt(AMDGPU::Waitcnt &
Wait);
658 void simplifyWaitcnt(InstCounterType
T,
unsigned &
Count)
const;
659 bool hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait);
660 bool canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait);
661 void simplifyXcnt(AMDGPU::Waitcnt &CheckWait, AMDGPU::Waitcnt &UpdateWait);
663 void determineWaitForPhysReg(InstCounterType
T,
MCPhysReg Reg,
664 AMDGPU::Waitcnt &
Wait)
const;
665 void determineWaitForLDSDMA(InstCounterType
T, VMEMID TID,
666 AMDGPU::Waitcnt &
Wait)
const;
667 void tryClearSCCWriteEvent(MachineInstr *Inst);
669 void applyWaitcnt(
const AMDGPU::Waitcnt &
Wait);
670 void applyWaitcnt(InstCounterType
T,
unsigned Count);
671 void updateByEvent(WaitEventType
E, MachineInstr &
MI);
673 unsigned hasPendingEvent()
const {
return PendingEvents; }
674 unsigned hasPendingEvent(WaitEventType
E)
const {
675 return PendingEvents & (1 <<
E);
677 unsigned hasPendingEvent(InstCounterType
T)
const {
678 unsigned HasPending = PendingEvents & Context->WaitEventMaskForInst[
T];
679 assert((HasPending != 0) == (getScoreRange(
T) != 0));
683 bool hasMixedPendingEvents(InstCounterType
T)
const {
684 unsigned Events = hasPendingEvent(
T);
686 return Events & (Events - 1);
689 bool hasPendingFlat()
const {
690 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
691 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
692 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
693 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
696 void setPendingFlat() {
697 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
698 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
701 bool hasPendingGDS()
const {
702 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
705 unsigned getPendingGDSWait()
const {
706 return std::min(getScoreUB(DS_CNT) - LastGDS,
707 Context->getWaitCountMax(DS_CNT) - 1);
710 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
714 bool hasOtherPendingVmemTypes(
MCPhysReg Reg, VmemType V)
const {
715 for (MCRegUnit RU : regunits(
Reg)) {
716 auto It = VMem.find(toVMEMID(RU));
717 if (It != VMem.end() && (It->second.VMEMTypes & ~(1 << V)))
724 for (MCRegUnit RU : regunits(
Reg)) {
725 if (
auto It = VMem.find(toVMEMID(RU)); It != VMem.end()) {
726 It->second.VMEMTypes = 0;
727 if (It->second.empty())
733 void setStateOnFunctionEntryOrReturn() {
734 setScoreUB(STORE_CNT,
735 getScoreUB(STORE_CNT) + Context->getWaitCountMax(STORE_CNT));
736 PendingEvents |= Context->WaitEventMaskForInst[STORE_CNT];
739 ArrayRef<const MachineInstr *> getLDSDMAStores()
const {
743 bool hasPointSampleAccel(
const MachineInstr &
MI)
const;
744 bool hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
747 void print(raw_ostream &)
const;
752 void purgeEmptyTrackingData();
762 void determineWaitForScore(InstCounterType
T,
unsigned Score,
763 AMDGPU::Waitcnt &
Wait)
const;
765 static bool mergeScore(
const MergeInfo &M,
unsigned &Score,
766 unsigned OtherScore);
769 assert(
Reg != AMDGPU::SCC &&
"Shouldn't be used on SCC");
770 if (!Context->TRI->isInAllocatableClass(
Reg))
772 const TargetRegisterClass *RC = Context->TRI->getPhysRegBaseClass(
Reg);
773 unsigned Size = Context->TRI->getRegSizeInBits(*RC);
774 if (
Size == 16 && Context->ST->hasD16Writes32BitVgpr())
775 Reg = Context->TRI->get32BitRegister(
Reg);
776 return Context->TRI->regunits(
Reg);
779 void setScoreLB(InstCounterType
T,
unsigned Val) {
784 void setScoreUB(InstCounterType
T,
unsigned Val) {
791 if (getScoreRange(EXP_CNT) > Context->getWaitCountMax(EXP_CNT))
792 ScoreLBs[
EXP_CNT] = ScoreUBs[
EXP_CNT] - Context->getWaitCountMax(EXP_CNT);
795 void setRegScore(
MCPhysReg Reg, InstCounterType
T,
unsigned Val) {
796 const SIRegisterInfo *
TRI = Context->TRI;
797 if (
Reg == AMDGPU::SCC) {
799 }
else if (
TRI->isVectorRegister(*Context->MRI,
Reg)) {
800 for (MCRegUnit RU : regunits(
Reg))
801 VMem[toVMEMID(RU)].Scores[
T] = Val;
802 }
else if (
TRI->isSGPRReg(*Context->MRI,
Reg)) {
803 auto STy = getSgprScoresIdx(
T);
804 for (MCRegUnit RU : regunits(
Reg))
805 SGPRs[RU].Scores[STy] = Val;
811 void setVMemScore(VMEMID TID, InstCounterType
T,
unsigned Val) {
812 VMem[TID].Scores[
T] = Val;
815 void setScoreByOperand(
const MachineOperand &
Op, InstCounterType CntTy,
818 const SIInsertWaitcnts *Context;
820 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
821 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
822 unsigned PendingEvents = 0;
824 unsigned LastFlat[NUM_INST_CNTS] = {0};
826 unsigned LastGDS = 0;
843 std::array<unsigned, NUM_INST_CNTS> Scores = {0};
845 unsigned VMEMTypes = 0;
848 return all_of(Scores, [](
unsigned K) {
return K == 0; }) && !VMEMTypes;
857 std::array<unsigned, 2> Scores = {0};
859 bool empty()
const {
return !Scores[0] && !Scores[1]; }
862 DenseMap<VMEMID, VMEMInfo> VMem;
863 DenseMap<MCRegUnit, SGPRInfo> SGPRs;
866 unsigned SCCScore = 0;
868 const MachineInstr *PendingSCCWrite =
nullptr;
872 SmallVector<const MachineInstr *> LDSDMAStores;
878 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
880 bool runOnMachineFunction(MachineFunction &MF)
override;
882 StringRef getPassName()
const override {
883 return "SI insert wait instructions";
886 void getAnalysisUsage(AnalysisUsage &AU)
const override {
889 AU.
addRequired<MachinePostDominatorTreeWrapperPass>();
899 InstCounterType CntTy,
unsigned Score) {
900 setRegScore(
Op.getReg().asMCReg(), CntTy, Score);
908bool WaitcntBrackets::hasPointSampleAccel(
const MachineInstr &
MI)
const {
913 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
923bool WaitcntBrackets::hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
925 if (!hasPointSampleAccel(
MI))
928 return hasOtherPendingVmemTypes(
Reg, VMEM_NOSAMPLER);
931void WaitcntBrackets::updateByEvent(WaitEventType
E, MachineInstr &Inst) {
932 InstCounterType
T = eventCounter(
Context->WaitEventMaskForInst,
E);
935 unsigned UB = getScoreUB(
T);
936 unsigned CurrScore = UB + 1;
942 PendingEvents |= 1 <<
E;
943 setScoreUB(
T, CurrScore);
946 const MachineRegisterInfo *
MRI =
Context->MRI;
955 if (
const auto *AddrOp =
TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
956 setScoreByOperand(*AddrOp, EXP_CNT, CurrScore);
959 if (
const auto *Data0 =
960 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
961 setScoreByOperand(*Data0, EXP_CNT, CurrScore);
962 if (
const auto *Data1 =
963 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
964 setScoreByOperand(*Data1, EXP_CNT, CurrScore);
967 Inst.
getOpcode() != AMDGPU::DS_CONSUME &&
968 Inst.
getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
969 for (
const MachineOperand &
Op : Inst.
all_uses()) {
970 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
971 setScoreByOperand(
Op, EXP_CNT, CurrScore);
974 }
else if (
TII->isFLAT(Inst)) {
976 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
979 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
982 }
else if (
TII->isMIMG(Inst)) {
984 setScoreByOperand(Inst.
getOperand(0), EXP_CNT, CurrScore);
986 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
989 }
else if (
TII->isMTBUF(Inst)) {
991 setScoreByOperand(Inst.
getOperand(0), EXP_CNT, CurrScore);
992 }
else if (
TII->isMUBUF(Inst)) {
994 setScoreByOperand(Inst.
getOperand(0), EXP_CNT, CurrScore);
996 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
999 }
else if (
TII->isLDSDIR(Inst)) {
1001 setScoreByOperand(*
TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
1002 EXP_CNT, CurrScore);
1004 if (
TII->isEXP(Inst)) {
1009 for (MachineOperand &DefMO : Inst.
all_defs()) {
1010 if (
TRI->isVGPR(*
MRI, DefMO.getReg())) {
1011 setScoreByOperand(DefMO, EXP_CNT, CurrScore);
1015 for (
const MachineOperand &
Op : Inst.
all_uses()) {
1016 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1017 setScoreByOperand(
Op, EXP_CNT, CurrScore);
1020 }
else if (
T == X_CNT) {
1021 WaitEventType OtherEvent =
E == SMEM_GROUP ? VMEM_GROUP : SMEM_GROUP;
1022 if (PendingEvents & (1 << OtherEvent)) {
1027 setScoreLB(
T, getScoreUB(
T) - 1);
1028 PendingEvents &= ~(1 << OtherEvent);
1030 for (
const MachineOperand &
Op : Inst.
all_uses())
1031 setScoreByOperand(
Op,
T, CurrScore);
1042 for (
const MachineOperand &
Op : Inst.
defs()) {
1043 if (
T == LOAD_CNT ||
T == SAMPLE_CNT ||
T == BVH_CNT) {
1044 if (!
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1046 if (updateVMCntOnly(Inst)) {
1051 VmemType
V = getVmemType(Inst);
1052 unsigned char TypesMask = 1 <<
V;
1055 if (hasPointSampleAccel(Inst))
1056 TypesMask |= 1 << VMEM_NOSAMPLER;
1057 for (MCRegUnit RU : regunits(
Op.getReg().asMCReg()))
1058 VMem[toVMEMID(RU)].VMEMTypes |= TypesMask;
1061 setScoreByOperand(
Op,
T, CurrScore);
1064 (
TII->isDS(Inst) ||
TII->mayWriteLDSThroughDMA(Inst))) {
1073 if (!MemOp->isStore() ||
1078 auto AAI = MemOp->getAAInfo();
1084 if (!AAI || !AAI.Scope)
1086 for (
unsigned I = 0,
E = LDSDMAStores.
size();
I !=
E && !Slot; ++
I) {
1087 for (
const auto *MemOp : LDSDMAStores[
I]->memoperands()) {
1088 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1103 setVMemScore(LDSDMA_BEGIN,
T, CurrScore);
1104 if (Slot && Slot < NUM_LDSDMA)
1105 setVMemScore(LDSDMA_BEGIN + Slot,
T, CurrScore);
1109 setRegScore(AMDGPU::SCC,
T, CurrScore);
1110 PendingSCCWrite = &Inst;
1115void WaitcntBrackets::print(raw_ostream &OS)
const {
1119 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
1120 unsigned SR = getScoreRange(
T);
1124 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"LOAD" :
"VM") <<
"_CNT("
1128 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"DS" :
"LGKM") <<
"_CNT("
1132 OS <<
" EXP_CNT(" << SR <<
"):";
1135 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"STORE" :
"VS") <<
"_CNT("
1139 OS <<
" SAMPLE_CNT(" << SR <<
"):";
1142 OS <<
" BVH_CNT(" << SR <<
"):";
1145 OS <<
" KM_CNT(" << SR <<
"):";
1148 OS <<
" X_CNT(" << SR <<
"):";
1151 OS <<
" UNKNOWN(" << SR <<
"):";
1157 unsigned LB = getScoreLB(
T);
1160 sort(SortedVMEMIDs);
1162 for (
auto ID : SortedVMEMIDs) {
1163 unsigned RegScore = VMem.at(
ID).Scores[
T];
1166 unsigned RelScore = RegScore - LB - 1;
1167 if (
ID < REGUNITS_END) {
1168 OS <<
' ' << RelScore <<
":vRU" <<
ID;
1170 assert(
ID >= LDSDMA_BEGIN &&
ID < LDSDMA_END &&
1171 "Unhandled/unexpected ID value!");
1172 OS <<
' ' << RelScore <<
":LDSDMA" <<
ID;
1177 if (isSmemCounter(
T)) {
1179 sort(SortedSMEMIDs);
1180 for (
auto ID : SortedSMEMIDs) {
1181 unsigned RegScore = SGPRs.at(
ID).Scores[getSgprScoresIdx(
T)];
1184 unsigned RelScore = RegScore - LB - 1;
1185 OS <<
' ' << RelScore <<
":sRU" <<
static_cast<unsigned>(
ID);
1189 if (
T == KM_CNT && SCCScore > 0)
1190 OS <<
' ' << SCCScore <<
":scc";
1195 OS <<
"Pending Events: ";
1196 if (hasPendingEvent()) {
1198 for (
unsigned I = 0;
I != NUM_WAIT_EVENTS; ++
I) {
1199 if (hasPendingEvent((WaitEventType)
I)) {
1200 OS <<
LS << WaitEventTypeName[
I];
1213void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &
Wait) {
1214 simplifyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1215 simplifyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1216 simplifyWaitcnt(DS_CNT,
Wait.DsCnt);
1217 simplifyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1218 simplifyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1219 simplifyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1220 simplifyWaitcnt(KM_CNT,
Wait.KmCnt);
1224void WaitcntBrackets::simplifyWaitcnt(InstCounterType
T,
1225 unsigned &
Count)
const {
1229 if (
Count >= getScoreRange(
T))
1233void WaitcntBrackets::purgeEmptyTrackingData() {
1244void WaitcntBrackets::determineWaitForScore(InstCounterType
T,
1245 unsigned ScoreToWait,
1246 AMDGPU::Waitcnt &
Wait)
const {
1247 const unsigned LB = getScoreLB(
T);
1248 const unsigned UB = getScoreUB(
T);
1251 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1252 if ((
T == LOAD_CNT ||
T == DS_CNT) && hasPendingFlat() &&
1253 !
Context->ST->hasFlatLgkmVMemCountInOrder()) {
1257 addWait(
Wait,
T, 0);
1258 }
else if (counterOutOfOrder(
T)) {
1262 addWait(
Wait,
T, 0);
1266 unsigned NeededWait =
1267 std::min(UB - ScoreToWait,
Context->getWaitCountMax(
T) - 1);
1268 addWait(
Wait,
T, NeededWait);
1273void WaitcntBrackets::determineWaitForPhysReg(InstCounterType
T,
MCPhysReg Reg,
1274 AMDGPU::Waitcnt &
Wait)
const {
1275 if (
Reg == AMDGPU::SCC) {
1276 determineWaitForScore(
T, SCCScore,
Wait);
1279 for (MCRegUnit RU : regunits(
Reg))
1280 determineWaitForScore(
1281 T, IsVGPR ? getVMemScore(toVMEMID(RU),
T) : getSGPRScore(RU,
T),
1286void WaitcntBrackets::determineWaitForLDSDMA(InstCounterType
T, VMEMID TID,
1287 AMDGPU::Waitcnt &
Wait)
const {
1288 assert(TID >= LDSDMA_BEGIN && TID < LDSDMA_END);
1289 determineWaitForScore(
T, getVMemScore(TID,
T),
Wait);
1292void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1295 if (PendingSCCWrite &&
1296 PendingSCCWrite->
getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1298 unsigned SCC_WRITE_PendingEvent = 1 << SCC_WRITE;
1300 if ((PendingEvents &
Context->WaitEventMaskForInst[KM_CNT]) ==
1301 SCC_WRITE_PendingEvent) {
1302 setScoreLB(KM_CNT, getScoreUB(KM_CNT));
1305 PendingEvents &= ~SCC_WRITE_PendingEvent;
1306 PendingSCCWrite =
nullptr;
1310void WaitcntBrackets::applyWaitcnt(
const AMDGPU::Waitcnt &
Wait) {
1311 applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1312 applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1313 applyWaitcnt(DS_CNT,
Wait.DsCnt);
1314 applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1315 applyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1316 applyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1317 applyWaitcnt(KM_CNT,
Wait.KmCnt);
1318 applyWaitcnt(X_CNT,
Wait.XCnt);
1321void WaitcntBrackets::applyWaitcnt(InstCounterType
T,
unsigned Count) {
1322 const unsigned UB = getScoreUB(
T);
1326 if (counterOutOfOrder(
T))
1328 setScoreLB(
T, std::max(getScoreLB(
T), UB -
Count));
1331 PendingEvents &= ~Context->WaitEventMaskForInst[
T];
1335bool WaitcntBrackets::hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait) {
1339 return Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP);
1342bool WaitcntBrackets::canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait) {
1346 return Wait.LoadCnt != ~0
u && hasPendingEvent(VMEM_GROUP) &&
1347 !hasPendingEvent(STORE_CNT);
1350void WaitcntBrackets::simplifyXcnt(AMDGPU::Waitcnt &CheckWait,
1351 AMDGPU::Waitcnt &UpdateWait) {
1357 if (hasRedundantXCntWithKmCnt(CheckWait)) {
1358 if (!hasMixedPendingEvents(X_CNT)) {
1359 applyWaitcnt(X_CNT, 0);
1361 PendingEvents &= ~(1 << SMEM_GROUP);
1363 }
else if (canOptimizeXCntWithLoadCnt(CheckWait)) {
1364 if (!hasMixedPendingEvents(X_CNT)) {
1365 applyWaitcnt(X_CNT, std::min(CheckWait.
XCnt, CheckWait.
LoadCnt));
1366 }
else if (CheckWait.
LoadCnt == 0) {
1367 PendingEvents &= ~(1 << VMEM_GROUP);
1370 simplifyWaitcnt(X_CNT, UpdateWait.
XCnt);
1375bool WaitcntBrackets::counterOutOfOrder(InstCounterType
T)
const {
1377 if ((
T ==
Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1378 (
T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1380 return hasMixedPendingEvents(
T);
1390char SIInsertWaitcntsLegacy::
ID = 0;
1395 return new SIInsertWaitcntsLegacy();
1400 int OpIdx = AMDGPU::getNamedOperandIdx(
MI.getOpcode(),
OpName);
1405 if (NewEnc == MO.
getImm())
1416 case AMDGPU::S_WAIT_LOADCNT:
1418 case AMDGPU::S_WAIT_EXPCNT:
1420 case AMDGPU::S_WAIT_STORECNT:
1422 case AMDGPU::S_WAIT_SAMPLECNT:
1424 case AMDGPU::S_WAIT_BVHCNT:
1426 case AMDGPU::S_WAIT_DSCNT:
1428 case AMDGPU::S_WAIT_KMCNT:
1430 case AMDGPU::S_WAIT_XCNT:
1437bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt)
const {
1451bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1452 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1455 assert(isNormalMode(MaxCounter));
1458 MachineInstr *WaitcntInstr =
nullptr;
1459 MachineInstr *WaitcntVsCntInstr =
nullptr;
1462 dbgs() <<
"PreGFX12::applyPreexistingWaitcnt at: ";
1464 dbgs() <<
"end of block\n";
1472 if (
II.isMetaInstruction()) {
1478 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1482 if (Opcode == AMDGPU::S_WAITCNT) {
1483 unsigned IEnc =
II.getOperand(0).getImm();
1486 ScoreBrackets.simplifyWaitcnt(OldWait);
1490 if (WaitcntInstr || (!
Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1491 II.eraseFromParent();
1495 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1498 <<
"Before: " <<
Wait <<
'\n';);
1499 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, LDSDMA_BEGIN,
Wait);
1508 II.eraseFromParent();
1510 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1511 assert(
II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1514 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1516 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1517 Wait.StoreCnt = std::min(
Wait.StoreCnt, OldVSCnt);
1519 if (WaitcntVsCntInstr || (!
Wait.hasWaitStoreCnt() && TrySimplify)) {
1520 II.eraseFromParent();
1523 WaitcntVsCntInstr = &
II;
1530 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1532 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1533 ScoreBrackets.applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1534 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1541 <<
"applied pre-existing waitcnt\n"
1542 <<
"New Instr at block end: " << *WaitcntInstr <<
'\n'
1543 :
dbgs() <<
"applied pre-existing waitcnt\n"
1544 <<
"Old Instr: " << *It
1545 <<
"New Instr: " << *WaitcntInstr <<
'\n');
1548 if (WaitcntVsCntInstr) {
1550 AMDGPU::OpName::simm16,
Wait.StoreCnt);
1551 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1553 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1554 Wait.StoreCnt = ~0
u;
1557 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1558 <<
"New Instr at block end: " << *WaitcntVsCntInstr
1560 :
dbgs() <<
"applied pre-existing waitcnt\n"
1561 <<
"Old Instr: " << *It
1562 <<
"New Instr: " << *WaitcntVsCntInstr <<
'\n');
1570bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1572 AMDGPU::Waitcnt
Wait) {
1574 assert(isNormalMode(MaxCounter));
1581 if (
Wait.hasWaitExceptStoreCnt()) {
1583 [[maybe_unused]]
auto SWaitInst =
1588 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1589 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1592 if (
Wait.hasWaitStoreCnt()) {
1595 [[maybe_unused]]
auto SWaitInst =
1602 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1603 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1610WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1611 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt &&
ST->hasVscnt() ? 0 : ~0u);
1615WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1616 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1624bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1625 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1628 assert(!isNormalMode(MaxCounter));
1631 MachineInstr *CombinedLoadDsCntInstr =
nullptr;
1632 MachineInstr *CombinedStoreDsCntInstr =
nullptr;
1633 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1636 dbgs() <<
"GFX12Plus::applyPreexistingWaitcnt at: ";
1638 dbgs() <<
"end of block\n";
1646 if (
II.isMetaInstruction()) {
1651 MachineInstr **UpdatableInstr;
1657 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1661 if (Opcode == AMDGPU::S_WAITCNT)
1664 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1666 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1669 ScoreBrackets.simplifyWaitcnt(OldWait);
1671 UpdatableInstr = &CombinedLoadDsCntInstr;
1672 }
else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1674 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1677 ScoreBrackets.simplifyWaitcnt(OldWait);
1679 UpdatableInstr = &CombinedStoreDsCntInstr;
1680 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1683 II.eraseFromParent();
1689 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1691 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1692 addWait(
Wait, CT.value(), OldCnt);
1693 UpdatableInstr = &WaitInstrs[CT.value()];
1697 if (!*UpdatableInstr) {
1698 *UpdatableInstr = &
II;
1700 II.eraseFromParent();
1706 AMDGPU::Waitcnt PreCombine =
Wait;
1707 if (CombinedLoadDsCntInstr) {
1715 if (
Wait.LoadCnt != ~0u &&
Wait.DsCnt != ~0u) {
1718 AMDGPU::OpName::simm16, NewEnc);
1719 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1720 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1721 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1726 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1727 <<
"New Instr at block end: "
1728 << *CombinedLoadDsCntInstr <<
'\n'
1729 :
dbgs() <<
"applied pre-existing waitcnt\n"
1730 <<
"Old Instr: " << *It <<
"New Instr: "
1731 << *CombinedLoadDsCntInstr <<
'\n');
1738 if (CombinedStoreDsCntInstr) {
1740 if (
Wait.StoreCnt != ~0u &&
Wait.DsCnt != ~0u) {
1743 AMDGPU::OpName::simm16, NewEnc);
1744 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1745 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1746 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1747 Wait.StoreCnt = ~0
u;
1751 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1752 <<
"New Instr at block end: "
1753 << *CombinedStoreDsCntInstr <<
'\n'
1754 :
dbgs() <<
"applied pre-existing waitcnt\n"
1755 <<
"Old Instr: " << *It <<
"New Instr: "
1756 << *CombinedStoreDsCntInstr <<
'\n');
1769 if (
Wait.DsCnt != ~0u) {
1778 if (
Wait.LoadCnt != ~0u) {
1779 WaitsToErase.
push_back(&WaitInstrs[LOAD_CNT]);
1780 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1781 }
else if (
Wait.StoreCnt != ~0u) {
1782 WaitsToErase.
push_back(&WaitInstrs[STORE_CNT]);
1783 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1786 for (MachineInstr **WI : WaitsToErase) {
1790 (*WI)->eraseFromParent();
1796 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1797 if ((CT == KM_CNT && ScoreBrackets.hasRedundantXCntWithKmCnt(PreCombine)) ||
1799 ScoreBrackets.canOptimizeXCntWithLoadCnt(PreCombine))) {
1802 ScoreBrackets.simplifyXcnt(PreCombine,
Wait);
1804 if (!WaitInstrs[CT])
1807 unsigned NewCnt = getWait(
Wait, CT);
1808 if (NewCnt != ~0u) {
1810 AMDGPU::OpName::simm16, NewCnt);
1811 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1813 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1814 setNoWait(
Wait, CT);
1817 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1818 <<
"New Instr at block end: " << *WaitInstrs[CT]
1820 :
dbgs() <<
"applied pre-existing waitcnt\n"
1821 <<
"Old Instr: " << *It
1822 <<
"New Instr: " << *WaitInstrs[CT] <<
'\n');
1833bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1835 AMDGPU::Waitcnt
Wait) {
1837 assert(!isNormalMode(MaxCounter));
1843 if (
Wait.DsCnt != ~0u) {
1844 MachineInstr *SWaitInst =
nullptr;
1846 if (
Wait.LoadCnt != ~0u) {
1854 }
else if (
Wait.StoreCnt != ~0u) {
1861 Wait.StoreCnt = ~0
u;
1869 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1870 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1877 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1882 [[maybe_unused]]
auto SWaitInst =
1889 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1890 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1921bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &
MI,
1922 WaitcntBrackets &ScoreBrackets,
1923 MachineInstr *OldWaitcntInstr,
1925 setForceEmitWaitcnt();
1929 AMDGPU::Waitcnt
Wait;
1930 const unsigned Opc =
MI.getOpcode();
1936 if (
Opc == AMDGPU::BUFFER_WBINVL1 ||
Opc == AMDGPU::BUFFER_WBINVL1_SC ||
1937 Opc == AMDGPU::BUFFER_WBINVL1_VOL ||
Opc == AMDGPU::BUFFER_GL0_INV ||
1938 Opc == AMDGPU::BUFFER_GL1_INV) {
1945 if (
Opc == AMDGPU::SI_RETURN_TO_EPILOG ||
Opc == AMDGPU::SI_RETURN ||
1946 Opc == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1947 Opc == AMDGPU::S_SETPC_B64_return ||
1949 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
false));
1959 else if (
Opc == AMDGPU::S_ENDPGM ||
Opc == AMDGPU::S_ENDPGM_SAVED) {
1960 if (!WCG->isOptNone() &&
1961 (
MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1962 (
ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1963 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1964 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1968 else if ((
Opc == AMDGPU::S_SENDMSG ||
Opc == AMDGPU::S_SENDMSGHALT) &&
1969 ST->hasLegacyGeometry() &&
1980 if (
MI.modifiesRegister(AMDGPU::EXEC,
TRI)) {
1983 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1984 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1985 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1986 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1993 if (
TII->isAlwaysGDS(
Opc) && ScoreBrackets.hasPendingGDS())
1994 addWait(
Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
2000 Wait = AMDGPU::Waitcnt();
2002 const auto &CallAddrOp = *
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
2003 if (CallAddrOp.isReg()) {
2004 ScoreBrackets.determineWaitForPhysReg(
2005 SmemAccessCounter, CallAddrOp.getReg().asMCReg(),
Wait);
2007 if (
const auto *RtnAddrOp =
2008 TII->getNamedOperand(
MI, AMDGPU::OpName::dst)) {
2009 ScoreBrackets.determineWaitForPhysReg(
2010 SmemAccessCounter, RtnAddrOp->getReg().asMCReg(),
Wait);
2013 }
else if (
Opc == AMDGPU::S_BARRIER_WAIT) {
2014 ScoreBrackets.tryClearSCCWriteEvent(&
MI);
2030 for (
const MachineMemOperand *Memop :
MI.memoperands()) {
2031 const Value *Ptr = Memop->getValue();
2032 if (Memop->isStore()) {
2033 if (
auto It = SLoadAddresses.
find(Ptr); It != SLoadAddresses.
end()) {
2034 addWait(
Wait, SmemAccessCounter, 0);
2036 SLoadAddresses.
erase(It);
2039 unsigned AS = Memop->getAddrSpace();
2043 if (
TII->mayWriteLDSThroughDMA(
MI))
2047 unsigned TID = LDSDMA_BEGIN;
2048 if (Ptr && Memop->getAAInfo()) {
2049 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
2050 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E; ++
I) {
2051 if (
MI.mayAlias(AA, *LDSDMAStores[
I],
true)) {
2052 if ((
I + 1) >= NUM_LDSDMA) {
2055 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID,
Wait);
2059 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID +
I + 1,
Wait);
2063 ScoreBrackets.determineWaitForLDSDMA(LOAD_CNT, TID,
Wait);
2065 if (Memop->isStore()) {
2066 ScoreBrackets.determineWaitForLDSDMA(EXP_CNT, TID,
Wait);
2071 for (
const MachineOperand &
Op :
MI.operands()) {
2076 if (
Op.isTied() &&
Op.isUse() &&
TII->doesNotReadTiedSource(
MI))
2081 const bool IsVGPR =
TRI->isVectorRegister(*
MRI,
Op.getReg());
2088 if (
Op.isImplicit() &&
MI.mayLoadOrStore())
2097 if (
Op.isUse() || !updateVMCntOnly(
MI) ||
2098 ScoreBrackets.hasOtherPendingVmemTypes(
Reg, getVmemType(
MI)) ||
2099 ScoreBrackets.hasPointSamplePendingVmemTypes(
MI,
Reg) ||
2100 !
ST->hasVmemWriteVgprInOrder()) {
2101 ScoreBrackets.determineWaitForPhysReg(LOAD_CNT,
Reg,
Wait);
2102 ScoreBrackets.determineWaitForPhysReg(SAMPLE_CNT,
Reg,
Wait);
2103 ScoreBrackets.determineWaitForPhysReg(BVH_CNT,
Reg,
Wait);
2104 ScoreBrackets.clearVgprVmemTypes(
Reg);
2107 if (
Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2108 ScoreBrackets.determineWaitForPhysReg(EXP_CNT,
Reg,
Wait);
2110 ScoreBrackets.determineWaitForPhysReg(DS_CNT,
Reg,
Wait);
2111 }
else if (
Op.getReg() == AMDGPU::SCC) {
2112 ScoreBrackets.determineWaitForPhysReg(KM_CNT,
Reg,
Wait);
2114 ScoreBrackets.determineWaitForPhysReg(SmemAccessCounter,
Reg,
Wait);
2117 if (
ST->hasWaitXCnt() &&
Op.isDef())
2118 ScoreBrackets.determineWaitForPhysReg(X_CNT,
Reg,
Wait);
2135 if (
Opc == AMDGPU::S_BARRIER && !
ST->hasAutoWaitcntBeforeBarrier() &&
2136 !
ST->supportsBackOffBarrier()) {
2137 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
true));
2144 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2149 ScoreBrackets.simplifyWaitcnt(
Wait);
2154 if (
Wait.XCnt != ~0u && isVmemAccess(
MI)) {
2155 ScoreBrackets.applyWaitcnt(X_CNT,
Wait.XCnt);
2162 Wait = WCG->getAllZeroWaitcnt(
false);
2164 if (ForceEmitWaitcnt[LOAD_CNT])
2166 if (ForceEmitWaitcnt[EXP_CNT])
2168 if (ForceEmitWaitcnt[DS_CNT])
2170 if (ForceEmitWaitcnt[SAMPLE_CNT])
2172 if (ForceEmitWaitcnt[BVH_CNT])
2174 if (ForceEmitWaitcnt[KM_CNT])
2176 if (ForceEmitWaitcnt[X_CNT])
2180 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2182 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2184 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2191 return generateWaitcnt(
Wait,
MI.getIterator(), *
MI.getParent(), ScoreBrackets,
2195bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt
Wait,
2197 MachineBasicBlock &
Block,
2198 WaitcntBrackets &ScoreBrackets,
2199 MachineInstr *OldWaitcntInstr) {
2202 if (OldWaitcntInstr)
2206 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr,
Wait, It);
2210 ScoreBrackets.applyWaitcnt(
Wait);
2213 if (
Wait.ExpCnt != ~0u && It !=
Block.instr_end() &&
2215 MachineOperand *WaitExp =
2216 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2224 <<
"Update Instr: " << *It);
2227 if (WCG->createNewWaitcnt(
Block, It,
Wait))
2233bool SIInsertWaitcnts::isVmemAccess(
const MachineInstr &
MI)
const {
2234 return (
TII->isFLAT(
MI) &&
TII->mayAccessVMEMThroughFlat(
MI)) ||
2241 MachineBasicBlock *
Block)
const {
2242 auto BlockEnd =
Block->getParent()->end();
2243 auto BlockIter =
Block->getIterator();
2247 if (++BlockIter != BlockEnd) {
2248 It = BlockIter->instr_begin();
2255 if (!It->isMetaInstruction())
2263 return It->getOpcode() == AMDGPU::S_ENDPGM;
2267bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2268 MachineBasicBlock &
Block,
2269 WaitcntBrackets &ScoreBrackets) {
2270 AMDGPU::Waitcnt
Wait;
2271 bool NeedsEndPGMCheck =
false;
2279 NeedsEndPGMCheck =
true;
2282 ScoreBrackets.simplifyWaitcnt(
Wait);
2285 bool Result = generateWaitcnt(
Wait, SuccessorIt,
Block, ScoreBrackets,
2288 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &
Block)) {
2296void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2297 WaitcntBrackets *ScoreBrackets) {
2305 bool IsVMEMAccess =
false;
2306 bool IsSMEMAccess =
false;
2307 if (
TII->isDS(Inst) &&
TII->usesLGKM_CNT(Inst)) {
2309 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2310 ScoreBrackets->updateByEvent(GDS_ACCESS, Inst);
2311 ScoreBrackets->updateByEvent(GDS_GPR_LOCK, Inst);
2312 ScoreBrackets->setPendingGDS();
2314 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2316 }
else if (
TII->isFLAT(Inst)) {
2318 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2324 int FlatASCount = 0;
2326 if (
TII->mayAccessVMEMThroughFlat(Inst)) {
2328 IsVMEMAccess =
true;
2329 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2332 if (
TII->mayAccessLDSThroughFlat(Inst)) {
2334 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2343 ScoreBrackets->setPendingFlat();
2346 IsVMEMAccess =
true;
2347 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2349 if (
ST->vmemWriteNeedsExpWaitcnt() &&
2351 ScoreBrackets->updateByEvent(VMW_GPR_LOCK, Inst);
2353 }
else if (
TII->isSMRD(Inst)) {
2354 IsSMEMAccess =
true;
2355 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2356 }
else if (Inst.
isCall()) {
2359 ScoreBrackets->applyWaitcnt(
2360 WCG->getAllZeroWaitcnt(
false));
2361 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2364 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2367 ScoreBrackets->updateByEvent(EXP_LDS_ACCESS, Inst);
2368 }
else if (
TII->isVINTERP(Inst)) {
2369 int64_t
Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2370 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2372 unsigned Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2374 ScoreBrackets->updateByEvent(EXP_PARAM_ACCESS, Inst);
2376 ScoreBrackets->updateByEvent(EXP_POS_ACCESS, Inst);
2378 ScoreBrackets->updateByEvent(EXP_GPR_LOCK, Inst);
2380 ScoreBrackets->updateByEvent(SCC_WRITE, Inst);
2383 case AMDGPU::S_SENDMSG:
2384 case AMDGPU::S_SENDMSG_RTN_B32:
2385 case AMDGPU::S_SENDMSG_RTN_B64:
2386 case AMDGPU::S_SENDMSGHALT:
2387 ScoreBrackets->updateByEvent(SQ_MESSAGE, Inst);
2389 case AMDGPU::S_MEMTIME:
2390 case AMDGPU::S_MEMREALTIME:
2391 case AMDGPU::S_GET_BARRIER_STATE_M0:
2392 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2393 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2398 if (!
ST->hasWaitXCnt())
2402 ScoreBrackets->updateByEvent(VMEM_GROUP, Inst);
2405 ScoreBrackets->updateByEvent(SMEM_GROUP, Inst);
2408bool WaitcntBrackets::mergeScore(
const MergeInfo &M,
unsigned &Score,
2409 unsigned OtherScore) {
2410 unsigned MyShifted = Score <=
M.OldLB ? 0 : Score +
M.MyShift;
2411 unsigned OtherShifted =
2412 OtherScore <=
M.OtherLB ? 0 : OtherScore +
M.OtherShift;
2413 Score = std::max(MyShifted, OtherShifted);
2414 return OtherShifted > MyShifted;
2422bool WaitcntBrackets::merge(
const WaitcntBrackets &
Other) {
2423 bool StrictDom =
false;
2427 for (
auto K :
Other.VMem.keys())
2428 VMem.try_emplace(K);
2429 for (
auto K :
Other.SGPRs.keys())
2430 SGPRs.try_emplace(K);
2432 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
2434 const unsigned *WaitEventMaskForInst =
Context->WaitEventMaskForInst;
2435 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[
T];
2436 const unsigned OtherEvents =
Other.PendingEvents & WaitEventMaskForInst[
T];
2437 if (OtherEvents & ~OldEvents)
2439 PendingEvents |= OtherEvents;
2442 const unsigned MyPending = ScoreUBs[
T] - ScoreLBs[
T];
2443 const unsigned OtherPending =
Other.ScoreUBs[
T] -
Other.ScoreLBs[
T];
2444 const unsigned NewUB = ScoreLBs[
T] + std::max(MyPending, OtherPending);
2445 if (NewUB < ScoreLBs[
T])
2449 M.OldLB = ScoreLBs[
T];
2450 M.OtherLB =
Other.ScoreLBs[
T];
2451 M.MyShift = NewUB - ScoreUBs[
T];
2452 M.OtherShift = NewUB -
Other.ScoreUBs[
T];
2454 ScoreUBs[
T] = NewUB;
2456 StrictDom |= mergeScore(M, LastFlat[
T],
Other.LastFlat[
T]);
2459 StrictDom |= mergeScore(M, LastGDS,
Other.LastGDS);
2462 StrictDom |= mergeScore(M, SCCScore,
Other.SCCScore);
2463 if (
Other.hasPendingEvent(SCC_WRITE)) {
2464 unsigned OldEventsHasSCCWrite = OldEvents & (1 << SCC_WRITE);
2465 if (!OldEventsHasSCCWrite) {
2466 PendingSCCWrite =
Other.PendingSCCWrite;
2467 }
else if (PendingSCCWrite !=
Other.PendingSCCWrite) {
2468 PendingSCCWrite =
nullptr;
2473 for (
auto &[RegID,
Info] : VMem)
2474 StrictDom |= mergeScore(M,
Info.Scores[
T],
Other.getVMemScore(RegID,
T));
2476 if (isSmemCounter(
T)) {
2477 unsigned Idx = getSgprScoresIdx(
T);
2478 for (
auto &[RegID,
Info] : SGPRs) {
2479 auto It =
Other.SGPRs.find(RegID);
2480 unsigned OtherScore =
2481 (It !=
Other.SGPRs.end()) ? It->second.Scores[Idx] : 0;
2482 StrictDom |= mergeScore(M,
Info.Scores[Idx], OtherScore);
2487 for (
auto &[TID,
Info] : VMem) {
2488 if (
auto It =
Other.VMem.find(TID); It !=
Other.VMem.end()) {
2489 unsigned char NewVmemTypes =
Info.VMEMTypes | It->second.VMEMTypes;
2490 StrictDom |= NewVmemTypes !=
Info.VMEMTypes;
2491 Info.VMEMTypes = NewVmemTypes;
2495 purgeEmptyTrackingData();
2501 return Opcode == AMDGPU::S_WAITCNT ||
2504 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2505 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2506 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2511bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2512 MachineBasicBlock &
Block,
2513 WaitcntBrackets &ScoreBrackets) {
2517 dbgs() <<
"*** Begin Block: ";
2519 ScoreBrackets.dump();
2525 bool VCCZCorrect =
true;
2526 if (
ST->hasReadVCCZBug()) {
2529 VCCZCorrect =
false;
2530 }
else if (!
ST->partialVCCWritesUpdateVCCZ()) {
2533 VCCZCorrect =
false;
2537 MachineInstr *OldWaitcntInstr =
nullptr;
2542 MachineInstr &Inst = *Iter;
2551 if (!OldWaitcntInstr)
2552 OldWaitcntInstr = &Inst;
2557 bool FlushVmCnt =
Block.getFirstTerminator() == Inst &&
2558 isPreheaderToFlush(
Block, ScoreBrackets);
2561 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2563 OldWaitcntInstr =
nullptr;
2569 if (
ST->hasReadVCCZBug() || !
ST->partialVCCWritesUpdateVCCZ()) {
2573 if (!
ST->partialVCCWritesUpdateVCCZ())
2574 VCCZCorrect =
false;
2583 if (
ST->hasReadVCCZBug() &&
2584 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2587 VCCZCorrect =
false;
2595 if (
TII->isSMRD(Inst)) {
2596 for (
const MachineMemOperand *Memop : Inst.
memoperands()) {
2599 if (!Memop->isInvariant()) {
2600 const Value *Ptr = Memop->getValue();
2604 if (
ST->hasReadVCCZBug()) {
2606 VCCZCorrect =
false;
2610 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2612 Modified |= insertForcedWaitAfter(Inst,
Block, ScoreBrackets);
2616 ScoreBrackets.dump();
2626 TII->get(
ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2638 AMDGPU::Waitcnt
Wait;
2639 if (
Block.getFirstTerminator() ==
Block.end() &&
2640 isPreheaderToFlush(
Block, ScoreBrackets)) {
2641 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2643 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2645 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2654 dbgs() <<
"*** End Block: ";
2656 ScoreBrackets.dump();
2664bool SIInsertWaitcnts::isPreheaderToFlush(
2665 MachineBasicBlock &
MBB,
const WaitcntBrackets &ScoreBrackets) {
2666 auto [Iterator, IsInserted] = PreheadersToFlush.
try_emplace(&
MBB,
false);
2668 return Iterator->second;
2679 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2680 Iterator->second =
true;
2687bool SIInsertWaitcnts::isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const {
2689 return TII->mayAccessVMEMThroughFlat(
MI);
2701bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *
ML,
2702 const WaitcntBrackets &Brackets) {
2703 bool HasVMemLoad =
false;
2704 bool HasVMemStore =
false;
2705 bool UsesVgprLoadedOutside =
false;
2706 DenseSet<MCRegUnit> VgprUse;
2707 DenseSet<MCRegUnit> VgprDef;
2709 for (MachineBasicBlock *
MBB :
ML->blocks()) {
2710 for (MachineInstr &
MI : *
MBB) {
2711 if (isVMEMOrFlatVMEM(
MI)) {
2712 HasVMemLoad |=
MI.mayLoad();
2713 HasVMemStore |=
MI.mayStore();
2716 for (
const MachineOperand &
Op :
MI.all_uses()) {
2717 if (
Op.isDebug() || !
TRI->isVectorRegister(*
MRI,
Op.getReg()))
2720 for (MCRegUnit RU :
TRI->regunits(
Op.getReg().asMCReg())) {
2728 VMEMID
ID = toVMEMID(RU);
2729 if (Brackets.getVMemScore(
ID, LOAD_CNT) >
2730 Brackets.getScoreLB(LOAD_CNT) ||
2731 Brackets.getVMemScore(
ID, SAMPLE_CNT) >
2732 Brackets.getScoreLB(SAMPLE_CNT) ||
2733 Brackets.getVMemScore(
ID, BVH_CNT) >
2734 Brackets.getScoreLB(BVH_CNT)) {
2735 UsesVgprLoadedOutside =
true;
2742 if (isVMEMOrFlatVMEM(
MI) &&
MI.mayLoad()) {
2743 for (
const MachineOperand &
Op :
MI.all_defs()) {
2744 for (MCRegUnit RU :
TRI->regunits(
Op.getReg().asMCReg())) {
2755 if (!
ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2757 return HasVMemLoad && UsesVgprLoadedOutside &&
ST->hasVmemWriteVgprInOrder();
2760bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2761 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2763 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2765 if (
auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2766 AA = &AAR->getAAResults();
2768 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2780 if (!SIInsertWaitcnts(MLI, PDT,
AA).
run(MF))
2785 .preserve<AAManager>();
2790 TII = ST->getInstrInfo();
2791 TRI = &
TII->getRegisterInfo();
2797 if (ST->hasExtendedWaitCounts()) {
2798 MaxCounter = NUM_EXTENDED_INST_CNTS;
2799 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2800 WCG = &WCGGFX12Plus;
2802 MaxCounter = NUM_NORMAL_INST_CNTS;
2803 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF, MaxCounter);
2807 for (
auto T : inst_counter_types())
2808 ForceEmitWaitcnt[
T] =
false;
2810 WaitEventMaskForInst = WCG->getWaitEventMask();
2812 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2814 if (
ST->hasExtendedWaitCounts()) {
2831 MachineBasicBlock &EntryBB = MF.
front();
2842 I !=
E && (
I->isPHI() ||
I->isMetaInstruction()); ++
I)
2845 if (
ST->hasExtendedWaitCounts()) {
2848 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2849 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2852 if (!
ST->hasImageInsts() &&
2853 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2857 TII->get(instrsForExtendedCounterTypes[CT]))
2864 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(
this);
2865 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2866 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2873 for (
auto *
MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2876 std::unique_ptr<WaitcntBrackets> Brackets;
2881 for (
auto BII = BlockInfos.
begin(), BIE = BlockInfos.
end(); BII != BIE;
2883 MachineBasicBlock *
MBB = BII->first;
2884 BlockInfo &BI = BII->second;
2890 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2892 *Brackets = *BI.Incoming;
2895 Brackets = std::make_unique<WaitcntBrackets>(
this);
2900 Brackets->~WaitcntBrackets();
2901 new (Brackets.get()) WaitcntBrackets(
this);
2905 Modified |= insertWaitcntInBlock(MF, *
MBB, *Brackets);
2908 if (Brackets->hasPendingEvent()) {
2909 BlockInfo *MoveBracketsToSucc =
nullptr;
2911 auto *SuccBII = BlockInfos.
find(Succ);
2912 BlockInfo &SuccBI = SuccBII->second;
2913 if (!SuccBI.Incoming) {
2914 SuccBI.Dirty =
true;
2915 if (SuccBII <= BII) {
2919 if (!MoveBracketsToSucc) {
2920 MoveBracketsToSucc = &SuccBI;
2922 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2924 }
else if (SuccBI.Incoming->merge(*Brackets)) {
2925 SuccBI.Dirty =
true;
2926 if (SuccBII <= BII) {
2932 if (MoveBracketsToSucc)
2933 MoveBracketsToSucc->Incoming = std::move(Brackets);
2938 if (
ST->hasScalarStores()) {
2939 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2940 bool HaveScalarStores =
false;
2942 for (MachineBasicBlock &
MBB : MF) {
2943 for (MachineInstr &
MI :
MBB) {
2944 if (!HaveScalarStores &&
TII->isScalarStore(
MI))
2945 HaveScalarStores =
true;
2947 if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
2948 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2953 if (HaveScalarStores) {
2962 for (MachineBasicBlock *
MBB : EndPgmBlocks) {
2963 bool SeenDCacheWB =
false;
2967 if (
I->getOpcode() == AMDGPU::S_DCACHE_WB)
2968 SeenDCacheWB =
true;
2969 else if (
TII->isScalarStore(*
I))
2970 SeenDCacheWB =
false;
2973 if ((
I->getOpcode() == AMDGPU::S_ENDPGM ||
2974 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2990 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2992 TII->get(AMDGPU::S_ALLOC_VGPR))
2997 if (!ReleaseVGPRInsts.empty() &&
2998 (MF.getFrameInfo().hasCalls() ||
2999 ST->getOccupancyWithNumVGPRs(
3000 TRI->getNumUsedPhysRegs(*
MRI, AMDGPU::VGPR_32RegClass),
3003 for (MachineInstr *
MI : ReleaseVGPRInsts) {
3004 if (
ST->requiresNopBeforeDeallocVGPRs()) {
3006 TII->get(AMDGPU::S_NOP))
3010 TII->get(AMDGPU::S_SENDMSG))
3016 ReleaseVGPRInsts.clear();
3017 PreheadersToFlush.
clear();
3018 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.
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 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 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 shouldExecute(CounterInfo &Counter)
static bool isCounterSet(CounterInfo &Info)
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.
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 isCBranchVCCZRead(const MachineInstr &MI)
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 isGFX12CacheInvOrWBInst(unsigned Opc)
static bool isSBarrierSCCWrite(unsigned Opcode)
static bool isMIMG(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
static bool isLDSDMA(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...
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.
@ 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...
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
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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
void sort(IteratorTy Start, IteratorTy End)
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...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
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