Skip to content

[AMDGPU] Do not delete soft waits in loops - #211684

Closed
jrbyrnes wants to merge 5 commits into
mainfrom
users/jebyrnes/SoftWaitLoopOpt
Closed

jrbyrnes wants to merge 5 commits into
mainfrom
users/jebyrnes/SoftWaitLoopOpt

Conversation

@jrbyrnes

@jrbyrnes jrbyrnes commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

This PR addresses an issue in WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt

  1. The core loop of SIInsertWaitcnts walks over the MF in RPO traversal. In WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt we use WaitcntBrackets under the assumption that it contains the wait events for all predecessor blocks. However, this assumption is not true for loops. In WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt when deciding whether or not to optimize out soft waits, we reference the WaitcntBrackets to check if the soft wait is necessary. If we find it is not, we optimize it out. However, we must also check if we have visited all predecessors, otherwise we may optimize out a soft wait prematurely.

This PR addresses the problem in WaitcntGeneratorGFX12Plus in the following ways.

  1. It marks all soft waits as required. These do not get simplified out. This non simplified required wait is then combined into the wait we use to check if we can promote / delete the soft wait. Thus, if AllowWaitDeletion is false, we will always find an associated wait with this soft wait and will always promote the soft wait. This results in many soft waits being unnecessarily promoted - however, since they are unnecessary and do not have associated events, they also should not affect performance too much.

Fixes: LCOMPILER-2480

@llvmorg-github-actions

llvmorg-github-actions Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

@llvm/pr-subscribers-llvm-globalisel

@llvm/pr-subscribers-backend-amdgpu

Author: Jeffrey Byrnes (jrbyrnes)

Changes

This PR addresses a few issues in WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt

  1. The core loop of SIInsertWaitcnts walks over the MF in RPO traversal. In WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt we use WaitcntBrackets under the assumption that it contains the wait events for all predecessor blocks. However, this assumption is not true for loops.

In WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt when deciding whether or not to optimize out soft waits, we reference the WaitcntBrackets to check if the soft wait is necessary. If we find it is not, we optimize it out. However, we must also check if we have visited all predecessors, otherwise we may optimize out a soft wait prematurely.

  1. Additionally, since these soft waits may be optimized out, we must not use them to simplify e.g. vm_vsrc unless we know they will be used to resolve the outstanding events (e.g. will not be optimized out).

This PR addresses the problems in WaitcntGeneratorGFX12Plus in the following ways.

  1. It allows for promotion if we find any partial state of WaitcntBrackets which deems the soft wait necessary, and defers deletion until we are sure we have visited all the predecessors. By deferring and promoting in this way, the soft wait is provably unnecessary if AllowWaitDeletion is true and we find it is not required.

  2. Simplify the soft waits before using them to simplify other waits. For example, if we use the raw wait values of the soft wait in our CheckWait for vm_vsrc, we may conclude it covers the vm_vsrc, even if we ultimately optimize out the soft wait. Thus, we first simplify the soft waits, to remove these from the CheckWait in the case where they are not promoted.


Patch is 186.36 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/211684.diff

16 Files Affected:

  • (modified) llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp (+128-38)
  • (modified) llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmax.ll (+4-2)
  • (modified) llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmin.ll (+4-2)
  • (modified) llvm/test/CodeGen/AMDGPU/atomicrmw_usub_sat.ll (+8)
  • (modified) llvm/test/CodeGen/AMDGPU/buffer-fat-pointer-atomicrmw-fmax.ll (+20-8)
  • (modified) llvm/test/CodeGen/AMDGPU/buffer-fat-pointer-atomicrmw-fmin.ll (+20-8)
  • (modified) llvm/test/CodeGen/AMDGPU/expert_scheduling_gfx12.mir (+724-1)
  • (modified) llvm/test/CodeGen/AMDGPU/function-esm2-prologue-epilogue.ll (+2-2)
  • (modified) llvm/test/CodeGen/AMDGPU/insert-waitcnts-gfx12-wbinv.mir (+1)
  • (modified) llvm/test/CodeGen/AMDGPU/insert_waitcnt_for_precise_memory.ll (+1)
  • (modified) llvm/test/CodeGen/AMDGPU/local-atomicrmw-fadd.ll (+28)
  • (modified) llvm/test/CodeGen/AMDGPU/local-atomicrmw-fmax.ll (+36)
  • (modified) llvm/test/CodeGen/AMDGPU/local-atomicrmw-fmin.ll (+36)
  • (modified) llvm/test/CodeGen/AMDGPU/local-atomicrmw-fsub.ll (+46)
  • (added) llvm/test/CodeGen/AMDGPU/soft-waitcnt-deletion.mir (+431)
  • (added) llvm/test/CodeGen/AMDGPU/soft-waitcnt-loop-deletion.ll (+118)
diff --git a/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp b/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp
index 7fa33458fa325..4f411588de86c 100644
--- a/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp
@@ -197,10 +197,15 @@ class WaitcntGenerator {
   // needed. It may also remove existing instructions for which a wait
   // is needed if it can be determined that it is better to generate new
   // instructions later, as can happen on gfx12.
-  virtual bool
-  applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
-                          MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
-                          MachineBasicBlock::instr_iterator It) const = 0;
+  //
+  // If AllowWaitDeletion is false, soft waits will not be deleted even
+  // if they appear redundant. This is used when not all predecessor states
+  // have been seen yet (e.g., loop headers on first visit before back-edge).
+  virtual bool applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
+                                       MachineInstr &OldWaitcntInstr,
+                                       AMDGPU::Waitcnt &Wait,
+                                       MachineBasicBlock::instr_iterator It,
+                                       bool AllowWaitDeletion = true) const = 0;
 
   // Transform a soft waitcnt into a normal one.
   bool promoteSoftWaitCnt(MachineInstr *Waitcnt) const;
@@ -259,10 +264,11 @@ class WaitcntGeneratorPreGFX12 final : public WaitcntGenerator {
 
 public:
   using WaitcntGenerator::WaitcntGenerator;
-  bool
-  applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
-                          MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
-                          MachineBasicBlock::instr_iterator It) const override;
+  bool applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
+                               MachineInstr &OldWaitcntInstr,
+                               AMDGPU::Waitcnt &Wait,
+                               MachineBasicBlock::instr_iterator It,
+                               bool AllowWaitDeletion = true) const override;
 
   bool createNewWaitcnt(MachineBasicBlock &Block,
                         MachineBasicBlock::instr_iterator It,
@@ -313,10 +319,11 @@ class WaitcntGeneratorGFX12Plus final : public WaitcntGenerator {
                             bool IsExpertMode)
       : WaitcntGenerator(MF, MaxCounter, Limits), IsExpertMode(IsExpertMode) {}
 
-  bool
-  applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
-                          MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
-                          MachineBasicBlock::instr_iterator It) const override;
+  bool applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
+                               MachineInstr &OldWaitcntInstr,
+                               AMDGPU::Waitcnt &Wait,
+                               MachineBasicBlock::instr_iterator It,
+                               bool AllowWaitDeletion = true) const override;
 
   bool createNewWaitcnt(MachineBasicBlock &Block,
                         MachineBasicBlock::instr_iterator It,
@@ -347,6 +354,9 @@ class SIInsertWaitcnts {
   struct BlockInfo {
     std::unique_ptr<WaitcntBrackets> Incoming;
     bool Dirty = true;
+    // Track which predecessors have contributed to Incoming state.
+    // Used to determine if we've seen all paths before optimizing soft waits.
+    SmallPtrSet<MachineBasicBlock *, 4> SeenPredecessors;
     BlockInfo() = default;
     BlockInfo(BlockInfo &&) = default;
     BlockInfo &operator=(BlockInfo &&) = default;
@@ -432,11 +442,13 @@ class SIInsertWaitcnts {
   bool generateWaitcntInstBefore(MachineInstr &MI,
                                  WaitcntBrackets &ScoreBrackets,
                                  MachineInstr *OldWaitcntInstr,
-                                 PreheaderFlushFlags FlushFlags);
+                                 PreheaderFlushFlags FlushFlags,
+                                 bool AllowWaitDeletion = true);
   bool generateWaitcnt(AMDGPU::Waitcnt Wait,
                        MachineBasicBlock::instr_iterator It,
                        MachineBasicBlock &Block, WaitcntBrackets &ScoreBrackets,
-                       MachineInstr *OldWaitcntInstr);
+                       MachineInstr *OldWaitcntInstr,
+                       bool AllowWaitDeletion = true);
   void updateEventWaitcntAfter(MachineInstr &Inst,
                                WaitcntBrackets *ScoreBrackets);
   bool isNextENDPGM(MachineBasicBlock::instr_iterator It,
@@ -444,7 +456,8 @@ class SIInsertWaitcnts {
   bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &Block,
                              WaitcntBrackets &ScoreBrackets);
   bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block,
-                            WaitcntBrackets &ScoreBrackets);
+                            WaitcntBrackets &ScoreBrackets,
+                            bool AllowWaitDeletion = true);
   /// Removes redundant Soft Xcnt Waitcnts in \p Block emitted by the Memory
   /// Legalizer. Returns true if block was modified.
   bool removeRedundantSoftXcnts(MachineBasicBlock &Block);
@@ -537,11 +550,13 @@ class WaitcntBrackets {
   bool merge(const WaitcntBrackets &Other);
 
   bool counterOutOfOrder(AMDGPU::InstCounterType T) const;
-  void simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
-    simplifyWaitcnt(Wait, Wait);
+  void simplifyWaitcnt(AMDGPU::Waitcnt &Wait,
+                       bool UseImpliedWait = true) const {
+    simplifyWaitcnt(Wait, Wait, UseImpliedWait);
   }
   void simplifyWaitcnt(const AMDGPU::Waitcnt &CheckWait,
-                       AMDGPU::Waitcnt &UpdateWait) const;
+                       AMDGPU::Waitcnt &UpdateWait,
+                       bool UseImpliedWait = true) const;
   void simplifyWaitcnt(AMDGPU::InstCounterType T, unsigned &Count) const;
   void simplifyWaitcnt(AMDGPU::Waitcnt &Wait, AMDGPU::InstCounterType T) const;
   void simplifyXcnt(const AMDGPU::Waitcnt &CheckWait,
@@ -1252,7 +1267,8 @@ void WaitcntBrackets::print(raw_ostream &OS) const {
 /// Simplify \p UpdateWait by removing waits that are redundant based on the
 /// current WaitcntBrackets and any other waits specified in \p CheckWait.
 void WaitcntBrackets::simplifyWaitcnt(const AMDGPU::Waitcnt &CheckWait,
-                                      AMDGPU::Waitcnt &UpdateWait) const {
+                                      AMDGPU::Waitcnt &UpdateWait,
+                                      bool UseImpliedWait) const {
   simplifyWaitcnt(UpdateWait, AMDGPU::LOAD_CNT);
   simplifyWaitcnt(UpdateWait, AMDGPU::EXP_CNT);
   simplifyWaitcnt(UpdateWait, AMDGPU::DS_CNT);
@@ -1260,10 +1276,12 @@ void WaitcntBrackets::simplifyWaitcnt(const AMDGPU::Waitcnt &CheckWait,
   simplifyWaitcnt(UpdateWait, AMDGPU::SAMPLE_CNT);
   simplifyWaitcnt(UpdateWait, AMDGPU::BVH_CNT);
   simplifyWaitcnt(UpdateWait, AMDGPU::KM_CNT);
-  simplifyXcnt(CheckWait, UpdateWait);
+  if (UseImpliedWait)
+    simplifyXcnt(CheckWait, UpdateWait);
   simplifyWaitcnt(UpdateWait, AMDGPU::VA_VDST_RD);
   simplifyWaitcnt(UpdateWait, AMDGPU::VA_VDST_WR);
-  simplifyVmVsrc(CheckWait, UpdateWait);
+  if (UseImpliedWait)
+    simplifyVmVsrc(CheckWait, UpdateWait);
   simplifyWaitcnt(UpdateWait, AMDGPU::ASYNC_CNT);
 }
 
@@ -1622,7 +1640,8 @@ bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt) const {
 /// correctness.
 bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
     WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
-    AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
+    AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It,
+    bool AllowWaitDeletion) const {
   assert(isNormalMode(MaxCounter));
 
   bool Modified = false;
@@ -1646,6 +1665,10 @@ bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
     }
 
     unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
+    // TODO -- is this handled correctly in cases where we have predecessors
+    // which have not yet been visited (i.e. loops). In other words, are
+    // we prematurely deleting required soft waits? See
+    // WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt
     bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
 
     // Update required wait count. If this is a soft waitcnt (= it was added
@@ -1857,7 +1880,8 @@ WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(bool IncludeVSCnt) const {
 /// assumes that these preexisting waits are required for correctness.
 bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
     WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
-    AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
+    AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It,
+    bool AllowWaitDeletion) const {
   assert(!isNormalMode(MaxCounter));
 
   bool Modified = false;
@@ -1887,7 +1911,6 @@ bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
 
     // Update required wait count. If this is a soft waitcnt (= it was added
     // by an earlier pass), it may be entirely removed.
-
     unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
     bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
 
@@ -1935,9 +1958,10 @@ bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
       OldWait.set(AMDGPU::VA_VDST_RD, VaVdst);
       OldWait.set(AMDGPU::VA_VDST_WR, VaVdst);
       OldWait.set(AMDGPU::VM_VSRC, AMDGPU::DepCtr::decodeFieldVmVsrc(OldEnc));
-      if (TrySimplify)
-        ScoreBrackets.simplifyWaitcnt(OldWait);
+
+      assert(!TrySimplify);
       Wait = Wait.combined(OldWait);
+
       if (WaitcntDepctrInstr == nullptr) {
         WaitcntDepctrInstr = &II;
       } else {
@@ -1994,6 +2018,40 @@ bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
     }
   }
 
+  // Simplify Wait based on the combined waits. Note that we need to take care
+  // when using soft waits in our simplifications. In cases with loops, we may
+  // not have visited all predecessor edges of the block. The three possible
+  // states for a soft wait are: 1. it is required based on events from already
+  // visited predeccesors, 2. it is not required based on events from already
+  // visited predecesors, but is required after adding events from non-visited
+  // predecessors, or 3. it is not required based on events from already visited
+  // predecessors, and will not be required after adding events from non-visited
+  // predecessors.
+
+  // In case 1, we simply promote the soft wait to a regular wait. It will not
+  // be simplified by either call to simplifyWaitcnt. Since it is not simplified
+  // by the first call, it will be used to do implied wait simplifications in
+  // the second call. Then, given it is not simplified out and there is a
+  // meaningful wait, we will promote it.
+
+  // In case 2, we must simplify the soft wait out before using `Wait` for
+  // implied simplifications. For example, a S_WAIT_DSCNT_soft 0 will manifest
+  // as a 0 wait DS_CNT in `Wait`. If we use this (combined with RequiredWait)
+  // as the CheckWait in simplifyWaitcnt, we may have a case where we infer that
+  // a wait vm_vsrc is not required since the dscnt wait will cover all the
+  // oustanding events. However, since it is not a provably required soft wait
+  // we may end up deleting it, resulting in an incorrect implied
+  // simplification. Thus, we first do non-implied wait simplifications, to
+  // simplify out irrelevant softwaits, then use the simplified output to do
+  // implied simplifications. After simplifying in this way, the non provably
+  // required soft wait will not have a meaningful wait in the `Wait` Waitcnt,
+  // thus it will not be promoted. However, since we have not visited all
+  // predecessors we also do not delete it as we may find it is required later.
+
+  // In case 3, we handle the simpifications in the same way as case 2. The only
+  // difference is that when we reach the promote/delete decision, we recognize
+  // we have visited all the predecessor, so it is okay to remove the soft wait.
+  ScoreBrackets.simplifyWaitcnt(Wait, false);
   ScoreBrackets.simplifyWaitcnt(Wait.combined(RequiredWait), Wait);
   Wait = Wait.combined(RequiredWait);
 
@@ -2110,8 +2168,13 @@ bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
                               << "Old Instr: " << *It
                               << "New Instr: " << *WaitInstrs[CT] << '\n');
     } else {
-      WaitInstrs[CT]->eraseFromParent();
-      Modified = true;
+      if (AllowWaitDeletion) {
+        // Only delete waits if we've seen all predecessor states.
+        // Otherwise, keep them - they may become necessary after considering
+        // other edges.
+        WaitInstrs[CT]->eraseFromParent();
+        Modified = true;
+      }
     }
   }
 
@@ -2277,9 +2340,11 @@ bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
 ///  If FlushFlags.FlushVmCnt is true, we want to flush the vmcnt counter here.
 ///  If FlushFlags.FlushDsCnt is true, we want to flush the dscnt counter here
 ///  (GFX12+ only, where DS_CNT is a separate counter).
-bool SIInsertWaitcnts::generateWaitcntInstBefore(
-    MachineInstr &MI, WaitcntBrackets &ScoreBrackets,
-    MachineInstr *OldWaitcntInstr, PreheaderFlushFlags FlushFlags) {
+bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &MI,
+                                                 WaitcntBrackets &ScoreBrackets,
+                                                 MachineInstr *OldWaitcntInstr,
+                                                 PreheaderFlushFlags FlushFlags,
+                                                 bool AllowWaitDeletion) {
   LLVM_DEBUG(dbgs() << "\n*** GenerateWaitcntInstBefore: "; MI.print(dbgs()););
 
   assert(!isNonWaitcntMetaInst(MI));
@@ -2585,21 +2650,22 @@ bool SIInsertWaitcnts::generateWaitcntInstBefore(
     Wait.set(AMDGPU::LOAD_CNT, 0);
 
   return generateWaitcnt(Wait, MI.getIterator(), *MI.getParent(), ScoreBrackets,
-                         OldWaitcntInstr);
+                         OldWaitcntInstr, AllowWaitDeletion);
 }
 
 bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt Wait,
                                        MachineBasicBlock::instr_iterator It,
                                        MachineBasicBlock &Block,
                                        WaitcntBrackets &ScoreBrackets,
-                                       MachineInstr *OldWaitcntInstr) {
+                                       MachineInstr *OldWaitcntInstr,
+                                       bool AllowWaitDeletion) {
   bool Modified = false;
 
   if (OldWaitcntInstr)
     // Try to merge the required wait with preexisting waitcnt instructions.
     // Also erase redundant waitcnt.
-    Modified =
-        WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, It);
+    Modified = WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr,
+                                            Wait, It, AllowWaitDeletion);
 
   // ExpCnt can be merged into VINTERP.
   if (Wait.get(AMDGPU::EXP_CNT) != ~0u && It != Block.instr_end() &&
@@ -3027,7 +3093,8 @@ class VCCZWorkaround {
 // Generate s_waitcnt instructions where needed.
 bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
                                             MachineBasicBlock &Block,
-                                            WaitcntBrackets &ScoreBrackets) {
+                                            WaitcntBrackets &ScoreBrackets,
+                                            bool AllowWaitDeletion) {
   bool Modified = false;
 
   LLVM_DEBUG({
@@ -3062,7 +3129,7 @@ bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
 
     // Generate an s_waitcnt instruction to be placed before Inst, if needed.
     Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
-                                          FlushFlags);
+                                          FlushFlags, AllowWaitDeletion);
     OldWaitcntInstr = nullptr;
 
     if (Inst.getOpcode() == AMDGPU::ASYNCMARK) {
@@ -3536,8 +3603,31 @@ bool SIInsertWaitcnts::run() {
 
       if (ST.hasWaitXcnt())
         Modified |= removeRedundantSoftXcnts(*MBB);
-      Modified |= insertWaitcntInBlock(MF, *MBB, *Brackets);
+      // Only allow soft wait deletion if we've seen all reachable predecessors.
+      // This prevents premature deletion on the first pass through loop headers
+      // before back-edge state is known. We only count predecessors that are
+      // in BlockInfos (i.e., reachable via RPO traversal) to avoid infinite
+      // loops when unreachable blocks exist.
+      unsigned ReachablePredCount = 0;
+      for (MachineBasicBlock *Pred : MBB->predecessors()) {
+        if (BlockInfos.count(Pred))
+          ++ReachablePredCount;
+      }
+      bool AllowWaitDeletion = BI.SeenPredecessors.size() >= ReachablePredCount;
+      Modified |= insertWaitcntInBlock(MF, *MBB, *Brackets, AllowWaitDeletion);
       BI.Dirty = false;
+      if (!AllowWaitDeletion) {
+        BI.Dirty = true;
+        Repeat = true;
+      }
+
+      // Track that this predecessor has been processed for all successors,
+      // regardless of whether it has pending events. This ensures
+      // AllowWaitDeletion is only true when we've truly seen all predecessors.
+      for (MachineBasicBlock *Succ : MBB->successors()) {
+        BlockInfo &SuccBI = BlockInfos.find(Succ)->second;
+        SuccBI.SeenPredecessors.insert(MBB);
+      }
 
       if (Brackets->hasPendingEvent()) {
         BlockInfo *MoveBracketsToSucc = nullptr;
diff --git a/llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmax.ll b/llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmax.ll
index d62546e3de255..5444a36a542cb 100644
--- a/llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmax.ll
+++ b/llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmax.ll
@@ -1834,8 +1834,9 @@ define double @buffer_fat_ptr_agent_atomic_fmax_ret_f64__amdgpu_no_fine_grained_
 ; GFX12-NEXT:    s_mov_b32 s4, 0
 ; GFX12-NEXT:  .LBB14_1: ; %atomicrmw.start
 ; GFX12-NEXT:    ; =>This Inner Loop Header: Depth=1
-; GFX12-NEXT:    s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
+; GFX12-NEXT:    s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_2) | instid1(VALU_DEP_1)
 ; GFX12-NEXT:    v_max_num_f64_e32 v[0:1], v[4:5], v[4:5]
+; GFX12-NEXT:    s_wait_loadcnt 0x0
 ; GFX12-NEXT:    s_wait_storecnt 0x0
 ; GFX12-NEXT:    v_max_num_f64_e32 v[2:3], v[0:1], v[6:7]
 ; GFX12-NEXT:    s_delay_alu instid0(VALU_DEP_1)
@@ -2020,8 +2021,9 @@ define void @buffer_fat_ptr_agent_atomic_fmax_noret_f64__amdgpu_no_fine_grained_
 ; GFX12-NEXT:    s_mov_b32 s4, 0
 ; GFX12-NEXT:  .LBB15_1: ; %atomicrmw.start
 ; GFX12-NEXT:    ; =>This Inner Loop Header: Depth=1
-; GFX12-NEXT:    s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
+; GFX12-NEXT:    s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_2) | instid1(VALU_DEP_1)
 ; GFX12-NEXT:    v_max_num_f64_e32 v[0:1], v[2:3], v[2:3]
+; GFX12-NEXT:    s_wait_loadcnt 0x0
 ; GFX12-NEXT:    s_wait_storecnt 0x0
 ; GFX12-NEXT:    v_max_num_f64_e32 v[0:1], v[0:1], v[4:5]
 ; GFX12-NEXT:    v_dual_mov_b32 v10, v3 :: v_dual_mov_b32 v9, v2
diff --git a/llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmin.ll b/llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmin.ll
index 0530f5e69456b..508e8e1da7b5e 100644
--- a/llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmin.ll
+++ b/llvm/test/CodeGen/AMDGPU/GlobalISel/atomicrmw_fmin.ll
@@ -1834,8 +1834,9 @@ define double @buffer_fat_ptr_agent_atomic_fmin_ret_f64__amdgpu_no_fine_grained_
 ; GFX12-NEXT:    s_mov_b32 s4, 0
 ; GFX12-NEXT:  .LBB14_1: ; %atomicrmw.start
 ; GFX12-NEXT:    ; =>This Inner Loop Header: Depth=1
-; GFX12-NEXT:    s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_1) | instid1(VALU_DEP_1)
+; GFX12-NEXT:    s_delay_alu instid0(VALU_DEP_1) | instskip(SKIP_2) | instid1(VALU_DEP_1)
 ; GFX12-NEXT:    v_max_num_f64_e32 v[0:1], v[4:5], v[4:5]
+; GFX12-NEXT:    s_wait_loadcnt 0x0
 ; GFX12-NEXT:    s_wait_storecnt 0x0
 ; GFX12-NEXT:    v_min_num_f64_e32 v[2:3], v[0:1], v[6:7]
 ; GFX12-NEXT:    s_delay_alu instid0(VALU_DEP_1)
@@ -2020,8 +2021,9 @@ define void @buffer_fat_ptr_agent_atomic_fmin_noret_f64__amdgpu_no_fine_grained_
 ; GFX12-NEXT:    s_mov_b32 s4, 0
 ; GFX12-NEXT:  .LBB15_1: ; %atomicrmw.start
 ; GFX12-NEXT:    ; =>This Inner L...
[truncated]

@jrbyrnes
jrbyrnes requested a review from krzysz00 July 23, 2026 22:35
@github-actions

github-actions Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

🐧 Linux x64 Test Results

  • 200855 tests passed
  • 5482 tests skipped

✅ The build succeeded and all tests passed.

@github-actions

github-actions Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

🪟 Windows x64 Test Results

  • 138928 tests passed
  • 3582 tests skipped

✅ The build succeeded and all tests passed.

jrbyrnes added 2 commits July 23, 2026 17:13
Change-Id: I92ca9784405e53f46aa4c8701e417d32f00bbff7
Change-Id: I5f8b91764af1964f6b4b68f07f08170546a5c83b
@jrbyrnes
jrbyrnes force-pushed the users/jebyrnes/SoftWaitLoopOpt branch from bf461e2 to 125113e Compare July 24, 2026 00:35
@jayfoad

jayfoad commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

This PR addresses a few issues in WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt

  1. The core loop of SIInsertWaitcnts walks over the MF in RPO traversal. In WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt we use WaitcntBrackets under the assumption that it contains the wait events for all predecessor blocks. However, this assumption is not true for loops. In WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt when deciding whether or not to optimize out soft waits, we reference the WaitcntBrackets to check if the soft wait is necessary. If we find it is not, we optimize it out. However, we must also check if we have visited all predecessors, otherwise we may optimize out a soft wait prematurely.

This PR addresses the problems in WaitcntGeneratorGFX12Plus in the following ways.

  1. It allows for promotion if we find any partial state of WaitcntBrackets which deems the soft wait necessary, and defers deletion until we are sure we have visited all the predecessors. By deferring and promoting in this way, the soft wait is provably unnecessary if AllowWaitDeletion is true and we find it is not required.

For issue #1, I agree this is a serious problem that needs fixing, but your "visited all predecessors" condition is not sufficient in the general case. You would also need to prove that you have visited all predecessors of predecessors, and so on. I think it is much better to view this as an iterative algorithm that must be allowed to reach a fix point before we can rely on the values in WaitcntBrackets to use them to remove soft waits.

I think we should be moving towards an analysis phase that does not make any modifications at all to the code, just analyses the existing code and iterates until it reaches a fix point. Then we can run one final pass over all blocks that actually does the modifications of removing unnecessary soft waits and generating new waits.

@jayfoad

jayfoad commented Jul 28, 2026

Copy link
Copy Markdown
Contributor
  1. Additionally, since these soft waits may be optimized out, we must not use them to simplify e.g. vm_vsrc unless we know they will be used to resolve the outstanding events (e.g. will not be optimized out).
  1. Simplify the soft waits before using them to simplify other waits. For example, if we use the raw wait values of the soft wait in our CheckWait for vm_vsrc, we may conclude it covers the vm_vsrc, even if we ultimately optimize out the soft wait. Thus, we first simplify the soft waits, to remove these from the CheckWait in the case where they are not promoted.

Issue #2 doesn't make sense to me. If there is a soft wait for vm_vsrc <= N then we would only optimize it out if vm_vsrc is already known to be <= N. In either case, it is still fine to do other optimizations based on the fact that at that point in the code, vm_vsrc is known to be <= N.

@jayfoad

jayfoad commented Jul 28, 2026

Copy link
Copy Markdown
Contributor
  1. Additionally, since these soft waits may be optimized out, we must not use them to simplify e.g. vm_vsrc unless we know they will be used to resolve the outstanding events (e.g. will not be optimized out).
  1. Simplify the soft waits before using them to simplify other waits. For example, if we use the raw wait values of the soft wait in our CheckWait for vm_vsrc, we may conclude it covers the vm_vsrc, even if we ultimately optimize out the soft wait. Thus, we first simplify the soft waits, to remove these from the CheckWait in the case where they are not promoted.

Issue #2 doesn't make sense to me. If there is a soft wait for vm_vsrc <= N then we would only optimize it out if vm_vsrc is already known to be <= N. In either case, it is still fine to do other optimizations based on the fact that at that point in the code, vm_vsrc is known to be <= N.

I think I see why you made these changes, but it's not the right fix. There's a pre-existing bug in simplifyVmVsrc. I opened #212481 to fix it properly.

@jrbyrnes

Copy link
Copy Markdown
Contributor Author
  1. Additionally, since these soft waits may be optimized out, we must not use them to simplify e.g. vm_vsrc unless we know they will be used to resolve the outstanding events (e.g. will not be optimized out).
  1. Simplify the soft waits before using them to simplify other waits. For example, if we use the raw wait values of the soft wait in our CheckWait for vm_vsrc, we may conclude it covers the vm_vsrc, even if we ultimately optimize out the soft wait. Thus, we first simplify the soft waits, to remove these from the CheckWait in the case where they are not promoted.

Issue #2 doesn't make sense to me. If there is a soft wait for vm_vsrc <= N then we would only optimize it out if vm_vsrc is already known to be <= N. In either case, it is still fine to do other optimizations based on the fact that at that point in the code, vm_vsrc is known to be <= N.

To clarify, exposure to #2 is introduced after changing the algorithm to visit all predecessors. I would want to double check the details, but IIRC the issue is that we may insert vm_vsrc at the soft-wait, then update the brackets to note that we've cleared the events. Then when we revisit these soft waits for the other predecessor, we think the soft wait is sufficient given the new brackets state, and we optimize out the vm_vsrc. The main point I'm trying to convey is that the issue is introduced by the new iteration structure, and is not fixed by #212481

@jayfoad

jayfoad commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

To clarify, exposure to #2 is introduced after changing the algorithm to visit all predecessors. I would want to double check the details, but IIRC the issue is that we may insert vm_vsrc at the soft-wait, then update the brackets to note that we've cleared the events. Then when we revisit these soft waits for the other predecessor, we think the soft wait is sufficient given the new brackets state, and we optimize out the vm_vsrc. The main point I'm trying to convey is that the issue is introduced by the new iteration structure, and is not fixed by #212481

I tried rebasing this PR on #212481, and then undoing all your UseImpliedWait-related changes, and no tests failed. So I sill think #212481 is sufficient to fix issue #2.

@jrbyrnes

Copy link
Copy Markdown
Contributor Author

To clarify, exposure to #2 is introduced after changing the algorithm to visit all predecessors. I would want to double check the details, but IIRC the issue is that we may insert vm_vsrc at the soft-wait, then update the brackets to note that we've cleared the events. Then when we revisit these soft waits for the other predecessor, we think the soft wait is sufficient given the new brackets state, and we optimize out the vm_vsrc. The main point I'm trying to convey is that the issue is introduced by the new iteration structure, and is not fixed by #212481

I tried rebasing this PR on #212481, and then undoing all your UseImpliedWait-related changes, and no tests failed. So I sill think #212481 is sufficient to fix issue #2.

Thanks for pointing it out - after taking a second, deeper look I agree with your take. The true problem is that we aren't tracking the async loads. Then, given we don't have any PendingVmemEvents, the dscnt soft wait is sufficient to optimize out the vm_vsrc - the "problem" manifested when the soft wait was optimized out after a subsequent pass. So, in order to have exposure to this problem, we need 1. soft wait used to optimize the vm_vsrc, 2. soft wait gets optimized out. The only way for 1 to occur is if the pending events either include only LDS or are empty. If the pending events contain LDS, then 2 cannot happen since the soft wait will be promoted. And, after adding the async cnt, we can't have empty as we only insert these waits on WAR on some memory instruction.

jrbyrnes added 2 commits July 28, 2026 15:26
Change-Id: I1c4c4a38334ea2991730ad7b969d3780f934a6cb
Change-Id: Ib85bb44ae70d064c096f3443f37268fe11db4131
@jrbyrnes jrbyrnes changed the title [AMDGPU] Check all incoming edges before deleting soft waits [AMDGPU] Do not delete soft waits in loops Jul 28, 2026
@jrbyrnes

jrbyrnes commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor Author

For issue #1, I agree this is a serious problem that needs fixing, but your "visited all predecessors" condition is not sufficient in the general case. You would also need to prove that you have visited all predecessors of predecessors, and so on. I think it is much better to view this as an iterative algorithm that must be allowed to reach a fix point before we can rely on the values in WaitcntBrackets to use them to remove soft waits.

Yes - you're right that it is not sufficient in complex CFGs. To address it sufficiently we would need to do a non-trivial iterative restructure of the pass. I've changed the PR to always promote soft waits in loops in the interim. It will result in many soft waits being unnecessarily promoted, however since they are unnecessary they should not have associated memory events, and should not have much impact on performance.

I should also mention that the decision to promote affects the brackets - so even if we arrive at a fixed point and do a followup iteration, we would still have to contend with stale brackets.

Change-Id: I17d9a3e0db85f4f25c70099e9225340c1bd07eaa
@Pierre-vh

Copy link
Copy Markdown
Contributor

Is this ready for review?

@jrbyrnes

jrbyrnes commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Is this ready for review?

Yes - it needs to be rebased to capture minor lit changes in ToT , but in meantime we can discuss the approach.

The approach being: ultimately, we would like to restructure the iterative process to extract out soft wait handling after the brackets have reached a fixed point (as described by Jay above), but in the interim, the soft wait optimization is broken. This PR disables the optimization.

@kerbowa

kerbowa commented Aug 27, 2026

Copy link
Copy Markdown
Member

Anyone have thoughts on the approach here? This does resolve an active issue in Triton.

@qcolombet qcolombet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jayfoad could you take another look?

I don't know enough the pass to have an opinion here, but this is fixing a known bug so I would rather have an imperfect solution now than no solution at all for a while (aka the time it may take to do it right).

@jayfoad

jayfoad commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Looks like this got superseded by #220357.

@jayfoad

jayfoad commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Superseded by #220357.

@jayfoad jayfoad closed this Oct 20, 2026
@arsenm
arsenm deleted the users/jebyrnes/SoftWaitLoopOpt branch October 20, 2026 20:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants