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) \
129 DECL(EXP_POS_ACCESS) \
130 DECL(EXP_PARAM_ACCESS) \
135#define AMDGPU_EVENT_ENUM(Name) Name,
140#undef AMDGPU_EVENT_ENUM
142#define AMDGPU_EVENT_NAME(Name) #Name,
146#undef AMDGPU_EVENT_NAME
156enum RegisterMapping {
157 SQ_MAX_PGM_VGPRS = 2048,
159 SQ_MAX_PGM_SGPRS = 128,
165 FIRST_LDS_VGPR = SQ_MAX_PGM_VGPRS,
167 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_LDS_VGPRS,
168 NUM_ALL_ALLOCATABLE = NUM_ALL_VGPRS + SQ_MAX_PGM_SGPRS,
170 SCC = NUM_ALL_ALLOCATABLE
191static const unsigned instrsForExtendedCounterTypes[NUM_EXTENDED_INST_CNTS] = {
192 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT, AMDGPU::S_WAIT_EXPCNT,
193 AMDGPU::S_WAIT_STORECNT, AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
194 AMDGPU::S_WAIT_KMCNT, AMDGPU::S_WAIT_XCNT};
202static bool isNormalMode(InstCounterType MaxCounter) {
203 return MaxCounter == NUM_NORMAL_INST_CNTS;
208 assert(updateVMCntOnly(Inst));
210 return VMEM_NOSAMPLER;
224 return VMEM_NOSAMPLER;
236 return Wait.StoreCnt;
238 return Wait.SampleCnt;
251 unsigned &WC = getCounterRef(
Wait,
T);
252 WC = std::min(WC,
Count);
256 getCounterRef(
Wait,
T) = ~0
u;
260 return getCounterRef(
Wait,
T);
264InstCounterType eventCounter(
const unsigned *masks, WaitEventType
E) {
265 for (
auto T : inst_counter_types()) {
266 if (masks[
T] & (1 <<
E))
272class WaitcntBrackets;
280class WaitcntGenerator {
282 const GCNSubtarget *ST =
nullptr;
283 const SIInstrInfo *TII =
nullptr;
284 AMDGPU::IsaVersion IV;
285 InstCounterType MaxCounter;
289 WaitcntGenerator() =
default;
290 WaitcntGenerator(
const MachineFunction &MF, InstCounterType MaxCounter)
291 : ST(&MF.getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
298 bool isOptNone()
const {
return OptNone; }
312 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
313 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
317 bool promoteSoftWaitCnt(MachineInstr *Waitcnt)
const;
321 virtual bool createNewWaitcnt(MachineBasicBlock &
Block,
323 AMDGPU::Waitcnt
Wait) = 0;
327 virtual const unsigned *getWaitEventMask()
const = 0;
331 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const = 0;
333 virtual ~WaitcntGenerator() =
default;
336 static constexpr unsigned
337 eventMask(std::initializer_list<WaitEventType> Events) {
339 for (
auto &
E : Events)
346class WaitcntGeneratorPreGFX12 :
public WaitcntGenerator {
348 WaitcntGeneratorPreGFX12() =
default;
349 WaitcntGeneratorPreGFX12(
const MachineFunction &MF)
350 : WaitcntGenerator(MF, NUM_NORMAL_INST_CNTS) {}
353 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
354 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
357 bool createNewWaitcnt(MachineBasicBlock &
Block,
359 AMDGPU::Waitcnt
Wait)
override;
361 const unsigned *getWaitEventMask()
const override {
364 static const unsigned WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
365 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS,
366 VMEM_BVH_READ_ACCESS}),
367 eventMask({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
368 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
369 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
370 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
376 return WaitEventMaskForInstPreGFX12;
379 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
382class WaitcntGeneratorGFX12Plus :
public WaitcntGenerator {
384 WaitcntGeneratorGFX12Plus() =
default;
385 WaitcntGeneratorGFX12Plus(
const MachineFunction &MF,
386 InstCounterType MaxCounter)
387 : WaitcntGenerator(MF, MaxCounter) {}
390 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
391 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &
Wait,
394 bool createNewWaitcnt(MachineBasicBlock &
Block,
396 AMDGPU::Waitcnt
Wait)
override;
398 const unsigned *getWaitEventMask()
const override {
401 static const unsigned WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
402 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS}),
403 eventMask({LDS_ACCESS, GDS_ACCESS}),
404 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
405 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
406 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
407 eventMask({VMEM_SAMPLER_READ_ACCESS}),
408 eventMask({VMEM_BVH_READ_ACCESS}),
409 eventMask({SMEM_ACCESS, SQ_MESSAGE, SCC_WRITE}),
410 eventMask({VMEM_GROUP, SMEM_GROUP})};
412 return WaitEventMaskForInstGFX12Plus;
415 AMDGPU::Waitcnt getAllZeroWaitcnt(
bool IncludeVSCnt)
const override;
418class SIInsertWaitcnts {
420 const GCNSubtarget *ST;
421 const SIInstrInfo *TII =
nullptr;
422 const SIRegisterInfo *TRI =
nullptr;
423 const MachineRegisterInfo *MRI =
nullptr;
424 InstCounterType SmemAccessCounter;
425 InstCounterType MaxCounter;
426 const unsigned *WaitEventMaskForInst;
429 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
430 DenseMap<MachineBasicBlock *, bool> PreheadersToFlush;
431 MachineLoopInfo *MLI;
432 MachinePostDominatorTree *PDT;
436 std::unique_ptr<WaitcntBrackets> Incoming;
440 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
442 bool ForceEmitWaitcnt[NUM_INST_CNTS];
447 WaitcntGeneratorPreGFX12 WCGPreGFX12;
448 WaitcntGeneratorGFX12Plus WCGGFX12Plus;
450 WaitcntGenerator *WCG =
nullptr;
454 DenseSet<MachineInstr *> ReleaseVGPRInsts;
456 HardwareLimits Limits;
459 SIInsertWaitcnts(MachineLoopInfo *MLI, MachinePostDominatorTree *PDT,
461 : MLI(MLI), PDT(PDT), AA(AA) {
462 (void)ForceExpCounter;
463 (void)ForceLgkmCounter;
464 (void)ForceVMCounter;
467 unsigned getWaitCountMax(InstCounterType
T)
const {
470 return Limits.LoadcntMax;
472 return Limits.DscntMax;
474 return Limits.ExpcntMax;
476 return Limits.StorecntMax;
478 return Limits.SamplecntMax;
480 return Limits.BvhcntMax;
482 return Limits.KmcntMax;
484 return Limits.XcntMax;
491 bool shouldFlushVmCnt(MachineLoop *
ML,
const WaitcntBrackets &Brackets);
492 bool isPreheaderToFlush(MachineBasicBlock &
MBB,
493 const WaitcntBrackets &ScoreBrackets);
494 bool isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const;
495 bool run(MachineFunction &MF);
497 void setForceEmitWaitcnt() {
503 ForceEmitWaitcnt[
EXP_CNT] =
true;
505 ForceEmitWaitcnt[
EXP_CNT] =
false;
510 ForceEmitWaitcnt[DS_CNT] =
true;
511 ForceEmitWaitcnt[KM_CNT] =
true;
513 ForceEmitWaitcnt[DS_CNT] =
false;
514 ForceEmitWaitcnt[KM_CNT] =
false;
519 ForceEmitWaitcnt[LOAD_CNT] =
true;
520 ForceEmitWaitcnt[SAMPLE_CNT] =
true;
521 ForceEmitWaitcnt[BVH_CNT] =
true;
523 ForceEmitWaitcnt[LOAD_CNT] =
false;
524 ForceEmitWaitcnt[SAMPLE_CNT] =
false;
525 ForceEmitWaitcnt[BVH_CNT] =
false;
532 WaitEventType getVmemWaitEventType(
const MachineInstr &Inst)
const {
535 case AMDGPU::GLOBAL_INV:
536 return VMEM_READ_ACCESS;
537 case AMDGPU::GLOBAL_WB:
538 case AMDGPU::GLOBAL_WBINV:
539 return VMEM_WRITE_ACCESS;
545 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
546 VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
557 if (TII->mayAccessScratchThroughFlat(Inst))
558 return SCRATCH_WRITE_ACCESS;
559 return VMEM_WRITE_ACCESS;
562 return VMEM_READ_ACCESS;
563 return VmemReadMapping[getVmemType(Inst)];
566 bool isVmemAccess(
const MachineInstr &
MI)
const;
567 bool generateWaitcntInstBefore(MachineInstr &
MI,
568 WaitcntBrackets &ScoreBrackets,
569 MachineInstr *OldWaitcntInstr,
571 bool generateWaitcnt(AMDGPU::Waitcnt
Wait,
573 MachineBasicBlock &
Block, WaitcntBrackets &ScoreBrackets,
574 MachineInstr *OldWaitcntInstr);
575 void updateEventWaitcntAfter(MachineInstr &Inst,
576 WaitcntBrackets *ScoreBrackets);
578 MachineBasicBlock *
Block)
const;
579 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &
Block,
580 WaitcntBrackets &ScoreBrackets);
581 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &
Block,
582 WaitcntBrackets &ScoreBrackets);
593class WaitcntBrackets {
595 WaitcntBrackets(
const SIInsertWaitcnts *Context) : Context(Context) {}
597 bool isSmemCounter(InstCounterType
T)
const {
598 return T == Context->SmemAccessCounter ||
T == X_CNT;
601 unsigned getSgprScoresIdx(InstCounterType
T)
const {
602 assert(isSmemCounter(
T) &&
"Invalid SMEM counter");
603 return T == X_CNT ? 1 : 0;
606 unsigned getScoreLB(InstCounterType
T)
const {
611 unsigned getScoreUB(InstCounterType
T)
const {
616 unsigned getScoreRange(InstCounterType
T)
const {
617 return getScoreUB(
T) - getScoreLB(
T);
620 unsigned getRegScore(
int GprNo, InstCounterType
T)
const {
621 if (GprNo < NUM_ALL_VGPRS)
622 return VgprScores[
T][GprNo];
624 if (GprNo < NUM_ALL_ALLOCATABLE)
625 return SgprScores[getSgprScoresIdx(
T)][GprNo - NUM_ALL_VGPRS];
633 RegInterval getRegInterval(
const MachineInstr *
MI,
634 const MachineOperand &
Op)
const;
636 bool counterOutOfOrder(InstCounterType
T)
const;
637 void simplifyWaitcnt(AMDGPU::Waitcnt &
Wait);
638 void simplifyWaitcnt(InstCounterType
T,
unsigned &
Count)
const;
639 bool hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait);
640 bool canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait);
641 void simplifyXcnt(AMDGPU::Waitcnt &CheckWait, AMDGPU::Waitcnt &UpdateWait);
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);
649 void tryClearSCCWriteEvent(MachineInstr *Inst);
651 void applyWaitcnt(
const AMDGPU::Waitcnt &
Wait);
652 void applyWaitcnt(InstCounterType
T,
unsigned Count);
653 void updateByEvent(WaitEventType
E, MachineInstr &
MI);
655 unsigned hasPendingEvent()
const {
return PendingEvents; }
656 unsigned hasPendingEvent(WaitEventType
E)
const {
657 return PendingEvents & (1 <<
E);
659 unsigned hasPendingEvent(InstCounterType
T)
const {
660 unsigned HasPending = PendingEvents & Context->WaitEventMaskForInst[
T];
661 assert((HasPending != 0) == (getScoreRange(
T) != 0));
665 bool hasMixedPendingEvents(InstCounterType
T)
const {
666 unsigned Events = hasPendingEvent(
T);
668 return Events & (Events - 1);
671 bool hasPendingFlat()
const {
672 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
673 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
674 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
675 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
678 void setPendingFlat() {
679 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
680 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
683 bool hasPendingGDS()
const {
684 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
687 unsigned getPendingGDSWait()
const {
688 return std::min(getScoreUB(DS_CNT) - LastGDS,
689 Context->getWaitCountMax(DS_CNT) - 1);
692 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
696 bool hasOtherPendingVmemTypes(RegInterval
Interval, VmemType V)
const {
698 assert(RegNo < NUM_ALL_VGPRS);
699 if (VgprVmemTypes[RegNo] & ~(1 << V))
705 void clearVgprVmemTypes(RegInterval
Interval) {
707 assert(RegNo < NUM_ALL_VGPRS);
708 VgprVmemTypes[RegNo] = 0;
712 void setStateOnFunctionEntryOrReturn() {
713 setScoreUB(STORE_CNT,
714 getScoreUB(STORE_CNT) + Context->getWaitCountMax(STORE_CNT));
715 PendingEvents |= Context->WaitEventMaskForInst[STORE_CNT];
718 ArrayRef<const MachineInstr *> getLDSDMAStores()
const {
722 bool hasPointSampleAccel(
const MachineInstr &
MI)
const;
723 bool hasPointSamplePendingVmemTypes(
const MachineInstr &
MI,
726 void print(raw_ostream &)
const;
736 static bool mergeScore(
const MergeInfo &M,
unsigned &Score,
737 unsigned OtherScore);
739 void setScoreLB(InstCounterType
T,
unsigned Val) {
744 void setScoreUB(InstCounterType
T,
unsigned Val) {
751 if (getScoreRange(EXP_CNT) > Context->getWaitCountMax(EXP_CNT))
752 ScoreLBs[
EXP_CNT] = ScoreUBs[
EXP_CNT] - Context->getWaitCountMax(EXP_CNT);
755 void setRegScore(
int GprNo, InstCounterType
T,
unsigned Val) {
756 setScoreByInterval({GprNo, GprNo + 1},
T, Val);
759 void setScoreByInterval(RegInterval
Interval, InstCounterType CntTy,
762 void setScoreByOperand(
const MachineInstr *
MI,
const MachineOperand &
Op,
763 InstCounterType CntTy,
unsigned Val);
765 const SIInsertWaitcnts *Context;
767 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
768 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
769 unsigned PendingEvents = 0;
771 unsigned LastFlat[NUM_INST_CNTS] = {0};
773 unsigned LastGDS = 0;
778 unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}};
783 unsigned SgprScores[2][SQ_MAX_PGM_SGPRS] = {{0}};
785 unsigned SCCScore = 0;
787 const MachineInstr *PendingSCCWrite =
nullptr;
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,
821 if (
Op.getReg() == AMDGPU::SCC)
825 const MachineRegisterInfo *
MRI =
Context->MRI;
827 if (!
TRI->isInAllocatableClass(
Op.getReg()))
837 unsigned RegIdx =
TRI->getHWRegIndex(MCReg);
839 const TargetRegisterClass *RC =
TRI->getPhysRegBaseClass(
Op.getReg());
840 unsigned Size =
TRI->getRegSizeInBits(*RC);
843 if (
TRI->isVectorRegister(*
MRI,
Op.getReg())) {
848 Result.first += AGPR_OFFSET;
853 if (
Size == 16 &&
Context->ST->hasD16Writes32BitVgpr()) {
861 }
else if (
TRI->isSGPRReg(*
MRI,
Op.getReg()) && RegIdx < SQ_MAX_PGM_SGPRS) {
864 Result.first = RegIdx + NUM_ALL_VGPRS;
873void WaitcntBrackets::setScoreByInterval(RegInterval
Interval,
874 InstCounterType CntTy,
877 if (RegNo < NUM_ALL_VGPRS) {
878 VgprUB = std::max(VgprUB, RegNo);
879 VgprScores[CntTy][RegNo] = Score;
880 }
else if (RegNo < NUM_ALL_ALLOCATABLE) {
881 SgprUB = std::max(SgprUB, RegNo - NUM_ALL_VGPRS);
882 SgprScores[getSgprScoresIdx(CntTy)][RegNo - NUM_ALL_VGPRS] = Score;
890void WaitcntBrackets::setScoreByOperand(
const MachineInstr *
MI,
891 const MachineOperand &
Op,
892 InstCounterType CntTy,
unsigned Score) {
894 setScoreByInterval(
Interval, CntTy, Score);
902bool WaitcntBrackets::hasPointSampleAccel(
const MachineInstr &
MI)
const {
907 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
917bool WaitcntBrackets::hasPointSamplePendingVmemTypes(
918 const MachineInstr &
MI, RegInterval
Interval)
const {
919 if (!hasPointSampleAccel(
MI))
922 return hasOtherPendingVmemTypes(
Interval, VMEM_NOSAMPLER);
925void WaitcntBrackets::updateByEvent(WaitEventType
E, MachineInstr &Inst) {
926 InstCounterType
T = eventCounter(
Context->WaitEventMaskForInst,
E);
928 unsigned UB = getScoreUB(
T);
929 unsigned CurrScore = UB + 1;
935 PendingEvents |= 1 <<
E;
936 setScoreUB(
T, CurrScore);
939 const MachineRegisterInfo *
MRI =
Context->MRI;
948 if (
const auto *AddrOp =
TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
949 setScoreByOperand(&Inst, *AddrOp, EXP_CNT, CurrScore);
952 if (
const auto *Data0 =
953 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
954 setScoreByOperand(&Inst, *Data0, EXP_CNT, CurrScore);
955 if (
const auto *Data1 =
956 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
957 setScoreByOperand(&Inst, *Data1, EXP_CNT, CurrScore);
960 Inst.
getOpcode() != AMDGPU::DS_CONSUME &&
961 Inst.
getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
962 for (
const MachineOperand &
Op : Inst.
all_uses()) {
963 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
964 setScoreByOperand(&Inst,
Op, EXP_CNT, CurrScore);
967 }
else if (
TII->isFLAT(Inst)) {
969 setScoreByOperand(&Inst,
970 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
973 setScoreByOperand(&Inst,
974 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
977 }
else if (
TII->isMIMG(Inst)) {
979 setScoreByOperand(&Inst, Inst.
getOperand(0), EXP_CNT, CurrScore);
981 setScoreByOperand(&Inst,
982 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
985 }
else if (
TII->isMTBUF(Inst)) {
987 setScoreByOperand(&Inst, Inst.
getOperand(0), EXP_CNT, CurrScore);
988 }
else if (
TII->isMUBUF(Inst)) {
990 setScoreByOperand(&Inst, Inst.
getOperand(0), EXP_CNT, CurrScore);
992 setScoreByOperand(&Inst,
993 *
TII->getNamedOperand(Inst, AMDGPU::OpName::data),
996 }
else if (
TII->isLDSDIR(Inst)) {
998 setScoreByOperand(&Inst,
999 *
TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
1000 EXP_CNT, CurrScore);
1002 if (
TII->isEXP(Inst)) {
1007 for (MachineOperand &DefMO : Inst.
all_defs()) {
1008 if (
TRI->isVGPR(*
MRI, DefMO.getReg())) {
1009 setScoreByOperand(&Inst, DefMO, EXP_CNT, CurrScore);
1013 for (
const MachineOperand &
Op : Inst.
all_uses()) {
1014 if (
TRI->isVectorRegister(*
MRI,
Op.getReg()))
1015 setScoreByOperand(&Inst,
Op, EXP_CNT, CurrScore);
1018 }
else if (
T == X_CNT) {
1019 WaitEventType OtherEvent =
E == SMEM_GROUP ? VMEM_GROUP : SMEM_GROUP;
1020 if (PendingEvents & (1 << OtherEvent)) {
1025 setScoreLB(
T, getScoreUB(
T) - 1);
1026 PendingEvents &= ~(1 << OtherEvent);
1028 for (
const MachineOperand &
Op : Inst.
all_uses())
1029 setScoreByOperand(&Inst,
Op,
T, CurrScore);
1040 for (
const MachineOperand &
Op : Inst.
defs()) {
1041 RegInterval
Interval = getRegInterval(&Inst,
Op);
1042 if (
T == LOAD_CNT ||
T == SAMPLE_CNT ||
T == BVH_CNT) {
1043 if (
Interval.first >= NUM_ALL_VGPRS)
1045 if (updateVMCntOnly(Inst)) {
1050 VmemType
V = getVmemType(Inst);
1051 unsigned char TypesMask = 1 <<
V;
1054 if (hasPointSampleAccel(Inst))
1055 TypesMask |= 1 << VMEM_NOSAMPLER;
1057 VgprVmemTypes[RegNo] |= TypesMask;
1060 setScoreByInterval(
Interval,
T, CurrScore);
1063 (
TII->isDS(Inst) ||
TII->mayWriteLDSThroughDMA(Inst))) {
1068 if (!MemOp->isStore() ||
1073 auto AAI = MemOp->getAAInfo();
1081 if (!AAI || !AAI.Scope)
1083 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E && !Slot; ++
I) {
1084 for (
const auto *MemOp : LDSDMAStores[
I]->memoperands()) {
1085 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1091 if (Slot || LDSDMAStores.size() == NUM_LDS_VGPRS - 1)
1093 LDSDMAStores.push_back(&Inst);
1094 Slot = LDSDMAStores.size();
1097 setRegScore(FIRST_LDS_VGPR + Slot,
T, CurrScore);
1099 setRegScore(FIRST_LDS_VGPR,
T, CurrScore);
1103 setRegScore(SCC,
T, CurrScore);
1104 PendingSCCWrite = &Inst;
1109void WaitcntBrackets::print(raw_ostream &OS)
const {
1113 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
1114 unsigned SR = getScoreRange(
T);
1118 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"LOAD" :
"VM") <<
"_CNT("
1122 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"DS" :
"LGKM") <<
"_CNT("
1126 OS <<
" EXP_CNT(" << SR <<
"): ";
1129 OS <<
" " << (
ST->hasExtendedWaitCounts() ?
"STORE" :
"VS") <<
"_CNT("
1133 OS <<
" SAMPLE_CNT(" << SR <<
"): ";
1136 OS <<
" BVH_CNT(" << SR <<
"): ";
1139 OS <<
" KM_CNT(" << SR <<
"): ";
1142 OS <<
" X_CNT(" << SR <<
"): ";
1145 OS <<
" UNKNOWN(" << SR <<
"): ";
1151 unsigned LB = getScoreLB(
T);
1153 for (
int J = 0; J <= VgprUB; J++) {
1154 unsigned RegScore = getRegScore(J,
T);
1157 unsigned RelScore = RegScore - LB - 1;
1158 if (J < FIRST_LDS_VGPR) {
1159 OS << RelScore <<
":v" << J <<
" ";
1161 OS << RelScore <<
":ds ";
1165 if (isSmemCounter(
T)) {
1166 for (
int J = 0; J <= SgprUB; J++) {
1167 unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS,
T);
1170 unsigned RelScore = RegScore - LB - 1;
1171 OS << RelScore <<
":s" << J <<
" ";
1174 if (
T == KM_CNT && SCCScore > 0)
1175 OS << SCCScore <<
":scc ";
1180 OS <<
"Pending Events: ";
1181 if (hasPendingEvent()) {
1183 for (
unsigned I = 0;
I != NUM_WAIT_EVENTS; ++
I) {
1184 if (hasPendingEvent((WaitEventType)
I)) {
1185 OS <<
LS << WaitEventTypeName[
I];
1198void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &
Wait) {
1199 simplifyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1200 simplifyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1201 simplifyWaitcnt(DS_CNT,
Wait.DsCnt);
1202 simplifyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1203 simplifyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1204 simplifyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1205 simplifyWaitcnt(KM_CNT,
Wait.KmCnt);
1209void WaitcntBrackets::simplifyWaitcnt(InstCounterType
T,
1210 unsigned &
Count)
const {
1214 if (
Count >= getScoreRange(
T))
1218void WaitcntBrackets::determineWait(InstCounterType
T, RegInterval
Interval,
1219 AMDGPU::Waitcnt &
Wait)
const {
1220 const unsigned LB = getScoreLB(
T);
1221 const unsigned UB = getScoreUB(
T);
1223 unsigned ScoreToWait = getRegScore(RegNo,
T);
1227 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1228 if ((
T == LOAD_CNT ||
T == DS_CNT) && hasPendingFlat() &&
1229 !
Context->ST->hasFlatLgkmVMemCountInOrder()) {
1233 addWait(
Wait,
T, 0);
1234 }
else if (counterOutOfOrder(
T)) {
1238 addWait(
Wait,
T, 0);
1242 unsigned NeededWait =
1243 std::min(UB - ScoreToWait,
Context->getWaitCountMax(
T) - 1);
1244 addWait(
Wait,
T, NeededWait);
1250void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1253 if (PendingSCCWrite &&
1254 PendingSCCWrite->
getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1256 unsigned SCC_WRITE_PendingEvent = 1 << SCC_WRITE;
1258 if ((PendingEvents &
Context->WaitEventMaskForInst[KM_CNT]) ==
1259 SCC_WRITE_PendingEvent) {
1260 setScoreLB(KM_CNT, getScoreUB(KM_CNT));
1263 PendingEvents &= ~SCC_WRITE_PendingEvent;
1264 PendingSCCWrite =
nullptr;
1268void WaitcntBrackets::applyWaitcnt(
const AMDGPU::Waitcnt &
Wait) {
1269 applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1270 applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1271 applyWaitcnt(DS_CNT,
Wait.DsCnt);
1272 applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1273 applyWaitcnt(SAMPLE_CNT,
Wait.SampleCnt);
1274 applyWaitcnt(BVH_CNT,
Wait.BvhCnt);
1275 applyWaitcnt(KM_CNT,
Wait.KmCnt);
1276 applyWaitcnt(X_CNT,
Wait.XCnt);
1279void WaitcntBrackets::applyWaitcnt(InstCounterType
T,
unsigned Count) {
1280 const unsigned UB = getScoreUB(
T);
1284 if (counterOutOfOrder(
T))
1286 setScoreLB(
T, std::max(getScoreLB(
T), UB -
Count));
1289 PendingEvents &= ~Context->WaitEventMaskForInst[
T];
1293bool WaitcntBrackets::hasRedundantXCntWithKmCnt(
const AMDGPU::Waitcnt &
Wait) {
1297 return Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP);
1300bool WaitcntBrackets::canOptimizeXCntWithLoadCnt(
const AMDGPU::Waitcnt &
Wait) {
1304 return Wait.LoadCnt != ~0
u && hasPendingEvent(VMEM_GROUP) &&
1305 !hasPendingEvent(STORE_CNT);
1308void WaitcntBrackets::simplifyXcnt(AMDGPU::Waitcnt &CheckWait,
1309 AMDGPU::Waitcnt &UpdateWait) {
1315 if (hasRedundantXCntWithKmCnt(CheckWait)) {
1316 if (!hasMixedPendingEvents(X_CNT)) {
1317 applyWaitcnt(X_CNT, 0);
1319 PendingEvents &= ~(1 << SMEM_GROUP);
1321 }
else if (canOptimizeXCntWithLoadCnt(CheckWait)) {
1322 if (!hasMixedPendingEvents(X_CNT)) {
1323 applyWaitcnt(X_CNT, std::min(CheckWait.
XCnt, CheckWait.
LoadCnt));
1324 }
else if (CheckWait.
LoadCnt == 0) {
1325 PendingEvents &= ~(1 << VMEM_GROUP);
1328 simplifyWaitcnt(X_CNT, UpdateWait.
XCnt);
1333bool WaitcntBrackets::counterOutOfOrder(InstCounterType
T)
const {
1335 if ((
T ==
Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1336 (
T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1338 return hasMixedPendingEvents(
T);
1348char SIInsertWaitcntsLegacy::
ID = 0;
1353 return new SIInsertWaitcntsLegacy();
1358 int OpIdx = AMDGPU::getNamedOperandIdx(
MI.getOpcode(),
OpName);
1363 if (NewEnc == MO.
getImm())
1374 case AMDGPU::S_WAIT_LOADCNT:
1376 case AMDGPU::S_WAIT_EXPCNT:
1378 case AMDGPU::S_WAIT_STORECNT:
1380 case AMDGPU::S_WAIT_SAMPLECNT:
1382 case AMDGPU::S_WAIT_BVHCNT:
1384 case AMDGPU::S_WAIT_DSCNT:
1386 case AMDGPU::S_WAIT_KMCNT:
1388 case AMDGPU::S_WAIT_XCNT:
1395bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt)
const {
1409bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1410 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1413 assert(isNormalMode(MaxCounter));
1416 MachineInstr *WaitcntInstr =
nullptr;
1417 MachineInstr *WaitcntVsCntInstr =
nullptr;
1420 dbgs() <<
"PreGFX12::applyPreexistingWaitcnt at: ";
1422 dbgs() <<
"end of block\n";
1430 if (
II.isMetaInstruction()) {
1436 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1440 if (Opcode == AMDGPU::S_WAITCNT) {
1441 unsigned IEnc =
II.getOperand(0).getImm();
1444 ScoreBrackets.simplifyWaitcnt(OldWait);
1448 if (WaitcntInstr || (!
Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1449 II.eraseFromParent();
1453 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1456 <<
"Before: " <<
Wait.LoadCnt <<
'\n';);
1457 ScoreBrackets.determineWait(LOAD_CNT, FIRST_LDS_VGPR,
Wait);
1466 II.eraseFromParent();
1468 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1469 assert(
II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1472 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1474 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1475 Wait.StoreCnt = std::min(
Wait.StoreCnt, OldVSCnt);
1477 if (WaitcntVsCntInstr || (!
Wait.hasWaitStoreCnt() && TrySimplify)) {
1478 II.eraseFromParent();
1481 WaitcntVsCntInstr = &
II;
1488 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1490 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1491 ScoreBrackets.applyWaitcnt(EXP_CNT,
Wait.ExpCnt);
1492 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1499 <<
"applied pre-existing waitcnt\n"
1500 <<
"New Instr at block end: " << *WaitcntInstr <<
'\n'
1501 :
dbgs() <<
"applied pre-existing waitcnt\n"
1502 <<
"Old Instr: " << *It
1503 <<
"New Instr: " << *WaitcntInstr <<
'\n');
1506 if (WaitcntVsCntInstr) {
1508 AMDGPU::OpName::simm16,
Wait.StoreCnt);
1509 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1511 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1512 Wait.StoreCnt = ~0
u;
1515 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1516 <<
"New Instr at block end: " << *WaitcntVsCntInstr
1518 :
dbgs() <<
"applied pre-existing waitcnt\n"
1519 <<
"Old Instr: " << *It
1520 <<
"New Instr: " << *WaitcntVsCntInstr <<
'\n');
1528bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1530 AMDGPU::Waitcnt
Wait) {
1532 assert(isNormalMode(MaxCounter));
1539 if (
Wait.hasWaitExceptStoreCnt()) {
1541 [[maybe_unused]]
auto SWaitInst =
1546 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1547 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1550 if (
Wait.hasWaitStoreCnt()) {
1553 [[maybe_unused]]
auto SWaitInst =
1560 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1561 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1568WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1569 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt &&
ST->hasVscnt() ? 0 : ~0u);
1573WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(
bool IncludeVSCnt)
const {
1574 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1582bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1583 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1586 assert(!isNormalMode(MaxCounter));
1589 MachineInstr *CombinedLoadDsCntInstr =
nullptr;
1590 MachineInstr *CombinedStoreDsCntInstr =
nullptr;
1591 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1594 dbgs() <<
"GFX12Plus::applyPreexistingWaitcnt at: ";
1596 dbgs() <<
"end of block\n";
1604 if (
II.isMetaInstruction()) {
1609 MachineInstr **UpdatableInstr;
1615 bool TrySimplify = Opcode !=
II.getOpcode() && !OptNone;
1619 if (Opcode == AMDGPU::S_WAITCNT)
1622 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1624 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1627 ScoreBrackets.simplifyWaitcnt(OldWait);
1629 UpdatableInstr = &CombinedLoadDsCntInstr;
1630 }
else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1632 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1635 ScoreBrackets.simplifyWaitcnt(OldWait);
1637 UpdatableInstr = &CombinedStoreDsCntInstr;
1638 }
else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1641 II.eraseFromParent();
1647 TII->getNamedOperand(
II, AMDGPU::OpName::simm16)->getImm();
1649 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1650 addWait(
Wait, CT.value(), OldCnt);
1651 UpdatableInstr = &WaitInstrs[CT.value()];
1655 if (!*UpdatableInstr) {
1656 *UpdatableInstr = &
II;
1658 II.eraseFromParent();
1664 AMDGPU::Waitcnt PreCombine =
Wait;
1665 if (CombinedLoadDsCntInstr) {
1673 if (
Wait.LoadCnt != ~0u &&
Wait.DsCnt != ~0u) {
1676 AMDGPU::OpName::simm16, NewEnc);
1677 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1678 ScoreBrackets.applyWaitcnt(LOAD_CNT,
Wait.LoadCnt);
1679 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1684 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1685 <<
"New Instr at block end: "
1686 << *CombinedLoadDsCntInstr <<
'\n'
1687 :
dbgs() <<
"applied pre-existing waitcnt\n"
1688 <<
"Old Instr: " << *It <<
"New Instr: "
1689 << *CombinedLoadDsCntInstr <<
'\n');
1696 if (CombinedStoreDsCntInstr) {
1698 if (
Wait.StoreCnt != ~0u &&
Wait.DsCnt != ~0u) {
1701 AMDGPU::OpName::simm16, NewEnc);
1702 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1703 ScoreBrackets.applyWaitcnt(STORE_CNT,
Wait.StoreCnt);
1704 ScoreBrackets.applyWaitcnt(DS_CNT,
Wait.DsCnt);
1705 Wait.StoreCnt = ~0
u;
1709 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1710 <<
"New Instr at block end: "
1711 << *CombinedStoreDsCntInstr <<
'\n'
1712 :
dbgs() <<
"applied pre-existing waitcnt\n"
1713 <<
"Old Instr: " << *It <<
"New Instr: "
1714 << *CombinedStoreDsCntInstr <<
'\n');
1727 if (
Wait.DsCnt != ~0u) {
1736 if (
Wait.LoadCnt != ~0u) {
1737 WaitsToErase.
push_back(&WaitInstrs[LOAD_CNT]);
1738 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1739 }
else if (
Wait.StoreCnt != ~0u) {
1740 WaitsToErase.
push_back(&WaitInstrs[STORE_CNT]);
1741 WaitsToErase.
push_back(&WaitInstrs[DS_CNT]);
1744 for (MachineInstr **WI : WaitsToErase) {
1748 (*WI)->eraseFromParent();
1754 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1755 if ((CT == KM_CNT && ScoreBrackets.hasRedundantXCntWithKmCnt(PreCombine)) ||
1757 ScoreBrackets.canOptimizeXCntWithLoadCnt(PreCombine))) {
1760 ScoreBrackets.simplifyXcnt(PreCombine,
Wait);
1762 if (!WaitInstrs[CT])
1765 unsigned NewCnt = getWait(
Wait, CT);
1766 if (NewCnt != ~0u) {
1768 AMDGPU::OpName::simm16, NewCnt);
1769 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1771 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1772 setNoWait(
Wait, CT);
1775 ?
dbgs() <<
"applied pre-existing waitcnt\n"
1776 <<
"New Instr at block end: " << *WaitInstrs[CT]
1778 :
dbgs() <<
"applied pre-existing waitcnt\n"
1779 <<
"Old Instr: " << *It
1780 <<
"New Instr: " << *WaitInstrs[CT] <<
'\n');
1791bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1793 AMDGPU::Waitcnt
Wait) {
1795 assert(!isNormalMode(MaxCounter));
1801 if (
Wait.DsCnt != ~0u) {
1802 MachineInstr *SWaitInst =
nullptr;
1804 if (
Wait.LoadCnt != ~0u) {
1812 }
else if (
Wait.StoreCnt != ~0u) {
1819 Wait.StoreCnt = ~0
u;
1827 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1828 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1835 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1840 [[maybe_unused]]
auto SWaitInst =
1847 if (It !=
Block.instr_end())
dbgs() <<
"Old Instr: " << *It;
1848 dbgs() <<
"New Instr: " << *SWaitInst <<
'\n');
1879bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &
MI,
1880 WaitcntBrackets &ScoreBrackets,
1881 MachineInstr *OldWaitcntInstr,
1883 setForceEmitWaitcnt();
1887 AMDGPU::Waitcnt
Wait;
1888 const unsigned Opc =
MI.getOpcode();
1894 if (
Opc == AMDGPU::BUFFER_WBINVL1 ||
Opc == AMDGPU::BUFFER_WBINVL1_SC ||
1895 Opc == AMDGPU::BUFFER_WBINVL1_VOL ||
Opc == AMDGPU::BUFFER_GL0_INV ||
1896 Opc == AMDGPU::BUFFER_GL1_INV) {
1903 if (
Opc == AMDGPU::SI_RETURN_TO_EPILOG ||
Opc == AMDGPU::SI_RETURN ||
1904 Opc == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1905 Opc == AMDGPU::S_SETPC_B64_return ||
1907 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
false));
1917 else if (
Opc == AMDGPU::S_ENDPGM ||
Opc == AMDGPU::S_ENDPGM_SAVED) {
1918 if (!WCG->isOptNone() &&
1919 (
MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1920 (
ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1921 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1922 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1926 else if ((
Opc == AMDGPU::S_SENDMSG ||
Opc == AMDGPU::S_SENDMSGHALT) &&
1927 ST->hasLegacyGeometry() &&
1938 if (
MI.modifiesRegister(AMDGPU::EXEC,
TRI)) {
1941 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1942 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1943 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1944 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1951 if (
TII->isAlwaysGDS(
Opc) && ScoreBrackets.hasPendingGDS())
1952 addWait(
Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
1958 Wait = AMDGPU::Waitcnt();
1960 const auto &CallAddrOp = *
TII->getNamedOperand(
MI, AMDGPU::OpName::src0);
1961 if (CallAddrOp.isReg()) {
1962 RegInterval CallAddrOpInterval =
1963 ScoreBrackets.getRegInterval(&
MI, CallAddrOp);
1965 ScoreBrackets.determineWait(SmemAccessCounter, CallAddrOpInterval,
1968 if (
const auto *RtnAddrOp =
1969 TII->getNamedOperand(
MI, AMDGPU::OpName::dst)) {
1970 RegInterval RtnAddrOpInterval =
1971 ScoreBrackets.getRegInterval(&
MI, *RtnAddrOp);
1973 ScoreBrackets.determineWait(SmemAccessCounter, RtnAddrOpInterval,
1977 }
else if (
Opc == AMDGPU::S_BARRIER_WAIT) {
1978 ScoreBrackets.tryClearSCCWriteEvent(&
MI);
1994 for (
const MachineMemOperand *Memop :
MI.memoperands()) {
1995 const Value *Ptr = Memop->getValue();
1996 if (Memop->isStore()) {
1997 if (
auto It = SLoadAddresses.
find(Ptr); It != SLoadAddresses.
end()) {
1998 addWait(
Wait, SmemAccessCounter, 0);
2000 SLoadAddresses.
erase(It);
2003 unsigned AS = Memop->getAddrSpace();
2007 if (
TII->mayWriteLDSThroughDMA(
MI))
2011 unsigned RegNo = FIRST_LDS_VGPR;
2012 if (Ptr && Memop->getAAInfo()) {
2013 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
2014 for (
unsigned I = 0,
E = LDSDMAStores.size();
I !=
E; ++
I) {
2015 if (
MI.mayAlias(AA, *LDSDMAStores[
I],
true))
2016 ScoreBrackets.determineWait(LOAD_CNT, RegNo +
I + 1,
Wait);
2019 ScoreBrackets.determineWait(LOAD_CNT, RegNo,
Wait);
2021 if (Memop->isStore()) {
2022 ScoreBrackets.determineWait(EXP_CNT, RegNo,
Wait);
2027 for (
const MachineOperand &
Op :
MI.operands()) {
2032 if (
Op.isTied() &&
Op.isUse() &&
TII->doesNotReadTiedSource(
MI))
2035 RegInterval
Interval = ScoreBrackets.getRegInterval(&
MI,
Op);
2037 const bool IsVGPR =
TRI->isVectorRegister(*
MRI,
Op.getReg());
2044 if (
Op.isImplicit() &&
MI.mayLoadOrStore())
2053 if (
Op.isUse() || !updateVMCntOnly(
MI) ||
2054 ScoreBrackets.hasOtherPendingVmemTypes(
Interval,
2056 ScoreBrackets.hasPointSamplePendingVmemTypes(
MI,
Interval) ||
2057 !
ST->hasVmemWriteVgprInOrder()) {
2059 ScoreBrackets.determineWait(SAMPLE_CNT,
Interval,
Wait);
2061 ScoreBrackets.clearVgprVmemTypes(
Interval);
2064 if (
Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2068 }
else if (
Op.getReg() == AMDGPU::SCC) {
2071 ScoreBrackets.determineWait(SmemAccessCounter,
Interval,
Wait);
2074 if (
ST->hasWaitXCnt() &&
Op.isDef())
2092 if (
Opc == AMDGPU::S_BARRIER && !
ST->hasAutoWaitcntBeforeBarrier() &&
2093 !
ST->supportsBackOffBarrier()) {
2094 Wait =
Wait.combined(WCG->getAllZeroWaitcnt(
true));
2101 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2106 ScoreBrackets.simplifyWaitcnt(
Wait);
2111 if (
Wait.XCnt != ~0u && isVmemAccess(
MI)) {
2112 ScoreBrackets.applyWaitcnt(X_CNT,
Wait.XCnt);
2119 Wait = WCG->getAllZeroWaitcnt(
false);
2121 if (ForceEmitWaitcnt[LOAD_CNT])
2123 if (ForceEmitWaitcnt[EXP_CNT])
2125 if (ForceEmitWaitcnt[DS_CNT])
2127 if (ForceEmitWaitcnt[SAMPLE_CNT])
2129 if (ForceEmitWaitcnt[BVH_CNT])
2131 if (ForceEmitWaitcnt[KM_CNT])
2133 if (ForceEmitWaitcnt[X_CNT])
2137 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2139 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2141 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2148 return generateWaitcnt(
Wait,
MI.getIterator(), *
MI.getParent(), ScoreBrackets,
2152bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt
Wait,
2154 MachineBasicBlock &
Block,
2155 WaitcntBrackets &ScoreBrackets,
2156 MachineInstr *OldWaitcntInstr) {
2159 if (OldWaitcntInstr)
2163 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr,
Wait, It);
2167 ScoreBrackets.applyWaitcnt(
Wait);
2170 if (
Wait.ExpCnt != ~0u && It !=
Block.instr_end() &&
2172 MachineOperand *WaitExp =
2173 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2181 <<
"Update Instr: " << *It);
2184 if (WCG->createNewWaitcnt(
Block, It,
Wait))
2190bool SIInsertWaitcnts::isVmemAccess(
const MachineInstr &
MI)
const {
2191 return (
TII->isFLAT(
MI) &&
TII->mayAccessVMEMThroughFlat(
MI)) ||
2198 MachineBasicBlock *
Block)
const {
2199 auto BlockEnd =
Block->getParent()->end();
2200 auto BlockIter =
Block->getIterator();
2204 if (++BlockIter != BlockEnd) {
2205 It = BlockIter->instr_begin();
2212 if (!It->isMetaInstruction())
2220 return It->getOpcode() == AMDGPU::S_ENDPGM;
2224bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2225 MachineBasicBlock &
Block,
2226 WaitcntBrackets &ScoreBrackets) {
2227 AMDGPU::Waitcnt
Wait;
2228 bool NeedsEndPGMCheck =
false;
2236 NeedsEndPGMCheck =
true;
2239 ScoreBrackets.simplifyWaitcnt(
Wait);
2242 bool Result = generateWaitcnt(
Wait, SuccessorIt,
Block, ScoreBrackets,
2245 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &
Block)) {
2253void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2254 WaitcntBrackets *ScoreBrackets) {
2262 bool IsVMEMAccess =
false;
2263 bool IsSMEMAccess =
false;
2264 if (
TII->isDS(Inst) &&
TII->usesLGKM_CNT(Inst)) {
2266 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2267 ScoreBrackets->updateByEvent(GDS_ACCESS, Inst);
2268 ScoreBrackets->updateByEvent(GDS_GPR_LOCK, Inst);
2269 ScoreBrackets->setPendingGDS();
2271 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2273 }
else if (
TII->isFLAT(Inst)) {
2275 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2281 int FlatASCount = 0;
2283 if (
TII->mayAccessVMEMThroughFlat(Inst)) {
2285 IsVMEMAccess =
true;
2286 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2289 if (
TII->mayAccessLDSThroughFlat(Inst)) {
2291 ScoreBrackets->updateByEvent(LDS_ACCESS, Inst);
2297 if (FlatASCount > 1)
2298 ScoreBrackets->setPendingFlat();
2301 IsVMEMAccess =
true;
2302 ScoreBrackets->updateByEvent(getVmemWaitEventType(Inst), Inst);
2304 if (
ST->vmemWriteNeedsExpWaitcnt() &&
2306 ScoreBrackets->updateByEvent(VMW_GPR_LOCK, Inst);
2308 }
else if (
TII->isSMRD(Inst)) {
2309 IsSMEMAccess =
true;
2310 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2311 }
else if (Inst.
isCall()) {
2314 ScoreBrackets->applyWaitcnt(
2315 WCG->getAllZeroWaitcnt(
false));
2316 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2319 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2322 ScoreBrackets->updateByEvent(EXP_LDS_ACCESS, Inst);
2323 }
else if (
TII->isVINTERP(Inst)) {
2324 int64_t
Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2325 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2327 unsigned Imm =
TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2329 ScoreBrackets->updateByEvent(EXP_PARAM_ACCESS, Inst);
2331 ScoreBrackets->updateByEvent(EXP_POS_ACCESS, Inst);
2333 ScoreBrackets->updateByEvent(EXP_GPR_LOCK, Inst);
2335 ScoreBrackets->updateByEvent(SCC_WRITE, Inst);
2338 case AMDGPU::S_SENDMSG:
2339 case AMDGPU::S_SENDMSG_RTN_B32:
2340 case AMDGPU::S_SENDMSG_RTN_B64:
2341 case AMDGPU::S_SENDMSGHALT:
2342 ScoreBrackets->updateByEvent(SQ_MESSAGE, Inst);
2344 case AMDGPU::S_MEMTIME:
2345 case AMDGPU::S_MEMREALTIME:
2346 case AMDGPU::S_GET_BARRIER_STATE_M0:
2347 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2348 ScoreBrackets->updateByEvent(SMEM_ACCESS, Inst);
2353 if (!
ST->hasWaitXCnt())
2357 ScoreBrackets->updateByEvent(VMEM_GROUP, Inst);
2360 ScoreBrackets->updateByEvent(SMEM_GROUP, Inst);
2363bool WaitcntBrackets::mergeScore(
const MergeInfo &M,
unsigned &Score,
2364 unsigned OtherScore) {
2365 unsigned MyShifted = Score <=
M.OldLB ? 0 : Score +
M.MyShift;
2366 unsigned OtherShifted =
2367 OtherScore <=
M.OtherLB ? 0 : OtherScore +
M.OtherShift;
2368 Score = std::max(MyShifted, OtherShifted);
2369 return OtherShifted > MyShifted;
2377bool WaitcntBrackets::merge(
const WaitcntBrackets &
Other) {
2378 bool StrictDom =
false;
2380 VgprUB = std::max(VgprUB,
Other.VgprUB);
2381 SgprUB = std::max(SgprUB,
Other.SgprUB);
2383 for (
auto T : inst_counter_types(
Context->MaxCounter)) {
2385 const unsigned *WaitEventMaskForInst =
Context->WaitEventMaskForInst;
2386 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[
T];
2387 const unsigned OtherEvents =
Other.PendingEvents & WaitEventMaskForInst[
T];
2388 if (OtherEvents & ~OldEvents)
2390 PendingEvents |= OtherEvents;
2393 const unsigned MyPending = ScoreUBs[
T] - ScoreLBs[
T];
2394 const unsigned OtherPending =
Other.ScoreUBs[
T] -
Other.ScoreLBs[
T];
2395 const unsigned NewUB = ScoreLBs[
T] + std::max(MyPending, OtherPending);
2396 if (NewUB < ScoreLBs[
T])
2400 M.OldLB = ScoreLBs[
T];
2401 M.OtherLB =
Other.ScoreLBs[
T];
2402 M.MyShift = NewUB - ScoreUBs[
T];
2403 M.OtherShift = NewUB -
Other.ScoreUBs[
T];
2405 ScoreUBs[
T] = NewUB;
2407 StrictDom |= mergeScore(M, LastFlat[
T],
Other.LastFlat[
T]);
2410 StrictDom |= mergeScore(M, LastGDS,
Other.LastGDS);
2413 StrictDom |= mergeScore(M, SCCScore,
Other.SCCScore);
2414 if (
Other.hasPendingEvent(SCC_WRITE)) {
2415 unsigned OldEventsHasSCCWrite = OldEvents & (1 << SCC_WRITE);
2416 if (!OldEventsHasSCCWrite) {
2417 PendingSCCWrite =
Other.PendingSCCWrite;
2418 }
else if (PendingSCCWrite !=
Other.PendingSCCWrite) {
2419 PendingSCCWrite =
nullptr;
2424 for (
int J = 0; J <= VgprUB; J++)
2425 StrictDom |= mergeScore(M, VgprScores[
T][J],
Other.VgprScores[
T][J]);
2427 if (isSmemCounter(
T)) {
2428 unsigned Idx = getSgprScoresIdx(
T);
2429 for (
int J = 0; J <= SgprUB; J++)
2431 mergeScore(M, SgprScores[Idx][J],
Other.SgprScores[Idx][J]);
2435 for (
int J = 0; J <= VgprUB; J++) {
2436 unsigned char NewVmemTypes = VgprVmemTypes[J] |
Other.VgprVmemTypes[J];
2437 StrictDom |= NewVmemTypes != VgprVmemTypes[J];
2438 VgprVmemTypes[J] = NewVmemTypes;
2446 return Opcode == AMDGPU::S_WAITCNT ||
2449 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2450 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2451 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2456bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2457 MachineBasicBlock &
Block,
2458 WaitcntBrackets &ScoreBrackets) {
2462 dbgs() <<
"*** Begin Block: ";
2464 ScoreBrackets.dump();
2470 bool VCCZCorrect =
true;
2471 if (
ST->hasReadVCCZBug()) {
2474 VCCZCorrect =
false;
2475 }
else if (!
ST->partialVCCWritesUpdateVCCZ()) {
2478 VCCZCorrect =
false;
2482 MachineInstr *OldWaitcntInstr =
nullptr;
2487 MachineInstr &Inst = *Iter;
2496 if (!OldWaitcntInstr)
2497 OldWaitcntInstr = &Inst;
2502 bool FlushVmCnt =
Block.getFirstTerminator() == Inst &&
2503 isPreheaderToFlush(
Block, ScoreBrackets);
2506 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2508 OldWaitcntInstr =
nullptr;
2514 if (
ST->hasReadVCCZBug() || !
ST->partialVCCWritesUpdateVCCZ()) {
2518 if (!
ST->partialVCCWritesUpdateVCCZ())
2519 VCCZCorrect =
false;
2528 if (
ST->hasReadVCCZBug() &&
2529 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2532 VCCZCorrect =
false;
2540 if (
TII->isSMRD(Inst)) {
2541 for (
const MachineMemOperand *Memop : Inst.
memoperands()) {
2544 if (!Memop->isInvariant()) {
2545 const Value *Ptr = Memop->getValue();
2549 if (
ST->hasReadVCCZBug()) {
2551 VCCZCorrect =
false;
2555 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2557 Modified |= insertForcedWaitAfter(Inst,
Block, ScoreBrackets);
2561 ScoreBrackets.dump();
2571 TII->get(
ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2583 AMDGPU::Waitcnt
Wait;
2584 if (
Block.getFirstTerminator() ==
Block.end() &&
2585 isPreheaderToFlush(
Block, ScoreBrackets)) {
2586 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2588 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2590 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2599 dbgs() <<
"*** End Block: ";
2601 ScoreBrackets.dump();
2609bool SIInsertWaitcnts::isPreheaderToFlush(
2610 MachineBasicBlock &
MBB,
const WaitcntBrackets &ScoreBrackets) {
2611 auto [Iterator, IsInserted] = PreheadersToFlush.
try_emplace(&
MBB,
false);
2613 return Iterator->second;
2624 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2625 Iterator->second =
true;
2632bool SIInsertWaitcnts::isVMEMOrFlatVMEM(
const MachineInstr &
MI)
const {
2634 return TII->mayAccessVMEMThroughFlat(
MI);
2646bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *
ML,
2647 const WaitcntBrackets &Brackets) {
2648 bool HasVMemLoad =
false;
2649 bool HasVMemStore =
false;
2650 bool UsesVgprLoadedOutside =
false;
2651 DenseSet<Register> VgprUse;
2652 DenseSet<Register> VgprDef;
2654 for (MachineBasicBlock *
MBB :
ML->blocks()) {
2655 for (MachineInstr &
MI : *
MBB) {
2656 if (isVMEMOrFlatVMEM(
MI)) {
2657 HasVMemLoad |=
MI.mayLoad();
2658 HasVMemStore |=
MI.mayStore();
2661 for (
const MachineOperand &
Op :
MI.all_uses()) {
2662 if (
Op.isDebug() || !
TRI->isVectorRegister(*
MRI,
Op.getReg()))
2664 RegInterval
Interval = Brackets.getRegInterval(&
MI,
Op);
2674 if (Brackets.getRegScore(RegNo, LOAD_CNT) >
2675 Brackets.getScoreLB(LOAD_CNT) ||
2676 Brackets.getRegScore(RegNo, SAMPLE_CNT) >
2677 Brackets.getScoreLB(SAMPLE_CNT) ||
2678 Brackets.getRegScore(RegNo, BVH_CNT) >
2679 Brackets.getScoreLB(BVH_CNT)) {
2680 UsesVgprLoadedOutside =
true;
2687 if (isVMEMOrFlatVMEM(
MI) &&
MI.mayLoad()) {
2688 for (
const MachineOperand &
Op :
MI.all_defs()) {
2689 RegInterval
Interval = Brackets.getRegInterval(&
MI,
Op);
2701 if (!
ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2703 return HasVMemLoad && UsesVgprLoadedOutside &&
ST->hasVmemWriteVgprInOrder();
2706bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2707 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2709 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2711 if (
auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2712 AA = &AAR->getAAResults();
2714 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2726 if (!SIInsertWaitcnts(MLI, PDT,
AA).
run(MF))
2731 .preserve<AAManager>();
2736 TII = ST->getInstrInfo();
2737 TRI = &
TII->getRegisterInfo();
2743 if (ST->hasExtendedWaitCounts()) {
2744 MaxCounter = NUM_EXTENDED_INST_CNTS;
2745 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2746 WCG = &WCGGFX12Plus;
2748 MaxCounter = NUM_NORMAL_INST_CNTS;
2749 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF);
2753 for (
auto T : inst_counter_types())
2754 ForceEmitWaitcnt[
T] =
false;
2756 WaitEventMaskForInst = WCG->getWaitEventMask();
2758 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2760 if (
ST->hasExtendedWaitCounts()) {
2774 [[maybe_unused]]
unsigned NumVGPRsMax =
2776 [[maybe_unused]]
unsigned NumSGPRsMax =
ST->getAddressableNumSGPRs();
2777 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
2778 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
2783 MachineBasicBlock &EntryBB = MF.
front();
2794 I !=
E && (
I->isPHI() ||
I->isMetaInstruction()); ++
I)
2797 if (
ST->hasExtendedWaitCounts()) {
2800 for (
auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2801 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2804 if (!
ST->hasImageInsts() &&
2805 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2809 TII->get(instrsForExtendedCounterTypes[CT]))
2816 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(
this);
2817 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2818 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2825 for (
auto *
MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2828 std::unique_ptr<WaitcntBrackets> Brackets;
2833 for (
auto BII = BlockInfos.
begin(), BIE = BlockInfos.
end(); BII != BIE;
2835 MachineBasicBlock *
MBB = BII->first;
2836 BlockInfo &BI = BII->second;
2842 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2844 *Brackets = *BI.Incoming;
2847 Brackets = std::make_unique<WaitcntBrackets>(
this);
2852 Brackets->~WaitcntBrackets();
2853 new (Brackets.get()) WaitcntBrackets(
this);
2857 Modified |= insertWaitcntInBlock(MF, *
MBB, *Brackets);
2860 if (Brackets->hasPendingEvent()) {
2861 BlockInfo *MoveBracketsToSucc =
nullptr;
2863 auto *SuccBII = BlockInfos.
find(Succ);
2864 BlockInfo &SuccBI = SuccBII->second;
2865 if (!SuccBI.Incoming) {
2866 SuccBI.Dirty =
true;
2867 if (SuccBII <= BII) {
2871 if (!MoveBracketsToSucc) {
2872 MoveBracketsToSucc = &SuccBI;
2874 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2876 }
else if (SuccBI.Incoming->merge(*Brackets)) {
2877 SuccBI.Dirty =
true;
2878 if (SuccBII <= BII) {
2884 if (MoveBracketsToSucc)
2885 MoveBracketsToSucc->Incoming = std::move(Brackets);
2890 if (
ST->hasScalarStores()) {
2891 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2892 bool HaveScalarStores =
false;
2894 for (MachineBasicBlock &
MBB : MF) {
2895 for (MachineInstr &
MI :
MBB) {
2896 if (!HaveScalarStores &&
TII->isScalarStore(
MI))
2897 HaveScalarStores =
true;
2899 if (
MI.getOpcode() == AMDGPU::S_ENDPGM ||
2900 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2905 if (HaveScalarStores) {
2914 for (MachineBasicBlock *
MBB : EndPgmBlocks) {
2915 bool SeenDCacheWB =
false;
2919 if (
I->getOpcode() == AMDGPU::S_DCACHE_WB)
2920 SeenDCacheWB =
true;
2921 else if (
TII->isScalarStore(*
I))
2922 SeenDCacheWB =
false;
2925 if ((
I->getOpcode() == AMDGPU::S_ENDPGM ||
2926 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2942 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2944 TII->get(AMDGPU::S_ALLOC_VGPR))
2949 if (!ReleaseVGPRInsts.empty() &&
2950 (MF.getFrameInfo().hasCalls() ||
2951 ST->getOccupancyWithNumVGPRs(
2952 TRI->getNumUsedPhysRegs(*
MRI, AMDGPU::VGPR_32RegClass),
2955 for (MachineInstr *
MI : ReleaseVGPRInsts) {
2956 if (
ST->requiresNopBeforeDeallocVGPRs()) {
2958 TII->get(AMDGPU::S_NOP))
2962 TII->get(AMDGPU::S_SENDMSG))
2968 ReleaseVGPRInsts.clear();
2969 PreheadersToFlush.
clear();
2970 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 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 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.
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 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.
@ 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