https://github.com/danzimm updated https://github.com/llvm/llvm-project/pull/243204
>From 7c75a7fa3845857adbcdcb7daad90ac3e8ee4c6c Mon Sep 17 00:00:00 2001 From: Dan Zimmerman <[email protected]> Date: Thu, 29 Oct 2026 10:23:13 -0700 Subject: [PATCH 1/3] [AMDGPU] Add the counter padding intrinsic and builtin Assisted-by: Claude Opus 5.5 --- clang/include/clang/Basic/BuiltinsAMDGPU.td | 4 ++ .../include/clang/Basic/BuiltinsAMDGPUDocs.td | 22 ++++++++++ .../builtins-amdgcn-pad-waitcnt.cl | 27 ++++++++++++ .../SemaOpenCL/builtins-amdgcn-pad-waitcnt.cl | 11 +++++ llvm/docs/AMDGPUUsage.md | 4 ++ llvm/include/llvm/IR/IntrinsicsAMDGPU.td | 7 ++++ llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp | 8 ++++ llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp | 1 + .../AMDGPU/AMDGPURegBankLegalizeRules.cpp | 1 + llvm/lib/Target/AMDGPU/SIInstructions.td | 16 +++++++ .../CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll | 42 +++++++++++++++++++ mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td | 24 +++++++++++ .../LLVMIR/rocdl-pad-waitcnt-invalid.mlir | 31 ++++++++++++++ .../test/Target/LLVMIR/rocdl-pad-waitcnt.mlir | 40 ++++++++++++++++++ 14 files changed, 238 insertions(+) create mode 100644 clang/test/CodeGenOpenCL/builtins-amdgcn-pad-waitcnt.cl create mode 100644 clang/test/SemaOpenCL/builtins-amdgcn-pad-waitcnt.cl create mode 100644 llvm/test/CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll create mode 100644 mlir/test/Dialect/LLVMIR/rocdl-pad-waitcnt-invalid.mlir create mode 100644 mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir diff --git a/clang/include/clang/Basic/BuiltinsAMDGPU.td b/clang/include/clang/Basic/BuiltinsAMDGPU.td index 643d6f617cf0aa..44a41993c389ce 100644 --- a/clang/include/clang/Basic/BuiltinsAMDGPU.td +++ b/clang/include/clang/Basic/BuiltinsAMDGPU.td @@ -160,6 +160,10 @@ def __builtin_amdgcn_wave_barrier : AMDGPUBuiltin<"void()">; def __builtin_amdgcn_sched_barrier : AMDGPUBuiltin<"void(_Constant int)">; def __builtin_amdgcn_sched_group_barrier : AMDGPUBuiltin<"void(_Constant int, _Constant int, _Constant int)">; def __builtin_amdgcn_iglp_opt : AMDGPUBuiltin<"void(_Constant int)">; +def __builtin_amdgcn_pad_waitcnt : AMDGPUBuiltin<"void(_Constant int, _Constant int)"> { + let Documentation = [DocPadWaitcnt]; + let ArgNames = ["counter", "count"]; +} def __builtin_amdgcn_s_dcache_inv : AMDGPUBuiltin<"void()">; def __builtin_amdgcn_buffer_wbinvl1 : AMDGPUBuiltin<"void()">; def __builtin_amdgcn_fence : AMDGPUBuiltin<"void(unsigned int, char const *, ...)">; diff --git a/clang/include/clang/Basic/BuiltinsAMDGPUDocs.td b/clang/include/clang/Basic/BuiltinsAMDGPUDocs.td index 87a7663e75e46c..0aecd69d051adf 100644 --- a/clang/include/clang/Basic/BuiltinsAMDGPUDocs.td +++ b/clang/include/clang/Basic/BuiltinsAMDGPUDocs.td @@ -1050,3 +1050,25 @@ to instruction memory, with the length specified by ``len``, which should be 0-31 (1-32 chunks, units of 128 bytes). }]; } + +//===----------------------------------------------------------------------===// +// Pseudo-Instruction/Hint Builtins +//===----------------------------------------------------------------------===// + +def DocCatAMDGPUHints : DocumentationCategory<"Pseudo-Instruction/Hint Builtins"> { + let Content = [{ +These builtins do not correspond to a hardware instruction. They provide hints +to tweak code generation, but do not change program semantics. The backend may +ignore them, and they emit at most an assembly comment themselves. +}]; +} + +def DocPadWaitcnt : Documentation { + let Category = DocCatAMDGPUHints; + let Content = [{ +Optional hint to request ``count`` padding instructions in the opposite edge of +the branch whose arm contains this instruction. The supported ``counter``s are +platform dependent. Currently only passing 0 to select VMcnt on gfx9 is +supported. +}]; +} diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-waitcnt.cl b/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-waitcnt.cl new file mode 100644 index 00000000000000..3aa45ea5609d1f --- /dev/null +++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-waitcnt.cl @@ -0,0 +1,27 @@ +// RUN: %clang_cc1 -triple amdgpu9.50-amd-amdhsa -cl-std=CL2.0 -O2 -emit-llvm -o - %s | FileCheck %s --check-prefix=IR +// REQUIRES: amdgpu-registered-target + +// The void hint must survive optimization in the conditional load arm. +// IR-LABEL: @hinted_kernel( +// IR: [[A:%.*]] = load i32 +// IR: br i1 {{.*}}, label %[[JOIN:[^, ]+]], label %[[LOAD:[^, ]+]] +// IR: [[LOAD]]: +// IR: [[B:%.*]] = load i32 +// IR-NEXT: {{(tail )?}}call void @llvm.amdgcn.pad.waitcnt(i32 0, i32 1) +// IR: [[JOIN]]: +// IR-NEXT: [[V:%.*]] = phi i32 [ [[B]], %[[LOAD]] ], [ 0, %{{.*}} ] +// IR: store i32 [[A]] +// IR: store i32 [[V]] + +kernel void hinted_kernel(global int *data, global int *out, + int condition) { + unsigned index = __builtin_amdgcn_workitem_id_x(); + int a = data[index]; + int v = 0; + if (condition) { + v = data[index + 64]; + __builtin_amdgcn_pad_waitcnt(0, 1); + } + out[index] = a; + out[index + 64] = v; +} diff --git a/clang/test/SemaOpenCL/builtins-amdgcn-pad-waitcnt.cl b/clang/test/SemaOpenCL/builtins-amdgcn-pad-waitcnt.cl new file mode 100644 index 00000000000000..4c300602e79f40 --- /dev/null +++ b/clang/test/SemaOpenCL/builtins-amdgcn-pad-waitcnt.cl @@ -0,0 +1,11 @@ +// RUN: %clang_cc1 -triple amdgpu9.50-amd-amdhsa -cl-std=CL2.0 -fsyntax-only -verify %s +// REQUIRES: amdgpu-registered-target + +void immediate_arguments(int counter, int count) { + __builtin_amdgcn_pad_waitcnt(counter, 1); // expected-error {{must be a constant integer}} + __builtin_amdgcn_pad_waitcnt(0, count); // expected-error {{must be a constant integer}} + // Unsupported values are optional hints, not frontend errors. + __builtin_amdgcn_pad_waitcnt(0, 0); + __builtin_amdgcn_pad_waitcnt(0, -1); + __builtin_amdgcn_pad_waitcnt(1, 1); +} diff --git a/llvm/docs/AMDGPUUsage.md b/llvm/docs/AMDGPUUsage.md index 47a260e1f3876c..a5962c122aee8a 100644 --- a/llvm/docs/AMDGPUUsage.md +++ b/llvm/docs/AMDGPUUsage.md @@ -2620,6 +2620,10 @@ The AMDGPU backend implements the following LLVM IR intrinsics. The iglp_opt intrinsic cannot be combined with sched_barrier or sched_group_barrier. The iglp_opt strategy implementations are subject to change. +* - llvm.amdgcn.pad.waitcnt + - Optional exact-count hint to add counter events on the opposite edge of a supported single-block triangle or diamond arm. Both i32 arguments are immediate: counter 0 selects LOAD/VM and count selects the exact number of extra events. The hint itself emits no event and grants no permission to weaken a wait. + + Available through __builtin_amdgcn_pad_waitcnt(counter, count) and rocdl.pad.waitcnt. * - llvm.amdgcn.s.getpc - Provides access to the s_getpc_b64 instruction, but with the return value sign-extended from the width of the underlying PC hardware register even on processors where the s_getpc_b64 instruction returns a zero-extended value. * - llvm.amdgcn.implicit.buffer.ptr diff --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td index 3b9d7410786c88..bcfb094b9913dc 100644 --- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td +++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td @@ -409,6 +409,13 @@ def int_amdgcn_iglp_opt : ClangBuiltin<"__builtin_amdgcn_iglp_opt">, Intrinsic<[], [llvm_i32_ty], [ImmArg<ArgIndex<0>>, IntrNoMem, IntrHasSideEffects, IntrConvergent, IntrWillReturn, IntrNoCallback, IntrNoFree]>; +// Optional exact-count hint to pad the opposite arm of a supported branch. +// The hint itself has no hardware counter effect. +def int_amdgcn_pad_waitcnt : ClangBuiltin<"__builtin_amdgcn_pad_waitcnt">, + Intrinsic<[], [llvm_i32_ty, llvm_i32_ty], + [ImmArg<ArgIndex<0>>, ImmArg<ArgIndex<1>>, IntrNoMem, IntrHasSideEffects, + IntrConvergent, IntrWillReturn, IntrNoCallback, IntrNoFree]>; + def int_amdgcn_s_waitcnt : ClangBuiltin<"__builtin_amdgcn_s_waitcnt">, Intrinsic<[], [llvm_i32_ty], [ImmArg<ArgIndex<0>>, IntrNoMem, IntrHasSideEffects, IntrWillReturn, IntrNoCallback, IntrNoFree]>; diff --git a/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp b/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp index 9534140a1c1917..23bcff7b192f1c 100644 --- a/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp +++ b/llvm/lib/Target/AMDGPU/AMDGPUMCInstLower.cpp @@ -432,6 +432,14 @@ void AMDGPUAsmPrinter::emitInstruction(const MachineInstr *MI) { return; } + if (MI->getOpcode() == AMDGPU::PAD_WAITCNT) { + if (isVerbose()) + OutStreamer->emitRawComment(" pad_waitcnt(" + + Twine(MI->getOperand(0).getImm()) + ", " + + Twine(MI->getOperand(1).getImm()) + ")"); + return; + } + if (MI->getOpcode() == AMDGPU::SI_MASKED_UNREACHABLE) { if (isVerbose()) OutStreamer->emitRawComment(" divergent unreachable"); diff --git a/llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp b/llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp index 0125a402d0b187..d267682838c8c7 100644 --- a/llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp +++ b/llvm/lib/Target/AMDGPU/AMDGPUMemoryUtils.cpp @@ -397,6 +397,7 @@ bool isReallyAClobber(const Value *Ptr, MemoryDef *Def, AAResults *AA) { case Intrinsic::amdgcn_sched_barrier: case Intrinsic::amdgcn_sched_group_barrier: case Intrinsic::amdgcn_iglp_opt: + case Intrinsic::amdgcn_pad_waitcnt: return false; default: break; diff --git a/llvm/lib/Target/AMDGPU/AMDGPURegBankLegalizeRules.cpp b/llvm/lib/Target/AMDGPU/AMDGPURegBankLegalizeRules.cpp index e1207d9701cc67..7c911279df1700 100644 --- a/llvm/lib/Target/AMDGPU/AMDGPURegBankLegalizeRules.cpp +++ b/llvm/lib/Target/AMDGPU/AMDGPURegBankLegalizeRules.cpp @@ -1822,6 +1822,7 @@ RegBankLegalizeRules::RegBankLegalizeRules(const GCNSubtarget &_ST, addRulesForIOpcs({amdgcn_asyncmark, amdgcn_endpgm, amdgcn_iglp_opt, + amdgcn_pad_waitcnt, amdgcn_init_exec, amdgcn_s_barrier, amdgcn_s_barrier_leave, diff --git a/llvm/lib/Target/AMDGPU/SIInstructions.td b/llvm/lib/Target/AMDGPU/SIInstructions.td index bff8bf92f0a8f1..e668941e3c8af7 100644 --- a/llvm/lib/Target/AMDGPU/SIInstructions.td +++ b/llvm/lib/Target/AMDGPU/SIInstructions.td @@ -581,6 +581,22 @@ def IGLP_OPT : SPseudoInstSI<(outs), (ins i32imm:$mask, variable_ops), let isMeta = 1; } +// An advisory branch-arm hint for llvm.amdgcn.pad.waitcnt. The hint itself +// emits no code. +def PAD_WAITCNT : SPseudoInstSI<(outs), + (ins i32imm:$counter, i32imm:$count), + [(int_amdgcn_pad_waitcnt (i32 timm:$counter), (i32 timm:$count))]> { + let SchedRW = []; + let hasNoSchedulingInfo = 1; + let hasSideEffects = 1; + let mayLoad = 0; + let mayStore = 0; + let isConvergent = 1; + let FixedSize = 1; + let Size = 0; + let isMeta = 1; +} + // SI pseudo instructions. These are used by the CFG structurizer pass // and should be lowered to ISA instructions prior to codegen. diff --git a/llvm/test/CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll b/llvm/test/CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll new file mode 100644 index 00000000000000..43a9a3d51e7772 --- /dev/null +++ b/llvm/test/CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll @@ -0,0 +1,42 @@ +; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -stop-after=finalize-isel %s -o - | FileCheck %s --check-prefix=ISEL +; RUN: llc -global-isel -mtriple=amdgpu9.50-amd-amdhsa -stop-after=finalize-isel %s -o - | FileCheck %s --check-prefix=ISEL +; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck %s --check-prefix=ASM --implicit-check-not=buffer_inv + +; Both instruction selectors keep the hint in the arm that requests padding. +; ISEL-LABEL: name: hint_counter_intrinsic +; ISEL: bb.{{[0-9]+}}.long: +; ISEL: GLOBAL_LOAD_DWORD +; ISEL-NEXT: PAD_WAITCNT 0, 1 +; ISEL: bb.{{[0-9]+}}.join: + +; The hint itself emits nothing. +; ASM-LABEL: hint_counter_intrinsic: +; ASM: s_waitcnt vmcnt(0) +; ASM-NEXT: global_store_dword +define amdgpu_kernel void @hint_counter_intrinsic(ptr addrspace(1) %data, + ptr addrspace(1) %out, + i32 %condition) { +entry: + %index = call i32 @llvm.amdgcn.workitem.id.x() + %wide = zext i32 %index to i64 + %a.ptr = getelementptr i32, ptr addrspace(1) %data, i64 %wide + %a = load i32, ptr addrspace(1) %a.ptr, align 4 + %offset = add i64 %wide, 64 + %cond = icmp ne i32 %condition, 0 + br i1 %cond, label %long, label %join +long: + %b.ptr = getelementptr i32, ptr addrspace(1) %data, i64 %offset + %b = load i32, ptr addrspace(1) %b.ptr, align 4 + call void @llvm.amdgcn.pad.waitcnt(i32 0, i32 1) + br label %join +join: + %v = phi i32 [ %b, %long ], [ 0, %entry ] + %a.out = getelementptr i32, ptr addrspace(1) %out, i64 %wide + store i32 %a, ptr addrspace(1) %a.out, align 4 + %v.out = getelementptr i32, ptr addrspace(1) %out, i64 %offset + store i32 %v, ptr addrspace(1) %v.out, align 4 + ret void +} + +declare i32 @llvm.amdgcn.workitem.id.x() +declare void @llvm.amdgcn.pad.waitcnt(i32 immarg, i32 immarg) diff --git a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td index 619ad170120ff7..cf0dbd6d54d1c8 100644 --- a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td +++ b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td @@ -827,6 +827,30 @@ def ROCDL_IglpOpt : ROCDL_ConcreteNonMemIntrOp<"iglp.opt", [], 0, [0], ["variant }]; } +def ROCDL_PadWaitcntOp + : ROCDL_ConcreteNonMemIntrOp<"pad.waitcnt", [], 0, [0, 1], + ["counter", "count"]>, + Arguments<(ins + ConfinedAttr<I32Attr, [IntMinValue<0>, IntMaxValue<0>]>:$counter, + ConfinedAttr<I32Attr, [IntPositive]>:$count)> { + let assemblyFormat = "$counter `,` $count attr-dict"; + let summary = "optional exact-count hint to pad the opposite branch arm"; + let description = [{ + Requests exactly `count` extra counter events on the opposite edge of a + supported triangle or diamond. Counter 0 selects LOAD/VM. `counter` must be + 0 and `count` must be positive. The hint itself issues no event and does + not authorize weaker waits. + + Both arguments are immediate attributes. The operation lowers to + `llvm.amdgcn.pad.waitcnt`. + + Example: + ```mlir + rocdl.pad.waitcnt 0, 1 + ``` + }]; +} + //===---------------------------------------------------------------------===// // Xdlops intrinsics diff --git a/mlir/test/Dialect/LLVMIR/rocdl-pad-waitcnt-invalid.mlir b/mlir/test/Dialect/LLVMIR/rocdl-pad-waitcnt-invalid.mlir new file mode 100644 index 00000000000000..10d9684b443d7b --- /dev/null +++ b/mlir/test/Dialect/LLVMIR/rocdl-pad-waitcnt-invalid.mlir @@ -0,0 +1,31 @@ +// RUN: mlir-opt %s -split-input-file -verify-diagnostics + +llvm.func @pad_waitcnt_rejects_unsupported_counter() { + // expected-error@+1 {{attribute 'counter' failed to satisfy constraint}} + rocdl.pad.waitcnt 1, 1 + llvm.return +} + +// ----- + +llvm.func @pad_waitcnt_rejects_negative_counter() { + // expected-error@+1 {{attribute 'counter' failed to satisfy constraint}} + rocdl.pad.waitcnt -1, 1 + llvm.return +} + +// ----- + +llvm.func @pad_waitcnt_rejects_zero_count() { + // expected-error@+1 {{attribute 'count' failed to satisfy constraint}} + rocdl.pad.waitcnt 0, 0 + llvm.return +} + +// ----- + +llvm.func @pad_waitcnt_rejects_negative_count() { + // expected-error@+1 {{attribute 'count' failed to satisfy constraint}} + rocdl.pad.waitcnt 0, -1 + llvm.return +} diff --git a/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir b/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir new file mode 100644 index 00000000000000..5e73c47b96a3ea --- /dev/null +++ b/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir @@ -0,0 +1,40 @@ +// RUN: mlir-translate -mlir-to-llvmir %s -o %t.ll +// RUN: FileCheck %s --check-prefix=IR < %t.ll + +// IR-LABEL: @rocdl_hint_kernel( +// IR: [[A:%.*]] = load i32 +// IR: br i1 {{.*}}, label %[[LOAD:[^, ]+]], label %[[JOIN:[^, ]+]] +// IR: [[LOAD]]: +// IR: [[B:%.*]] = load i32 +// IR-NEXT: call void @llvm.amdgcn.pad.waitcnt(i32 0, i32 1) +// IR-NEXT: br label %[[JOIN]] +// IR: [[JOIN]]: +// IR-NEXT: [[V:%.*]] = phi i32 [ [[B]], %[[LOAD]] ], [ 0, %{{.*}} ] +// IR: store i32 [[A]] +// IR: store i32 [[V]] + +module attributes {llvm.target_triple = "amdgpu9.50-amd-amdhsa"} { + llvm.func @rocdl_hint_kernel(%data: !llvm.ptr<1>, %out: !llvm.ptr<1>, + %condition: i32) attributes {rocdl.kernel} { + %index = rocdl.workitem.id.x : i32 + %wide = llvm.zext %index : i32 to i64 + %a_ptr = llvm.getelementptr %data[%wide] : (!llvm.ptr<1>, i64) -> !llvm.ptr<1>, i32 + %a = llvm.load %a_ptr : !llvm.ptr<1> -> i32 + %offset = llvm.mlir.constant(64 : i64) : i64 + %b_index = llvm.add %wide, %offset : i64 + %zero = llvm.mlir.constant(0 : i32) : i32 + %cond = llvm.icmp "ne" %condition, %zero : i32 + llvm.cond_br %cond, ^load, ^join(%zero : i32) + ^load: + %b_ptr = llvm.getelementptr %data[%b_index] : (!llvm.ptr<1>, i64) -> !llvm.ptr<1>, i32 + %b = llvm.load %b_ptr : !llvm.ptr<1> -> i32 + rocdl.pad.waitcnt 0, 1 + llvm.br ^join(%b : i32) + ^join(%v: i32): + %a_out = llvm.getelementptr %out[%wide] : (!llvm.ptr<1>, i64) -> !llvm.ptr<1>, i32 + llvm.store %a, %a_out : i32, !llvm.ptr<1> + %v_out = llvm.getelementptr %out[%b_index] : (!llvm.ptr<1>, i64) -> !llvm.ptr<1>, i32 + llvm.store %v, %v_out : i32, !llvm.ptr<1> + llvm.return + } +} >From 1ebeb631ac2bf73c9554e75acb44a9adda86a442 Mon Sep 17 00:00:00 2001 From: Dan Zimmerman <[email protected]> Date: Tue, 10 Nov 2026 10:21:00 -0800 Subject: [PATCH 2/3] [AMDGPU] Lower counter padding hints in SIInsertWaitcnts Assisted-by: Claude Opus 5.5 --- .../builtins-amdgcn-pad-waitcnt.cl | 19 + llvm/docs/AMDGPUUsage.md | 4 +- llvm/lib/Target/AMDGPU/CMakeLists.txt | 1 + llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp | 55 +- llvm/lib/Target/AMDGPU/SIInstructions.td | 5 +- llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp | 171 +++++ llvm/lib/Target/AMDGPU/SIWaitcntPadding.h | 43 ++ .../CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll | 27 +- .../CodeGen/AMDGPU/pad-waitcnt-optnone.mir | 30 + .../AMDGPU/pad-waitcnt-preserve-analyses.mir | 55 ++ llvm/test/CodeGen/AMDGPU/pad-waitcnt.mir | 626 ++++++++++++++++++ .../secondary/llvm/lib/Target/AMDGPU/BUILD.gn | 1 + mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td | 10 +- .../test/Target/LLVMIR/rocdl-pad-waitcnt.mlir | 15 + 14 files changed, 1042 insertions(+), 20 deletions(-) create mode 100644 llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp create mode 100644 llvm/lib/Target/AMDGPU/SIWaitcntPadding.h create mode 100644 llvm/test/CodeGen/AMDGPU/pad-waitcnt-optnone.mir create mode 100644 llvm/test/CodeGen/AMDGPU/pad-waitcnt-preserve-analyses.mir create mode 100644 llvm/test/CodeGen/AMDGPU/pad-waitcnt.mir diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-waitcnt.cl b/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-waitcnt.cl index 3aa45ea5609d1f..bed9e3c6b5f420 100644 --- a/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-waitcnt.cl +++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-pad-waitcnt.cl @@ -1,4 +1,6 @@ // RUN: %clang_cc1 -triple amdgpu9.50-amd-amdhsa -cl-std=CL2.0 -O2 -emit-llvm -o - %s | FileCheck %s --check-prefix=IR +// RUN: %clang_cc1 -triple amdgpu9.50-amd-amdhsa -cl-std=CL2.0 -O2 -S -o - %s | FileCheck %s --check-prefix=ASM +// RUN: %clang_cc1 -triple amdgpu9.0a-amd-amdhsa -cl-std=CL2.0 -O2 -S -o - %s | FileCheck %s --check-prefix=NO_PAD --implicit-check-not=buffer_inv // REQUIRES: amdgpu-registered-target // The void hint must survive optimization in the conditional load arm. @@ -13,6 +15,23 @@ // IR: store i32 [[A]] // IR: store i32 [[V]] +// The real padding belongs to the skipped edge, not beside the extra load. +// ASM-LABEL: hinted_kernel: +// ASM: global_load_dword +// ASM: s_cbranch_scc{{[01]}} [[PAD:\.LBB[0-9]+_[0-9]+]] +// ASM: global_load_dword +// ASM-NOT: buffer_inv +// ASM: [[JOIN:\.LBB[0-9]+_[0-9]+]]: +// ASM-NEXT: s_waitcnt vmcnt(1) +// ASM-NEXT: global_store_dword +// ASM: s_endpgm +// ASM: [[PAD]]: +// ASM-NEXT: buffer_inv +// ASM-NEXT: s_branch [[JOIN]] +// NO_PAD-LABEL: hinted_kernel: +// NO_PAD: s_waitcnt vmcnt(0) +// NO_PAD-NEXT: global_store_dword + kernel void hinted_kernel(global int *data, global int *out, int condition) { unsigned index = __builtin_amdgcn_workitem_id_x(); diff --git a/llvm/docs/AMDGPUUsage.md b/llvm/docs/AMDGPUUsage.md index a5962c122aee8a..6d86e4344ee1cb 100644 --- a/llvm/docs/AMDGPUUsage.md +++ b/llvm/docs/AMDGPUUsage.md @@ -2621,7 +2621,9 @@ The AMDGPU backend implements the following LLVM IR intrinsics. The iglp_opt strategy implementations are subject to change. * - llvm.amdgcn.pad.waitcnt - - Optional exact-count hint to add counter events on the opposite edge of a supported single-block triangle or diamond arm. Both i32 arguments are immediate: counter 0 selects LOAD/VM and count selects the exact number of extra events. The hint itself emits no event and grants no permission to weaken a wait. + - Optional exact-count hint to add counter events on the opposite edge of a supported single-block triangle or diamond arm. Both i32 arguments are immediate: counter 0 selects LOAD/VM and count selects the exact number of extra events. The current implementation emits BUFFER_INV 0 on targets supporting that instruction and accepts counts 1 through the hardware wait limit minus one (1..62 on gfx942/gfx950). + + The backend materializes accepted hints immediately before waitcnt insertion, which then analyzes the padding like any other counter event. The hint itself emits no event and grants no permission to weaken a wait. Zero, invalid counts/selectors, optnone or opt-bisect skipped functions, unsupported shapes/targets, and repeated valid requests for one controlling branch are ignored. Accepted requests require an unambiguous arm in the same innermost loop as its branch and join; loop-header/latch joins are excluded. Profitability and later padding removal are not automated. Available through __builtin_amdgcn_pad_waitcnt(counter, count) and rocdl.pad.waitcnt. * - llvm.amdgcn.s.getpc diff --git a/llvm/lib/Target/AMDGPU/CMakeLists.txt b/llvm/lib/Target/AMDGPU/CMakeLists.txt index 5ed7d2acd4e025..0067ddf78db65f 100644 --- a/llvm/lib/Target/AMDGPU/CMakeLists.txt +++ b/llvm/lib/Target/AMDGPU/CMakeLists.txt @@ -195,6 +195,7 @@ add_llvm_target(AMDGPUCodeGen SIProgramInfo.cpp SIRegisterInfo.cpp SIShrinkInstructions.cpp + SIWaitcntPadding.cpp SIWholeQuadMode.cpp SIPostRA16BitMovFolding.cpp diff --git a/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp b/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp index 469a2d2c533eae..634406e07e472a 100644 --- a/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp +++ b/llvm/lib/Target/AMDGPU/SIInsertWaitcnts.cpp @@ -28,8 +28,10 @@ #include "AMDGPUWaitcntUtils.h" #include "GCNSubtarget.h" #include "SIMachineFunctionInfo.h" +#include "SIWaitcntPadding.h" #include "Utils/AMDGPUBaseInfo.h" #include "llvm/Analysis/AliasAnalysis.h" +#include "llvm/CodeGen/MachineDominators.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachinePassManager.h" @@ -349,9 +351,11 @@ class SIInsertWaitcnts { DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses; DenseMap<MachineBasicBlock *, PreheaderFlushFlags> PreheadersToFlush; MachineLoopInfo &MLI; + MachineDominatorTree *MDT; MachinePostDominatorTree &PDT; AliasAnalysis *AA = nullptr; MachineFunction &MF; + bool SkipPadding; struct BlockInfo { std::unique_ptr<WaitcntBrackets> Incoming; @@ -378,6 +382,7 @@ class SIInsertWaitcnts { DenseMap<MachineInstr *, bool> EndPgmInsts; AMDGPU::HardwareLimits Limits; + bool ChangedCFG = false; public: const GCNSubtarget &ST; @@ -389,15 +394,17 @@ class SIInsertWaitcnts { bool IsExpertMode = false; const bool TgSplit; - SIInsertWaitcnts(MachineLoopInfo &MLI, MachinePostDominatorTree &PDT, - AliasAnalysis *AA, MachineFunction &MF) - : MLI(MLI), PDT(PDT), AA(AA), MF(MF), ST(MF.getSubtarget<GCNSubtarget>()), - TII(*ST.getInstrInfo()), TRI(TII.getRegisterInfo()), - MRI(MF.getRegInfo()), + SIInsertWaitcnts(MachineLoopInfo &MLI, MachineDominatorTree *MDT, + MachinePostDominatorTree &PDT, AliasAnalysis *AA, + MachineFunction &MF, bool SkipPadding) + : MLI(MLI), MDT(MDT), PDT(PDT), AA(AA), MF(MF), SkipPadding(SkipPadding), + ST(MF.getSubtarget<GCNSubtarget>()), TII(*ST.getInstrInfo()), + TRI(TII.getRegisterInfo()), MRI(MF.getRegInfo()), TgSplit(ST.hasTgSplitSupport() && AMDGPU::isTgSplitEnabled(MF.getFunction())) {} const AMDGPU::HardwareLimits &getLimits() const { return Limits; } + bool changedCFG() const { return ChangedCFG; } PreheaderFlushFlags getPreheaderFlushFlags(MachineLoop *ML, const WaitcntBrackets &Brackets); @@ -834,9 +841,12 @@ class SIInsertWaitcntsLegacy : public MachineFunctionPass { } void getAnalysisUsage(AnalysisUsage &AU) const override { - AU.setPreservesCFG(); AU.addRequired<MachineLoopInfoWrapperPass>(); AU.addRequired<MachinePostDominatorTreeWrapperPass>(); + AU.addUsedIfAvailable<MachineDominatorTreeWrapperPass>(); + AU.addPreserved<MachineLoopInfoWrapperPass>(); + AU.addPreserved<MachineDominatorTreeWrapperPass>(); + AU.addPreserved<MachinePostDominatorTreeWrapperPass>(); AU.addUsedIfAvailable<AAResultsWrapperPass>(); AU.addPreserved<AAResultsWrapperPass>(); MachineFunctionPass::getAnalysisUsage(AU); @@ -3525,30 +3535,44 @@ SIInsertWaitcnts::getPreheaderFlushFlags(MachineLoop *ML, bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) { auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI(); + auto *MDTWrapper = getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>(); + MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr; auto &PDT = getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree(); AliasAnalysis *AA = nullptr; if (auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>()) AA = &AAR->getAAResults(); - return SIInsertWaitcnts(MLI, PDT, AA, MF).run(); + // Waitcnt insertion is required, but counter padding is an optimization. + bool SkipPadding = skipFunction(MF.getFunction()); + return SIInsertWaitcnts(MLI, MDT, PDT, AA, MF, SkipPadding).run(); } PreservedAnalyses SIInsertWaitcntsPass::run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM) { auto &MLI = MFAM.getResult<MachineLoopAnalysis>(MF); + auto *MDT = MFAM.getCachedResult<MachineDominatorTreeAnalysis>(MF); auto &PDT = MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF); auto *AA = MFAM.getResult<FunctionAnalysisManagerMachineFunctionProxy>(MF) .getManager() .getCachedResult<AAManager>(MF.getFunction()); - if (!SIInsertWaitcnts(MLI, PDT, AA, MF).run()) + // Waitcnt insertion is required, but counter padding is an optimization. + const Function &F = MF.getFunction(); + bool SkipPadding = F.hasOptNone() || shouldSkipOptimizationForOptBisect(F); + SIInsertWaitcnts Impl(MLI, MDT, PDT, AA, MF, SkipPadding); + if (!Impl.run()) return PreservedAnalyses::all(); - return getMachineFunctionPassPreservedAnalyses() - .preserveSet<CFGAnalyses>() - .preserve<AAManager>(); + auto PA = getMachineFunctionPassPreservedAnalyses(); + if (Impl.changedCFG()) + PA.preserve<MachineLoopAnalysis>() + .preserve<MachineDominatorTreeAnalysis>() + .preserve<MachinePostDominatorTreeAnalysis>(); + else + PA.preserveSet<CFGAnalyses>(); + return PA.preserve<AAManager>(); } bool SIInsertWaitcnts::run() { @@ -3575,7 +3599,16 @@ bool SIInsertWaitcnts::run() { SmemAccessCounter = getCounterFromEvent(HWEvents::SMEM_ACCESS); + // Materialize padding before taking any entry or exit score snapshots, so the + // ordinary solver sees every real counter event from its first sweep. When + // padding is skipped or unsupported, hints stay as meta instructions. bool Modified = false; + if (!SkipPadding && ST.hasBufferInvInst()) { + AMDGPU::CounterPaddingResult Padding = + AMDGPU::expandCounterPaddingHints(MF, MLI, MDT, PDT, Limits); + ChangedCFG = Padding.ChangedCFG; + Modified = Padding.Changed; + } MachineBasicBlock &EntryBB = MF.front(); diff --git a/llvm/lib/Target/AMDGPU/SIInstructions.td b/llvm/lib/Target/AMDGPU/SIInstructions.td index e668941e3c8af7..71d116cc69e768 100644 --- a/llvm/lib/Target/AMDGPU/SIInstructions.td +++ b/llvm/lib/Target/AMDGPU/SIInstructions.td @@ -581,8 +581,9 @@ def IGLP_OPT : SPseudoInstSI<(outs), (ins i32imm:$mask, variable_ops), let isMeta = 1; } -// An advisory branch-arm hint for llvm.amdgcn.pad.waitcnt. The hint itself -// emits no code. +// An advisory branch-arm hint for llvm.amdgcn.pad.waitcnt. When padding is +// enabled, waitcnt insertion replaces it with padding for a supported request; +// otherwise it is dropped at emission. def PAD_WAITCNT : SPseudoInstSI<(outs), (ins i32imm:$counter, i32imm:$count), [(int_amdgcn_pad_waitcnt (i32 timm:$counter), (i32 timm:$count))]> { diff --git a/llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp b/llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp new file mode 100644 index 00000000000000..222791e816a1d2 --- /dev/null +++ b/llvm/lib/Target/AMDGPU/SIWaitcntPadding.cpp @@ -0,0 +1,171 @@ +//===- SIWaitcntPadding.cpp - Counter padding hints for waitcnts ----------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Materialize exact-count padding hints before waitcnt insertion analyzes the +// machine function. The hint itself contributes no counter event and is +// removed once considered, whether or not its request is accepted. +// +//===----------------------------------------------------------------------===// + +#include "SIWaitcntPadding.h" +#include "AMDGPUWaitcntUtils.h" +#include "GCNSubtarget.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/CodeGen/MachineDomTreeUpdater.h" +#include "llvm/CodeGen/MachineInstrBuilder.h" +#include "llvm/CodeGen/MachineLoopInfo.h" +#include "llvm/CodeGen/MachinePostDominators.h" +#include "llvm/Support/Debug.h" +#include <optional> + +using namespace llvm; + +#define DEBUG_TYPE "si-insert-waitcnts" + +namespace { + +struct PaddingEdge { + MachineBasicBlock *Branch; + MachineBasicBlock *Pred; + MachineBasicBlock *Join; +}; + +[[maybe_unused]] void printIgnored(const MachineBasicBlock &Arm, + StringRef Reason) { + dbgs() << "Ignoring PAD_WAITCNT in " << printMBBReference(Arm) << " of " + << Arm.getParent()->getName() << ": " << Reason << '\n'; +} + +std::optional<PaddingEdge> getCounterPaddingEdge(MachineBasicBlock &Arm, + MachineLoopInfo &MLI, + const SIInstrInfo &TII) { + auto Reject = [&Arm](StringRef Reason) -> std::optional<PaddingEdge> { + LLVM_DEBUG(printIgnored(Arm, Reason)); + return std::nullopt; + }; + + MachineBasicBlock *Branch = Arm.getSinglePredecessor(); + MachineBasicBlock *Join = Arm.getSingleSuccessor(); + if (!Branch || !Join) + return Reject("arm lacks a single predecessor and successor"); + if (Branch->succ_size() != 2 || Join->pred_size() != 2) + return Reject("branch or join does not have exactly two edges"); + if (Arm.isEHPad() || Join->isEHPad()) + return Reject("arm or join is an EH pad"); + + MachineBasicBlock *Other = nullptr; + for (MachineBasicBlock *Pred : Join->predecessors()) + if (Pred != &Arm) + Other = Pred; + if (!Other || (Other != Branch && (Other->getSinglePredecessor() != Branch || + Other->getSingleSuccessor() != Join))) + return Reject("not a triangle or diamond"); + + MachineLoop *Loop = MLI.getLoopFor(Join); + if (MLI.getLoopFor(Branch) != Loop || MLI.getLoopFor(&Arm) != Loop || + MLI.getLoopFor(Other) != Loop) + return Reject("branch, arms and join are not in the same loop"); + if (Loop && (Loop->getHeader() == Join || Loop->isLoopLatch(Join))) + return Reject("join is a loop header or latch"); + + MachineBasicBlock *TBB = nullptr, *FBB = nullptr; + SmallVector<MachineOperand, 4> Cond; + if (TII.analyzeBranch(*Branch, TBB, FBB, Cond) || Cond.empty()) + return Reject("branch is not an analyzable conditional branch"); + for (MachineBasicBlock *MBB : {&Arm, Other}) { + if (MBB == Branch) + continue; + for (const MachineInstr &MI : MBB->terminators()) + if (MI.getOpcode() != AMDGPU::S_BRANCH) + return Reject("arm has a terminator other than S_BRANCH"); + } + if (Other == Branch && !Branch->canSplitCriticalEdge(Join, &MLI)) + return Reject("branch-to-join edge cannot be split"); + return PaddingEdge{Branch, Other, Join}; +} + +} // end anonymous namespace + +AMDGPU::CounterPaddingResult AMDGPU::expandCounterPaddingHints( + MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree *MDT, + MachinePostDominatorTree &PDT, const HardwareLimits &Limits) { + const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); + const SIInstrInfo &TII = *ST.getInstrInfo(); + const SIRegisterInfo &TRI = TII.getRegisterInfo(); + + struct Request { + MachineBasicBlock *Arm; + PaddingEdge Edge; + unsigned Count; + DebugLoc DL; + }; + SmallVector<Request, 8> Requests; + DenseSet<MachineBasicBlock *> SeenBranches, RepeatedBranches; + CounterPaddingResult Result; + for (MachineBasicBlock &MBB : MF) { + for (MachineInstr &MI : make_early_inc_range(MBB.instrs())) { + if (MI.getOpcode() != AMDGPU::PAD_WAITCNT) + continue; + int64_t Counter = MI.getOperand(0).getImm(); + int64_t Count = MI.getOperand(1).getImm(); + if (Counter != 0) { + LLVM_DEBUG(printIgnored(MBB, "unsupported counter selector")); + } else if (Count <= 0 || uint64_t(Count) > Limits.LoadcntMax - 1) { + LLVM_DEBUG(printIgnored(MBB, "count is out of range")); + } else if (auto Edge = getCounterPaddingEdge(MBB, MLI, TII)) { + if (!SeenBranches.insert(Edge->Branch).second) + RepeatedBranches.insert(Edge->Branch); + Requests.push_back({&MBB, *Edge, unsigned(Count), MI.getDebugLoc()}); + } + // An ignored hint grants no permission to weaken a wait. + MI.eraseFromParent(); + Result.Changed = true; + } + } + + MachineDomTreeUpdater MDTU(MDT, &PDT, + MachineDomTreeUpdater::UpdateStrategy::Eager); + for (const Request &R : Requests) { + auto [Branch, Pred, Join] = R.Edge; + if (RepeatedBranches.contains(Branch)) { + LLVM_DEBUG(printIgnored(*R.Arm, "branch has multiple padding requests")); + continue; + } + MachineBasicBlock *PadBlock = Pred; + if (Pred->succ_size() != 1) { + bool WasLayoutEdge = Pred->isLayoutSuccessor(Join); + MachineBasicBlock::SplitCriticalEdgeAnalyses Analyses{}; + Analyses.MLI = &MLI; + PadBlock = Pred->SplitCriticalEdge(Join, Analyses, &MDTU); + if (!PadBlock) { + LLVM_DEBUG(printIgnored(*R.Arm, "failed to split branch-to-join edge")); + continue; + } + Result.ChangedCFG = true; + PadBlock->setSectionID(Pred->getSectionID()); + if (!WasLayoutEdge) { + // The splitter repairs branches for its initial layout. Move a taken + // edge out of line and repair the predecessor's fallthrough again. + MF.splice(MF.end(), PadBlock); + Pred->updateTerminator(PadBlock); + } + } + PadBlock->addLiveIn(TRI.getExec()); + PadBlock->sortUniqueLiveIns(); + auto InsertPt = PadBlock->getFirstTerminator(); + for (unsigned I = 0; I != R.Count; ++I) + BuildMI(*PadBlock, InsertPt, R.DL, TII.get(AMDGPU::BUFFER_INV)).addImm(0); + LLVM_DEBUG(dbgs() << "Padded " << printMBBReference(*PadBlock) << " with " + << R.Count << " BUFFER_INV for PAD_WAITCNT in " + << printMBBReference(*R.Arm) << " of " << MF.getName() + << '\n'); + } + return Result; +} diff --git a/llvm/lib/Target/AMDGPU/SIWaitcntPadding.h b/llvm/lib/Target/AMDGPU/SIWaitcntPadding.h new file mode 100644 index 00000000000000..ba38c25559fc58 --- /dev/null +++ b/llvm/lib/Target/AMDGPU/SIWaitcntPadding.h @@ -0,0 +1,43 @@ +//===- SIWaitcntPadding.h - Counter padding hints for waitcnts --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_LIB_TARGET_AMDGPU_SIWAITCNTPADDING_H +#define LLVM_LIB_TARGET_AMDGPU_SIWAITCNTPADDING_H + +namespace llvm { + +class MachineDominatorTree; +class MachineFunction; +class MachineLoopInfo; +class MachinePostDominatorTree; + +namespace AMDGPU { + +struct HardwareLimits; + +struct CounterPaddingResult { + /// The function was modified, including by removing ignored hints. + bool Changed = false; + /// At least one edge was split to hold padding. + bool ChangedCFG = false; +}; + +/// Remove every PAD_WAITCNT hint in \p MF and materialize the padding requested +/// by supported hints, so that waitcnt insertion analyzes it like any other +/// counter event. The subtarget must support padding. \p MLI, \p PDT and, if +/// non-null, \p MDT are kept up to date. +CounterPaddingResult expandCounterPaddingHints(MachineFunction &MF, + MachineLoopInfo &MLI, + MachineDominatorTree *MDT, + MachinePostDominatorTree &PDT, + const HardwareLimits &Limits); + +} // namespace AMDGPU +} // namespace llvm + +#endif // LLVM_LIB_TARGET_AMDGPU_SIWAITCNTPADDING_H diff --git a/llvm/test/CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll b/llvm/test/CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll index 43a9a3d51e7772..457735dda589a7 100644 --- a/llvm/test/CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll +++ b/llvm/test/CodeGen/AMDGPU/pad-waitcnt-intrinsic.ll @@ -1,6 +1,9 @@ ; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -stop-after=finalize-isel %s -o - | FileCheck %s --check-prefix=ISEL ; RUN: llc -global-isel -mtriple=amdgpu9.50-amd-amdhsa -stop-after=finalize-isel %s -o - | FileCheck %s --check-prefix=ISEL -; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck %s --check-prefix=ASM --implicit-check-not=buffer_inv +; RUN: llc -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck %s --check-prefix=ASM +; RUN: llc -global-isel -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck %s --check-prefix=ASM +; RUN: llc -enable-new-pm -mtriple=amdgpu9.50-amd-amdhsa %s -o - | FileCheck %s --check-prefix=ASM +; RUN: llc -mtriple=amdgpu9.0a-amd-amdhsa %s -o - | FileCheck %s --check-prefix=NO-PAD --implicit-check-not=buffer_inv ; Both instruction selectors keep the hint in the arm that requests padding. ; ISEL-LABEL: name: hint_counter_intrinsic @@ -9,10 +12,28 @@ ; ISEL-NEXT: PAD_WAITCNT 0, 1 ; ISEL: bb.{{[0-9]+}}.join: -; The hint itself emits nothing. +; The padding belongs to the skipped edge, not beside the extra load, so the +; store of %a only waits for the older of two outstanding loads. ; ASM-LABEL: hint_counter_intrinsic: -; ASM: s_waitcnt vmcnt(0) +; ASM: global_load_dword +; ASM: s_cbranch_scc1 [[PAD:\.LBB[0-9]+_[0-9]+]] +; ASM: global_load_dword +; ASM-NOT: buffer_inv +; ASM: [[JOIN:\.LBB[0-9]+_[0-9]+]]: +; ASM-NEXT: s_waitcnt vmcnt(1) ; ASM-NEXT: global_store_dword +; ASM: s_endpgm +; ASM: [[PAD]]: +; ASM-NEXT: buffer_inv +; ASM-NEXT: s_branch [[JOIN]] + +; Without BUFFER_INV, the hint is ignored and the store waits for both loads. +; NO-PAD-LABEL: hint_counter_intrinsic: +; NO-PAD: ; %long +; NO-PAD: global_load_dword +; NO-PAD-NEXT: ; pad_waitcnt(0, 1) +; NO-PAD: s_waitcnt vmcnt(0) +; NO-PAD-NEXT: global_store_dword define amdgpu_kernel void @hint_counter_intrinsic(ptr addrspace(1) %data, ptr addrspace(1) %out, i32 %condition) { diff --git a/llvm/test/CodeGen/AMDGPU/pad-waitcnt-optnone.mir b/llvm/test/CodeGen/AMDGPU/pad-waitcnt-optnone.mir new file mode 100644 index 00000000000000..90828a82f218a7 --- /dev/null +++ b/llvm/test/CodeGen/AMDGPU/pad-waitcnt-optnone.mir @@ -0,0 +1,30 @@ +# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -run-pass=si-insert-waitcnts -o - %s | FileCheck %s --implicit-check-not=BUFFER_INV +# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -passes=si-insert-waitcnts -o - %s | FileCheck %s --implicit-check-not=BUFFER_INV + +--- | + define amdgpu_kernel void @optnone_hint() noinline optnone { ret void } +... +--- +name: optnone_hint +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + ; CHECK-LABEL: name: optnone_hint + ; CHECK: PAD_WAITCNT 0, 1 + ; CHECK: S_WAITCNT .Vmcnt_0 + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + bb.1: + successors: %bb.2 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + bb.2: + liveins: $exec, $vgpr2 + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... diff --git a/llvm/test/CodeGen/AMDGPU/pad-waitcnt-preserve-analyses.mir b/llvm/test/CodeGen/AMDGPU/pad-waitcnt-preserve-analyses.mir new file mode 100644 index 00000000000000..ff5a0755e0498a --- /dev/null +++ b/llvm/test/CodeGen/AMDGPU/pad-waitcnt-preserve-analyses.mir @@ -0,0 +1,55 @@ +# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -passes="require<machine-dom-tree>,require<machine-post-dom-tree>,require<machine-loops>,si-insert-waitcnts,print<machine-dom-tree>,print<machine-post-dom-tree>,print<machine-loops>" -debug-pass-manager -filetype=null %s 2>&1 | FileCheck %s + +# Splitting a hinted triangle inside a loop must update the cached dominator +# trees and loop membership without reconstructing the analyses. +# CHECK: Running analysis: MachineDominatorTreeAnalysis on hint_loop_triangle +# CHECK: Running analysis: MachinePostDominatorTreeAnalysis on hint_loop_triangle +# CHECK: Running analysis: MachineLoopAnalysis on hint_loop_triangle +# CHECK: Running pass: SIInsertWaitcntsPass on hint_loop_triangle +# CHECK-NOT: Running analysis: Machine{{.*}}Analysis +# CHECK: Running pass: MachineDominatorTreePrinterPass on hint_loop_triangle +# CHECK: Inorder Dominator Tree: +# CHECK: %bb.6 +# CHECK-NOT: Running analysis: Machine{{.*}}Analysis +# CHECK: Running pass: MachinePostDominatorTreePrinterPass on hint_loop_triangle +# CHECK: Inorder PostDominator Tree: +# CHECK: %bb.6 +# CHECK-NOT: Running analysis: Machine{{.*}}Analysis +# CHECK: Running pass: MachineLoopPrinterPass on hint_loop_triangle +# CHECK: Loop at depth 1 containing: {{.*}}%bb.6 + +--- +name: hint_loop_triangle +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1 + liveins: $exec, $scc + S_BRANCH %bb.1 + + bb.1: + successors: %bb.2, %bb.3 + liveins: $exec, $scc + S_CBRANCH_SCC1 %bb.3, implicit $scc + + bb.2: + successors: %bb.3 + liveins: $exec, $scc + PAD_WAITCNT 0, 1 + S_BRANCH %bb.3 + + bb.3: + successors: %bb.4 + liveins: $exec, $scc + S_BRANCH %bb.4 + + bb.4: + successors: %bb.1, %bb.5 + liveins: $exec, $scc + S_CBRANCH_SCC1 %bb.1, implicit $scc + + bb.5: + S_ENDPGM 0 +... diff --git a/llvm/test/CodeGen/AMDGPU/pad-waitcnt.mir b/llvm/test/CodeGen/AMDGPU/pad-waitcnt.mir new file mode 100644 index 00000000000000..8246878b57b78b --- /dev/null +++ b/llvm/test/CodeGen/AMDGPU/pad-waitcnt.mir @@ -0,0 +1,626 @@ +# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -run-pass=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=PAD --implicit-check-not=PAD_WAITCNT +# RUN: llc -mtriple=amdgpu9.42-amd-amdhsa -run-pass=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=PAD --implicit-check-not=PAD_WAITCNT +# RUN: llc -O0 -mtriple=amdgpu9.50-amd-amdhsa -run-pass=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=PAD --implicit-check-not=PAD_WAITCNT +# RUN: llc -mtriple=amdgpu9.0a-amd-amdhsa -run-pass=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=DISABLED --implicit-check-not=BUFFER_INV +# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -amdgpu-waitcnt-forcezero -run-pass=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=FORCED --implicit-check-not=PAD_WAITCNT +# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -passes=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=PAD --implicit-check-not=PAD_WAITCNT +# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -opt-bisect-limit=0 -run-pass=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=DISABLED --implicit-check-not=BUFFER_INV +# RUN: llc -mtriple=amdgpu9.50-amd-amdhsa -opt-bisect-limit=0 -passes=si-insert-waitcnts -o - %s | FileCheck %s --check-prefix=DISABLED --implicit-check-not=BUFFER_INV + +# A hint contributes no event on its own arm. Its exact count is materialized +# on the other edge before the ordinary solver, including force-zero mode. +# PAD-LABEL: name: hint_diamond +# PAD: bb.1: +# PAD: $vgpr3 = GLOBAL_LOAD_DWORD +# PAD-NOT: BUFFER_INV +# PAD: S_BRANCH %bb.3 +# PAD: bb.2: +# PAD-COUNT-2: BUFFER_INV 0, implicit $exec +# PAD-NEXT: S_BRANCH %bb.3 +# PAD: bb.3: +# PAD: S_WAITCNT .Vmcnt_1 +# DISABLED-LABEL: name: hint_diamond +# DISABLED: PAD_WAITCNT 0, 2 +# DISABLED: S_WAITCNT .Vmcnt_0 +# FORCED-LABEL: name: hint_diamond +# FORCED: bb.2: +# FORCED: S_WAITCNT .Vmcnt_0_Expcnt_0_Lgkmcnt_0 +# FORCED-NEXT: BUFFER_INV 0, implicit $exec +# FORCED-NEXT: S_WAITCNT .Vmcnt_0_Expcnt_0_Lgkmcnt_0 +# FORCED-NEXT: BUFFER_INV 0, implicit $exec + +--- +name: hint_diamond +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 2 + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_triangle_taken +# PAD: bb.0: +# PAD: S_CBRANCH_SCC1 %bb.[[TAKEN:[0-9]+]] +# PAD: bb.1: +# PAD: $vgpr3 = GLOBAL_LOAD_DWORD +# PAD-NOT: BUFFER_INV +# PAD: bb.2: +# PAD: S_WAITCNT .Vmcnt_1 +# PAD: bb.[[TAKEN]]: +# PAD: successors: %bb.2 +# PAD: BUFFER_INV 0, implicit $exec +# PAD-NEXT: S_BRANCH %bb.2 +--- +name: hint_triangle_taken +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.2 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + + bb.2: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_triangle_fallthrough +# PAD: bb.0: +# PAD: S_CBRANCH_SCC1 %bb.2 +# PAD: bb.[[FALL:[0-9]+]]: +# PAD: successors: %bb.1 +# PAD: BUFFER_INV 0, implicit $exec +# PAD: bb.1: +# PAD: S_WAITCNT .Vmcnt_1 +# PAD: bb.2: +# PAD: $vgpr3 = GLOBAL_LOAD_DWORD +# PAD-NOT: BUFFER_INV +# PAD: S_BRANCH %bb.1 +--- +name: hint_triangle_fallthrough +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 + + bb.2: + successors: %bb.1 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + S_BRANCH %bb.1 +... + +# Padding can expose old B across the backedge. Normal insertion must add a +# wait in the short arm before consuming B, while preserving A's VM1 at join. +# PAD-LABEL: name: hint_loop_carried +# PAD: bb.3: +# PAD: S_WAITCNT .Vmcnt_1 +# PAD-NEXT: $vgpr5 = V_MOV_B32_e32 $vgpr3 +# PAD-NEXT: BUFFER_INV 0, implicit $exec +# PAD-NEXT: S_BRANCH %bb.4 +# PAD: bb.4: +# PAD: S_WAITCNT .Vmcnt_1 +--- +name: hint_loop_carried +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr3 = V_MOV_B32_e32 0, implicit $exec + S_BRANCH %bb.1 + + bb.1: + successors: %bb.2, %bb.3 + liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr3 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.3, implicit $scc + + bb.2: + successors: %bb.4 + liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2, $vgpr3 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + S_BRANCH %bb.4 + + bb.3: + successors: %bb.4 + liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2, $vgpr3 + + $vgpr5 = V_MOV_B32_e32 $vgpr3, implicit $exec + S_BRANCH %bb.4 + + bb.4: + successors: %bb.5 + liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2, $vgpr3 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_BRANCH %bb.5 + + bb.5: + successors: %bb.1, %bb.6 + liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr3 + + S_CBRANCH_SCC1 %bb.1, implicit $scc + S_BRANCH %bb.6 + + bb.6: + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_multiple_branches +# PAD: S_WAITCNT .Vmcnt_2 +# PAD: BUFFER_INV 0, implicit $exec +# PAD: BUFFER_INV 0, implicit $exec +--- +name: hint_multiple_branches +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + bb.1: + successors: %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + bb.2: + successors: %bb.3, %bb.4 + liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2 + + S_CBRANCH_SCC1 %bb.4, implicit $scc + bb.3: + successors: %bb.4 + liveins: $exec, $scc, $vgpr0_vgpr1, $vgpr2 + + $vgpr5 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + bb.4: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_repeated +# PAD-NOT: BUFFER_INV +# PAD: S_WAITCNT .Vmcnt_0 +--- +name: hint_repeated +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + PAD_WAITCNT 0, 1 + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_both_arms +# PAD-NOT: BUFFER_INV +# PAD: S_WAITCNT .Vmcnt_0 +--- +name: hint_both_arms +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + PAD_WAITCNT 0, 1 + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_common_header +# PAD-NOT: BUFFER_INV +# PAD: S_WAITCNT .Vmcnt_0 +--- +name: hint_common_header +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_zero +# PAD-NOT: BUFFER_INV +# PAD: S_WAITCNT .Vmcnt_0 +--- +name: hint_zero +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 0 + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_invalid_selector +# PAD-NOT: BUFFER_INV +# PAD: S_WAITCNT .Vmcnt_0 +--- +name: hint_invalid_selector +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 1, 1 + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_negative_count +# PAD-NOT: BUFFER_INV +# PAD: S_WAITCNT .Vmcnt_0 +--- +name: hint_negative_count +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, -1 + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_above_range +# PAD-NOT: BUFFER_INV +# PAD: S_WAITCNT .Vmcnt_0 +--- +name: hint_above_range +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 63 + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# PAD-LABEL: name: hint_count_max +# PAD: bb.2: +# PAD-COUNT-62: BUFFER_INV 0, implicit $exec +# PAD-NEXT: S_BRANCH %bb.3 +# PAD: S_WAITCNT .Vmcnt_1 +--- +name: hint_count_max +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 62 + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# A hint never overrides an original ordering request. +# PAD-LABEL: name: hint_original_soft_wait +# PAD: bb.2: +# PAD: BUFFER_INV 0, implicit $exec +# PAD: bb.3: +# PAD: S_WAITCNT .Vmcnt_0 +# PAD-NEXT: S_BARRIER +--- +name: hint_original_soft_wait +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + + $vgpr2 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + S_CBRANCH_SCC1 %bb.2, implicit $scc + + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1, $vgpr2 + + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + S_BRANCH %bb.3 + + bb.2: + successors: %bb.3 + liveins: $exec, $vgpr2 + + S_BRANCH %bb.3 + + bb.3: + liveins: $exec, $vgpr2 + + S_WAITCNT_soft 0 + S_BARRIER + $vgpr4 = V_MOV_B32_e32 $vgpr2, implicit $exec + S_ENDPGM 0 +... + +# The original LDS release marker is resolved on the actual padded program. +# PAD-LABEL: name: hint_original_lds_marker +# PAD: bb.2: +# PAD: BUFFER_INV 0, implicit $exec +# PAD: bb.3: +# PAD-NOT: S_WAITCNT_lds_direct +# PAD: S_WAITCNT .Vmcnt_1 +# PAD-NEXT: S_BARRIER +--- +name: hint_original_lds_marker +tracksRegLiveness: true +machineFunctionInfo: + isEntryFunction: true +body: | + bb.0: + successors: %bb.1, %bb.2 + liveins: $exec, $scc, $vgpr0_vgpr1 + $m0 = S_MOV_B32 0 + GLOBAL_LOAD_LDS_DWORD $vgpr0_vgpr1, 0, 0, 0, implicit $m0, implicit $exec :: (load (s32), addrspace 1), (store (s32), addrspace 3) + S_CBRANCH_SCC1 %bb.2, implicit $scc + bb.1: + successors: %bb.3 + liveins: $exec, $vgpr0_vgpr1 + $vgpr3 = GLOBAL_LOAD_DWORD $vgpr0_vgpr1, 0, 0, implicit $exec + PAD_WAITCNT 0, 1 + S_BRANCH %bb.3 + bb.2: + successors: %bb.3 + liveins: $exec + S_BRANCH %bb.3 + bb.3: + liveins: $exec + S_WAITCNT_lds_direct + S_BARRIER + S_ENDPGM 0 +... diff --git a/llvm/utils/gn/secondary/llvm/lib/Target/AMDGPU/BUILD.gn b/llvm/utils/gn/secondary/llvm/lib/Target/AMDGPU/BUILD.gn index 03466bcf923375..0bbe01c7b1148c 100644 --- a/llvm/utils/gn/secondary/llvm/lib/Target/AMDGPU/BUILD.gn +++ b/llvm/utils/gn/secondary/llvm/lib/Target/AMDGPU/BUILD.gn @@ -290,6 +290,7 @@ static_library("LLVMAMDGPUCodeGen") { "SIRegisterInfo.cpp", "SIShrinkInstructions.cpp", "SISpillUtils.cpp", + "SIWaitcntPadding.cpp", "SIWholeQuadMode.cpp", ] } diff --git a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td index cf0dbd6d54d1c8..99c070b734b8d8 100644 --- a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td +++ b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td @@ -838,11 +838,15 @@ def ROCDL_PadWaitcntOp let description = [{ Requests exactly `count` extra counter events on the opposite edge of a supported triangle or diamond. Counter 0 selects LOAD/VM. `counter` must be - 0 and `count` must be positive. The hint itself issues no event and does - not authorize weaker waits. + 0 and `count` must be positive. The current backend supports `BUFFER_INV 0` + and accepts counts 1..62 on gfx942/gfx950. Out-of-range, unsupported, + ambiguous, and repeated requests are ignored. + The hint itself issues no event and does not authorize weaker waits. Both arguments are immediate attributes. The operation lowers to - `llvm.amdgcn.pad.waitcnt`. + `llvm.amdgcn.pad.waitcnt`. The backend materializes accepted hints + immediately before waitcnt insertion, which then analyzes the padding and + preserves completion and ordering requirements. Example: ```mlir diff --git a/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir b/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir index 5e73c47b96a3ea..6af870e6be9bad 100644 --- a/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir +++ b/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir @@ -1,5 +1,7 @@ // RUN: mlir-translate -mlir-to-llvmir %s -o %t.ll // RUN: FileCheck %s --check-prefix=IR < %t.ll +// RUN: %if has_llc_binary && host-supports-amdgpu %{ llc -mtriple=amdgpu9.50-amd-amdhsa %t.ll -o - | FileCheck %s --check-prefix=ASM %} +// RUN: %if has_llc_binary && host-supports-amdgpu %{ llc -global-isel -mtriple=amdgpu9.50-amd-amdhsa %t.ll -o - | FileCheck %s --check-prefix=ASM %} // IR-LABEL: @rocdl_hint_kernel( // IR: [[A:%.*]] = load i32 @@ -13,6 +15,19 @@ // IR: store i32 [[A]] // IR: store i32 [[V]] +// ASM-LABEL: rocdl_hint_kernel: +// ASM: global_load_dword +// ASM: s_cbranch_scc{{[01]}} [[PAD:\.LBB[0-9]+_[0-9]+]] +// ASM: global_load_dword +// ASM-NOT: buffer_inv +// ASM: [[JOIN:\.LBB[0-9]+_[0-9]+]]: +// ASM-NEXT: s_waitcnt vmcnt(1) +// ASM-NEXT: global_store_dword +// ASM: s_endpgm +// ASM: [[PAD]]: +// ASM-NEXT: buffer_inv +// ASM-NEXT: s_branch [[JOIN]] + module attributes {llvm.target_triple = "amdgpu9.50-amd-amdhsa"} { llvm.func @rocdl_hint_kernel(%data: !llvm.ptr<1>, %out: !llvm.ptr<1>, %condition: i32) attributes {rocdl.kernel} { >From 71183998745b735bac844e71be72177329745ea4 Mon Sep 17 00:00:00 2001 From: Dan Zimmerman <[email protected]> Date: Tue, 17 Nov 2026 10:49:26 -0800 Subject: [PATCH 3/3] [AMDGPU] Use a named enum for the rocdl.pad.waitcnt counter Assisted-by: Claude Opus 5.5 --- mlir/include/mlir/Dialect/LLVMIR/ROCDLAttrs.td | 3 +++ mlir/include/mlir/Dialect/LLVMIR/ROCDLEnums.td | 12 ++++++++++++ mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td | 18 +++++++++--------- .../LLVMIR/rocdl-pad-waitcnt-invalid.mlir | 12 ++++++------ mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir | 2 +- 5 files changed, 31 insertions(+), 16 deletions(-) diff --git a/mlir/include/mlir/Dialect/LLVMIR/ROCDLAttrs.td b/mlir/include/mlir/Dialect/LLVMIR/ROCDLAttrs.td index c8880818aace0d..f91e3532d89a4f 100644 --- a/mlir/include/mlir/Dialect/LLVMIR/ROCDLAttrs.td +++ b/mlir/include/mlir/Dialect/LLVMIR/ROCDLAttrs.td @@ -89,6 +89,9 @@ def ROCDL_SchedGroupMaskAttr def ROCDL_AsyncStagesAttr : ROCDL_IntrinsicIntegerEnumAttr<ROCDL_AsyncStages, "async_stages">; +def ROCDL_WaitcntCounterAttr + : ROCDL_IntrinsicIntegerEnumAttr<ROCDL_WaitcntCounter, "waitcnt_counter">; + def ROCDL_PreGfx12CachePolicyAttr : ROCDL_IntrinsicIntegerEnumAttr<ROCDL_PreGfx12CachePolicy, "pre_gfx12_cache_policy">; diff --git a/mlir/include/mlir/Dialect/LLVMIR/ROCDLEnums.td b/mlir/include/mlir/Dialect/LLVMIR/ROCDLEnums.td index e15db9e4f8dc1a..1b3552840f45bc 100644 --- a/mlir/include/mlir/Dialect/LLVMIR/ROCDLEnums.td +++ b/mlir/include/mlir/Dialect/LLVMIR/ROCDLEnums.td @@ -319,4 +319,16 @@ def ROCDL_Gfx12AtomicCachePolicy : ROCDL_I32BitEnum<"Gfx12AtomicCachePolicy", let printBitEnumQuoted = 0; } +//===----------------------------------------------------------------------===// +// Wait counter padding enum. +//===----------------------------------------------------------------------===// + +// Keep these values in sync with the counter encoding of +// llvm.amdgcn.pad.waitcnt. +def ROCDL_WaitcntCounter : ROCDL_I32Enum<"WaitcntCounter", + "hardware wait counter padded by rocdl.pad.waitcnt", + [ + I32EnumCase<"load", 0> + ]>; + #endif // ROCDLIR_ENUMS diff --git a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td index 99c070b734b8d8..f500fdcdb47edd 100644 --- a/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td +++ b/mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td @@ -830,17 +830,17 @@ def ROCDL_IglpOpt : ROCDL_ConcreteNonMemIntrOp<"iglp.opt", [], 0, [0], ["variant def ROCDL_PadWaitcntOp : ROCDL_ConcreteNonMemIntrOp<"pad.waitcnt", [], 0, [0, 1], ["counter", "count"]>, - Arguments<(ins - ConfinedAttr<I32Attr, [IntMinValue<0>, IntMaxValue<0>]>:$counter, - ConfinedAttr<I32Attr, [IntPositive]>:$count)> { - let assemblyFormat = "$counter `,` $count attr-dict"; + Arguments<(ins ROCDL_WaitcntCounterAttr:$counter, + ConfinedAttr<I32Attr, [IntPositive]>:$count)> { + let assemblyFormat = "enum($counter) `,` $count attr-dict"; let summary = "optional exact-count hint to pad the opposite branch arm"; let description = [{ Requests exactly `count` extra counter events on the opposite edge of a - supported triangle or diamond. Counter 0 selects LOAD/VM. `counter` must be - 0 and `count` must be positive. The current backend supports `BUFFER_INV 0` - and accepts counts 1..62 on gfx942/gfx950. Out-of-range, unsupported, - ambiguous, and repeated requests are ignored. + supported triangle or diamond. `counter` selects the counter to pad; `load` + (LOAD/VM, encoded as 0) is the only supported counter. `count` must be + positive. The current backend supports `BUFFER_INV 0` and accepts counts + 1..62 on gfx942/gfx950. Out-of-range, unsupported, ambiguous, and repeated + requests are ignored. The hint itself issues no event and does not authorize weaker waits. Both arguments are immediate attributes. The operation lowers to @@ -850,7 +850,7 @@ def ROCDL_PadWaitcntOp Example: ```mlir - rocdl.pad.waitcnt 0, 1 + rocdl.pad.waitcnt load, 1 ``` }]; } diff --git a/mlir/test/Dialect/LLVMIR/rocdl-pad-waitcnt-invalid.mlir b/mlir/test/Dialect/LLVMIR/rocdl-pad-waitcnt-invalid.mlir index 10d9684b443d7b..eab0ccd5b706f2 100644 --- a/mlir/test/Dialect/LLVMIR/rocdl-pad-waitcnt-invalid.mlir +++ b/mlir/test/Dialect/LLVMIR/rocdl-pad-waitcnt-invalid.mlir @@ -1,16 +1,16 @@ // RUN: mlir-opt %s -split-input-file -verify-diagnostics -llvm.func @pad_waitcnt_rejects_unsupported_counter() { - // expected-error@+1 {{attribute 'counter' failed to satisfy constraint}} +llvm.func @pad_waitcnt_rejects_numeric_counter() { + // expected-error@+1 {{expected string or keyword containing one of the following enum values for attribute 'counter' [load]}} rocdl.pad.waitcnt 1, 1 llvm.return } // ----- -llvm.func @pad_waitcnt_rejects_negative_counter() { +llvm.func @pad_waitcnt_rejects_integer_counter_attr() { // expected-error@+1 {{attribute 'counter' failed to satisfy constraint}} - rocdl.pad.waitcnt -1, 1 + "rocdl.pad.waitcnt"() {counter = 0 : i32, count = 1 : i32} : () -> () llvm.return } @@ -18,7 +18,7 @@ llvm.func @pad_waitcnt_rejects_negative_counter() { llvm.func @pad_waitcnt_rejects_zero_count() { // expected-error@+1 {{attribute 'count' failed to satisfy constraint}} - rocdl.pad.waitcnt 0, 0 + rocdl.pad.waitcnt load, 0 llvm.return } @@ -26,6 +26,6 @@ llvm.func @pad_waitcnt_rejects_zero_count() { llvm.func @pad_waitcnt_rejects_negative_count() { // expected-error@+1 {{attribute 'count' failed to satisfy constraint}} - rocdl.pad.waitcnt 0, -1 + rocdl.pad.waitcnt load, -1 llvm.return } diff --git a/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir b/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir index 6af870e6be9bad..ce90209521d642 100644 --- a/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir +++ b/mlir/test/Target/LLVMIR/rocdl-pad-waitcnt.mlir @@ -43,7 +43,7 @@ module attributes {llvm.target_triple = "amdgpu9.50-amd-amdhsa"} { ^load: %b_ptr = llvm.getelementptr %data[%b_index] : (!llvm.ptr<1>, i64) -> !llvm.ptr<1>, i32 %b = llvm.load %b_ptr : !llvm.ptr<1> -> i32 - rocdl.pad.waitcnt 0, 1 + rocdl.pad.waitcnt load, 1 llvm.br ^join(%b : i32) ^join(%v: i32): %a_out = llvm.getelementptr %out[%wide] : (!llvm.ptr<1>, i64) -> !llvm.ptr<1>, i32 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
