Skip to content

[AMDGPU] Merge consecutive wait_alu instruction #128916

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 12, 2025

Conversation

mihajlovicana
Copy link
Contributor

No description provided.

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Feb 26, 2025

@llvm/pr-subscribers-backend-amdgpu

Author: Ana Mihajlovic (mihajlovicana)

Changes

Full diff: https://github.com/llvm/llvm-project/pull/128916.diff

2 Files Affected:

  • (modified) llvm/lib/Target/AMDGPU/AMDGPUWaitSGPRHazards.cpp (+22)
  • (added) llvm/test/CodeGen/AMDGPU/merge-consecutive-wait-alus.mir (+30)
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUWaitSGPRHazards.cpp b/llvm/lib/Target/AMDGPU/AMDGPUWaitSGPRHazards.cpp
index 4df55eac5d76b..bb15d12ada650 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUWaitSGPRHazards.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUWaitSGPRHazards.cpp
@@ -164,6 +164,21 @@ class AMDGPUWaitSGPRHazards {
       BuildMI(MBB, MI, MI->getDebugLoc(), TII->get(AMDGPU::DS_NOP));
   }
 
+  unsigned mergeMasks(unsigned Mask1, unsigned Mask2) {
+    unsigned Mask = Mask1 & Mask2;
+
+    Mask = AMDGPU::DepCtr::encodeFieldVmVsrc(
+        Mask, std::min(AMDGPU::DepCtr::decodeFieldVmVsrc(Mask1),
+                       AMDGPU::DepCtr::decodeFieldVmVsrc(Mask2)));
+    Mask = AMDGPU::DepCtr::encodeFieldVaSdst(
+        Mask, std::min(AMDGPU::DepCtr::decodeFieldVaSdst(Mask1),
+                       AMDGPU::DepCtr::decodeFieldVaSdst(Mask2)));
+    Mask = AMDGPU::DepCtr::encodeFieldVaVdst(
+        Mask, std::min(AMDGPU::DepCtr::decodeFieldVaVdst(Mask1),
+                       AMDGPU::DepCtr::decodeFieldVaVdst(Mask2)));
+    return Mask;
+  }
+
   bool runOnMachineBasicBlock(MachineBasicBlock &MBB, bool Emit) {
     enum { WA_VALU = 0x1, WA_SALU = 0x2, WA_VCC = 0x4 };
 
@@ -362,6 +377,13 @@ class AMDGPUWaitSGPRHazards {
           Mask = AMDGPU::DepCtr::encodeFieldVaSdst(Mask, 0);
         }
         if (Emit) {
+          if (MI != MI->getParent()->begin()) {
+            MachineInstr &PrevMI = *std::prev(MI);
+            if (PrevMI.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR) {
+              Mask = mergeMasks(Mask, PrevMI.getOperand(0).getImm());
+              PrevMI.eraseFromParent();
+            }
+          }
           auto NewMI = BuildMI(MBB, MI, MI->getDebugLoc(),
                                TII->get(AMDGPU::S_WAITCNT_DEPCTR))
                            .addImm(Mask);
diff --git a/llvm/test/CodeGen/AMDGPU/merge-consecutive-wait-alus.mir b/llvm/test/CodeGen/AMDGPU/merge-consecutive-wait-alus.mir
new file mode 100644
index 0000000000000..0cd203e6a9bbb
--- /dev/null
+++ b/llvm/test/CodeGen/AMDGPU/merge-consecutive-wait-alus.mir
@@ -0,0 +1,30 @@
+# NOTE: Assertions have been autogenerated by utils/update_mir_test_checks.py UTC_ARGS: --version 5
+# RUN: llc -mtriple=amdgcn -mcpu=gfx1200 -verify-machineinstrs -run-pass amdgpu-wait-sgpr-hazards -o -  %s | FileCheck %s
+
+
+---
+name: merge_consecutive_wait_alus
+exposesReturnsTwice: false
+legalized:       false
+regBankSelected: false
+selected:        false
+failedISel:      false
+tracksRegLiveness: true
+body:             |
+  bb.0:
+    liveins: $vgpr0
+
+    ; CHECK-LABEL: name: merge_consecutive_wait_alus
+    ; CHECK: liveins: $vgpr0
+    ; CHECK-NEXT: {{  $}}
+    ; CHECK-NEXT: renamable $sgpr0 = V_CMP_NE_U32_e64 0, $vgpr0, implicit $exec, implicit-def $vcc_lo, implicit-def $vcc_lo
+    ; CHECK-NEXT: S_WAITCNT_DEPCTR 61946
+    ; CHECK-NEXT: renamable $vgpr0 = V_CNDMASK_B32_e64 0, -1, 0, killed $vgpr0, killed $sgpr0, implicit $exec, implicit-def $vcc_lo
+    renamable $sgpr0 = V_CMP_NE_U32_e64 0, $vgpr0, implicit $exec, implicit-def $vcc_lo, implicit-def $vcc
+    S_WAITCNT_DEPCTR 65530
+    renamable $vgpr0 = V_CNDMASK_B32_e64 0, -1, 0, killed $vgpr0, killed $sgpr0, implicit $exec, implicit-def $vcc
+...
+
+
+## NOTE: These prefixes are unused and the list is autogenerated. Do not add tests below this line:
+# CHECK: {{.*}}

@@ -362,6 +377,13 @@ class AMDGPUWaitSGPRHazards {
Mask = AMDGPU::DepCtr::encodeFieldVaSdst(Mask, 0);
}
if (Emit) {
if (MI != MI->getParent()->begin()) {
MachineInstr &PrevMI = *std::prev(MI);
if (PrevMI.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR) {
Copy link
Contributor

Choose a reason for hiding this comment

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

do we also want to check s_wait_alu here? They are aliases.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

do we also want to check s_wait_alu here? They are aliases.

I think in MIR there is only S_WAITCNT_DEPCTR

Comment on lines 23 to 24
## NOTE: These prefixes are unused and the list is autogenerated. Do not add tests below this line:
# CHECK: {{.*}}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Left-over from an earlier version, should be removed.

S_WAITCNT_DEPCTR 65530
renamable $vgpr0 = V_CNDMASK_B32_e64 0, -1, 0, killed $vgpr0, killed $sgpr0, implicit $exec, implicit-def $vcc
...

Copy link
Contributor

Choose a reason for hiding this comment

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

Test where it's the start of the block and end of the block

Copy link
Contributor

Choose a reason for hiding this comment

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

Also add a test that skips meta instructions

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Test where it's the start of the block and end of the block

Do you mean same basic block or successor and predecessor ?

S_WAITCNT_DEPCTR 65530
renamable $vgpr0 = V_CNDMASK_B32_e64 0, -1, 0, killed $vgpr0, killed $sgpr0, implicit $exec, implicit-def $vcc
...

Copy link
Contributor

Choose a reason for hiding this comment

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

Also add a test that skips meta instructions

@@ -362,6 +377,13 @@ class AMDGPUWaitSGPRHazards {
Mask = AMDGPU::DepCtr::encodeFieldVaSdst(Mask, 0);
}
if (Emit) {
if (MI != MI->getParent()->begin()) {
MachineInstr &PrevMI = *std::prev(MI);
Copy link
Contributor

Choose a reason for hiding this comment

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

You need to skip over debug instructions to avoid them changing the result

@@ -164,6 +164,21 @@ class AMDGPUWaitSGPRHazards {
BuildMI(MBB, MI, MI->getDebugLoc(), TII->get(AMDGPU::DS_NOP));
}

unsigned mergeMasks(unsigned Mask1, unsigned Mask2) {
unsigned Mask = Mask1 & Mask2;
Copy link
Contributor

Choose a reason for hiding this comment

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

Need a comment to document why an AND operation here is appropriate.
I can reason that it is safe; however, I think using this method is embedded an implicit assumption that SaSdst and VaVcc are single bits when these should be handled like other fields below (i.e. using encode and decode).
Specifically comment needs to explain why the AND is safe for any undefined/undocumented bits in the mask.
Alternatively this function should fail gracefully for bits it doesn't explicit handle.

Comment on lines 19 to 25
#include "llvm-c/Core.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/ilist_iterator.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/IR/CFG.h"
#include <iterator>
Copy link
Contributor

Choose a reason for hiding this comment

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

Are any of these actually required? The llvm-c include looks particularly suspicious.

return Mask;
}

MachineInstr *getPreviousWaitAlu(MachineBasicBlock::instr_iterator &MI) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Function seems badly named, since it does not return a wait_alu instruction. Could you use the standard prev_nodbg or do you really need to skip meta instructions too for some reason?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Function seems badly named, since it does not return a wait_alu instruction. Could you use the standard prev_nodbg or do you really need to skip meta instructions too for some reason?

llvm/test/CodeGen/AMDGPU/llvm.amdgcn.sched.barrier.ll <- test where meta instructions are there until the end

Copy link
Contributor

Choose a reason for hiding this comment

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

OK... but is there a compelling reason to combine wait_alus on either side of a sched_barrier? That feels a bit like moving wait_alus across a sched_barrier, and the whole point of sched_barrier is to prevent that, isn't it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

what about other meta instructions ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

what about other meta instructions ?
@nhaehnle what do you think ?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Let's just only skip debug instructions, so that debug instructions affect code generation as little as possible.

if (PrevWaitAlu != nullptr &&
PrevWaitAlu->getOpcode() == AMDGPU::S_WAITCNT_DEPCTR) {
Mask = mergeMasks(Mask, PrevWaitAlu->getOperand(0).getImm());
PrevWaitAlu->eraseFromParent();
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: updating the mask of the existing instruction should be a bit cheaper than erasing it and creating a new instruction.

PrevWaitAlu = getPreviousWaitAlu(MI);
} else {
auto Preds = MBB.predecessors();
if (MBB.pred_size() == 1) {
Copy link
Contributor

Choose a reason for hiding this comment

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

I guess here you are relying on the fact that if the predecessor block ends with s_wait_alu then it must fall through into MBB, i.e. it only has a single successor. But does the single-successor --> single predecessor case really occur often enough to be worth handling here?

Copy link
Contributor Author

@mihajlovicana mihajlovicana Feb 28, 2025

Choose a reason for hiding this comment

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

I think it is rare but I still ended up including it just in case.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@nhaehnle I am also not sure about this one

Copy link
Collaborator

Choose a reason for hiding this comment

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

As discussed offline, let's not look across different basic blocks.

if (It->getOpcode() == AMDGPU::S_WAITCNT_DEPCTR) {
Mask = mergeMasks(Mask, It->getOperand(0).getImm());
It->getOperand(0).setImm(Mask);
continue;
Copy link
Contributor

Choose a reason for hiding this comment

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

This will skip the "Update hazards based on defs" code below. Is that really safe?

Also I think you still need to set Emitted = true in this path, since it will be used to determine whether this pass changed anything at all in the MIR.

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes code below should not be skipped.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for pointing this out !

Copy link
Contributor

@jayfoad jayfoad left a comment

Choose a reason for hiding this comment

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

Looks much cleaner now, thanks.

Copy link
Contributor

@jayfoad jayfoad left a comment

Choose a reason for hiding this comment

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

LGTM, just some optional nits inline.

return Mask;
}

bool mergeSubsequentWaitAlus(MachineBasicBlock::instr_iterator &MI,
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe:

Suggested change
bool mergeSubsequentWaitAlus(MachineBasicBlock::instr_iterator &MI,
bool mergeConsecutiveWaitAlus(MachineBasicBlock::instr_iterator &MI,

bool mergeSubsequentWaitAlus(MachineBasicBlock::instr_iterator &MI,
unsigned Mask) {
auto MBB = MI->getParent();
if (MI != MBB->instr_begin()) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Could use early returns in this function to reduce indentation.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

    auto MBB = MI->getParent();  
    if (MI == MBB->instr_begin())  
        return false;  
  
    MachineBasicBlock::instr_iterator It = std::prev(MI);  
    while (It != MBB->instr_begin() && It->isDebugInstr())  
        --It;  
  
    if (It->getOpcode() == AMDGPU::S_WAITCNT_DEPCTR) {  
        It->getOperand(0).setImm(mergeMasks(Mask, It->getOperand(0).getImm()));  
        return true;  
    }  
  
    return false;  
}  ```

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Do you mean something like this ?

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes. You can go even further:

    if (It->getOpcode() != AMDGPU::S_WAITCNT_DEPCTR)
      return false;
    It->getOperand(0).setImm(mergeMasks(Mask, It->getOperand(0).getImm()));  
    return true;  

It is a matter of taste, but it is pretty common to do this in LLVM code.

auto MBB = MI->getParent();
if (MI != MBB->instr_begin()) {
MachineBasicBlock::instr_iterator It = std::prev(MI);
while (It != MBB->instr_begin() && It->isDebugInstr())
Copy link
Contributor

Choose a reason for hiding this comment

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

Could use getPrevNonDebugInstruction?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I tried searching for a function like that but I only found getLastNonDebugInstr() and getFirstNonDebugInstr() for a given Machine BB but not something that retrieves previous non debug instruction relative to current Machine Instruction.

Copy link
Contributor

Choose a reason for hiding this comment

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

skipDebugInstructionsForward and skipDebugInstructionsBackward

Comment on lines 198 to 199
while (It != MBB->instr_begin() && It->isDebugInstr())
--It;
Copy link
Contributor

Choose a reason for hiding this comment

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

Sorry, I meant prev_nodbg not getPrevNonDebugInstruction:

Suggested change
while (It != MBB->instr_begin() && It->isDebugInstr())
--It;
It = prev_nodbg(It, MBB->instr_begin());

Comment on lines 205 to 206

return false;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Spurious return false.

}

unsigned encodeFieldVaSsrc(unsigned VaSsrc) {
return encodeFieldVaSsrc(0xfff, VaSsrc);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should be 0xffff?

}

unsigned encodeFieldHoldCnt(unsigned HoldCnt) {
return encodeFieldHoldCnt(0xfff, HoldCnt);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Same here: 0xffff?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, that should be fixed

@mihajlovicana
Copy link
Contributor Author

PING

Copy link
Collaborator

@nhaehnle nhaehnle left a comment

Choose a reason for hiding this comment

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

Thanks, LGTM

@mbrkusanin mbrkusanin merged commit 65ade6d into llvm:main Mar 12, 2025
11 checks passed
Copy link

@mihajlovicana Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@mihajlovicana mihajlovicana deleted the merge_wait_alu branch March 12, 2025 12:59
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.

8 participants