Skip to content

shader: lower a per-lane compute guard as control flow around its stores - #776

Merged
R0Y00 merged 1 commit into
R0Y00:mainfrom
roansystemlabs:compute/per-lane-guard
Nov 23, 2026
Merged

R0Y00 merged 1 commit into
R0Y00:mainfrom
roansystemlabs:compute/per-lane-guard

Conversation

@roansystemlabs

Copy link
Copy Markdown
Contributor

Change

Step 2 of #721: the per-lane guard, modelled as control flow around the store, as you asked on #721. Refs #721.

For a per-lane bound such as if (gid < n) store, LLVM 15 does not emit an early s_endpgm (see #738). It emits one exit and masks the store instead:

v_cmp_gt_u32_e32 vcc_lo, s3, v0        ; n > gid, per lane
s_and_saveexec_b32 s0, vcc_lo          ; save exec, keep only the passing lanes
s_cbranch_execz .LBB1_2                ; skip the block when no lane passes
buffer_store_dword v0, v0, s[4:7], 0 idxen
.LBB1_2:
s_waitcnt_depctr 0xffe3
s_or_b32 exec_lo, exec_lo, s0          ; restore (or exit with the mask still applied)

compute_store_aot.lower() now accepts this form and emits an HLSL if around the stores issued under the mask. Stores after the restore stay outside the if. The guard is lowered as control flow only. Masked VGPR merges are out of scope, and so are reads and any new address or data ALU.

  • Compare: v_cmp_{gt,lt,ge,le}_u32_e32 vcc_lo, a, vN. Both operands must already be known words (a dispatch index, a constant word or an immediate). The HLSL condition keeps the operator and operand order. No other compare, and no _e64 or signed form, is accepted.
  • Mask: s_and_saveexec_b32 sN, vcc_lo after a compare, at most once per program, so guards cannot nest. The restore is s_or_b32 exec_lo, exec_lo, sM, where sM must still hold the saved mask. With a branch, sM must already hold it at the branch, so it also holds the mask when the block is skipped (a copy made only inside the block is rejected). If no restore comes before s_endpgm, the mask holds to the exit and every later store is guarded. Wave64 s_and_saveexec_b64 is rejected.
  • Branch: s_cbranch_execz is optional. It must land exactly where the masked block ends, and only s_waitcnt_depctr or s_nop may come between the target and the restore or the exit. The CLI decodes with offsets, and a new labelled() turns each target into a label. The target must be forward and at a decoded instruction start. lower() checks where the label sits.
  • State after the restore: a scalar or vector register written under the guard is unknown afterwards. Lanes that did not pass, or a wave whose block was skipped, keep the old value. A load whose wait ran only under the guard is pending again.
  • s_waitcnt_depctr is a no-op everywhere. hlsl_word() factors out the existing store-data formatting, and the output for the existing cases is unchanged.

No helper from pixel_aot is reused. #651 (open) lowers masked regions in pixel programs to per-lane selects and rejects memory side effects inside them, which is the opposite of what a store guard needs. It also works on wave64 s_and_saveexec_b64.

shader_profile_audit.py is unchanged. It does not bind b0 and does not label branches, so it does not try guarded programs yet. Docs: new subsection "Per-lane guards around compute stores", after "Compute programs with two exits".

Verification

Commit d8840b5 on 761e323. Windows 11 build 26200.9974, D3D12 debug layer enabled, NVIDIA GeForce RTX 3070 (driver 32.0.16.2101) and WARP (10.0.26100.9818).

Fixtures. Both programs are unchanged LLVM 15 output of original amdgpu_cs sources (source and commands below): a 32-bit table pointer and the group X ID as SGPR arguments, a group of 32, u0 at table byte 0, b0 at byte 32, and n = params[0].x.

  • guard_end: if (gid < n) store gid at element gid. The guard stays open to the exit, and LLVM sinks the u0 descriptor load under it. Bindings: --table-reg 0 --descriptor-offset 0 --constant-descriptor 32 --group-reg 1 --stride 4.
  • guard_join: the same guard, then an unguarded store 0x600d at word 1 of the element, so the mask is restored before it. Same bindings with --stride 8.

Emitted HLSL for guard_join:

void main(uint3 tid : SV_DispatchThreadID) {
    if (params[0].x > tid.x) {
        outputData.Store(tid.x * 8u + 0u, tid.x);
    }
    outputData.Store(tid.x * 8u + 4u, 0x0000600du);
}

Binary checks (LLVM 15). tests/compute_store_check.py binary assembles both fixtures, extracts them from a container, and checks that lower(labelled(disassemble(..., offsets=True))) and the CLI give the hand-listed result. It also patches the decoded branch distance in the native code:

  • landing on the s_or_b32 itself, past the hazard wait, is accepted with the same output;
  • landing on the guarded store fails with "Lane guard branch does not reach its restore";
  • landing in the store's second dword fails with "Branch outside decoded instruction boundaries";
  • landing past the restore fails with "Unverified lane guard restore", and past the exit with "Branch outside decoded instruction boundaries".

I don't have llc-15/llvm-mc-15 for AMDGPU on Windows, and the fork's CI did not start runs tonight. I ran the binary mode locally with the official LLVM 15.0.7 Windows build, as on #749: clang 15.0.7 as the assembler (clang -c -x assembler --target=amdgcn--amdpal -mcpu=gfx1013) behind an llvm-mc-style wrapper, llvm-objcopy 15.0.7, and its LLVM-C.dll for disassembly:

python -B tests/compute_store_check.py binary <llvm-mc wrapper> llvm-objcopy.exe LLVM-C.dll
exit 0

The Ubuntu pixel-binary job runs the same command with llvm-mc-15, so CI will run it on this PR.

CPU controls (run before every mode). Exact output for both programs, then:

  • all four compares produce their operator, and an immediate bound becomes a literal;
  • a later compare does not change the guard, a saved mask in another SGPR or in a copy restores it, and a load waited for again after the restore is accepted;
  • without both the restore and the branch, both stores are inside the if, because the mask then holds to the exit.

Rejected, each with its named diagnostic so that a control cannot pass for an unrelated reason:

  • Exec not restored: the restore removed while the branch still targets the block end ("does not reach its restore"), a restore from an SGPR that does not hold the mask, the saved mask overwritten under the guard, a restore from a copy of the mask made only inside the block the branch skips, and a restore with no guard.
  • Branch: a target past the restore or inside the block, a missing label, a label with no branch, a second branch to another label, an unlabelled open guard at the exit, a non-no-op after the label, and s_cbranch_execnz.
  • Compare and mask: no compare, and compares of an unknown, pending, group-ID or table operand. Also rejected: a mask taken from an SGPR instead of vcc_lo, wave64 s_and_saveexec_b64, a nested or second guard, and a guard around no store.
  • State: a vector or scalar register written under the guard and read after the restore, a load waited for only under the guard and used after it, and the saved mask stored as data.
  • labelled(): targets inside an instruction, past the span, backward, or printed as a negative or 16-bit pattern.

Mutation check (local, LLVM 15.0.7 tools as above). Each of 25 single-site mutants of compute_store_aot.py ran the full compute_store_check.py binary in a copy of tools/ and tests/. All 25 were killed. Two are not killed by a rejection assertion. "saveexec without compare" makes the no-compare control crash with a TypeError when the HLSL condition is built. "saved mask not tagged" makes lower() reject the valid fixtures. The others are each killed by a control with its diagnostic or by an exact-output assertion: wrong operator mapping, swapped operands, written registers kept, pending loads not restored, a second guard, restore from any register, a restore before the branch target, a restore from a copy made after the branch, the label name, anything after the label, an unreached label at the exit, an empty guard, the restore ignored in the output, labels inside an instruction, backward or at the branch itself, a condition taken from the last compare, a pending compare operand, the CLI without labels, s_waitcnt_depctr not a no-op, and a non-vcc_lo mask source.

Windows tests (d8840b5, rebuilt):

ctest --preset dev --no-tests=error -R "^(compute_store_aot_|compute_mesh_texture_|compute_to_pixel_|offscreen_warp|compute_|shader_metadata_census|pixel_aot_)" -V
100% tests passed, 0 tests failed out of 48

compute_store_aot_hardware and compute_store_aot_warp each passed 36 full 320-word readbacks, 22 existing and 14 new, all with mismatches=0 and debug_errors=0 debug_warnings=0. The buffer starts at the sentinel 0xc5c5c5c5, and the expected words come from an independent per-lane model. Each guard program runs seven dispatches:

Groups n Covers
1 0 no lane passes, so the branch is taken
1 17 split wave
1 32 whole group
3 1 one lane
3 70 the third group split
3 96 exactly the dispatch
3 200 bound past the dispatch

On 3 groups with n = 70, each of these must fail with "Compute readback differs", and all failed on both adapters:

  • a reference built for n = 69 or n = 71 (first mismatch at the lane on the bound);
  • recompiled HLSL with the guard inverted (!(…)), off by one (>=) or removed;
  • for guard_join, HLSL that keeps the second store under the guard, i.e. exec not restored.

compute_store_aot_hardware took 28.4 s and _warp 5.1 s, against a 45 s timeout. Ten runs elsewhere report debug_warnings=1 (compute_to_pixel_*, pixel_aot_buffer_color_*, pixel_aot_attribute_*). These are the same tests and the same count as on main in #738, and this PR does not touch them.

Pure-Python checks from AGENTS.md (23, including docs_links_check.py, bidi_controls_check.py and pixel_aot_check.py without LLVM): all exit 0.

GPU load during the Windows run (nvidia-smi): 5 % before and 9 % after. About 5.6 GB of 8 GB was already in use by other processes. The tests are short dispatches.

Overlap. Rebased on main after #750 and #754, which changed the same compute files. Their fixtures (llvm_cube, pitch) and every older case lower to the same HLSL, and the same rejections, as on main. No open PR touches tools/compute_store_aot.py or tests/compute_store_check.py. Against all 54 open PRs that touch these files or docs/experiments.md, git merge-tree shows no conflict, and no conflicted file, that main does not already have.

Kernel source and commands
declare i32 @llvm.amdgcn.s.buffer.load.i32(<4 x i32>, i32, i32)
declare void @llvm.amdgcn.struct.buffer.store.i32(i32, <4 x i32>, i32, i32, i32, i32)

define amdgpu_cs void @guard_end(i32 inreg %table, i32 inreg %group, <3 x i32> %lid3) #0 {
entry:
  %t64 = zext i32 %table to i64
  %tp = inttoptr i64 %t64 to ptr addrspace(4)
  %uav = load <4 x i32>, ptr addrspace(4) %tp, align 16, !invariant.load !0
  %cp = getelementptr inbounds i8, ptr addrspace(4) %tp, i32 32
  %cbv = load <4 x i32>, ptr addrspace(4) %cp, align 16, !invariant.load !0
  %n = call i32 @llvm.amdgcn.s.buffer.load.i32(<4 x i32> %cbv, i32 0, i32 0)
  %lid = extractelement <3 x i32> %lid3, i32 0
  %base = shl i32 %group, 5
  %gid = add i32 %base, %lid
  %in = icmp ult i32 %gid, %n
  br i1 %in, label %body, label %end
body:
  call void @llvm.amdgcn.struct.buffer.store.i32(i32 %gid, <4 x i32> %uav, i32 %gid, i32 0, i32 0, i32 0)
  br label %end
end:
  ret void
}
attributes #0 = { "amdgpu-flat-work-group-size"="32,32" }
!0 = !{}

guard_join is the same function with one more call in %end: struct.buffer.store.i32(i32 24589, <4 x i32> %uav, i32 %gid, i32 4, i32 0, i32 0), that is 0x600d at byte 4 of the element.

The local IDs are taken as the <3 x i32> VGPR argument (v0..v2) instead of llvm.amdgcn.workitem.id.x. As noted on #738, reading a local ID from an amdgpu_cs function crashes LLVM 15 in "SI Fix SGPR copies". A 32-bit addrspace(6) table pointer makes LLVM add the b0 offset with s_add_i32 instead of an SMEM immediate offset, so the pointer is zero-extended to addrspace(4).

The listing comes from the LLVM 15.0.7 code generator run on the IR, through clang because the Windows release has no llc:

clang -S --target=amdgcn--amdpal -mcpu=gfx1013 -O2 -x ir guard.ll -o guard.s
clang -S --target=amdgcn--amdpal -mcpu=gfx1013 -O2 -x ir -Xclang -disable-llvm-passes guard.ll -o guard_cg.s

On IR input, clang -O2 also runs the IR optimization pipeline before the code generator. The second command skips it, so it runs only the code generator, as llc-15 -mtriple=amdgcn--amdpal -mcpu=gfx1013 -O2 does. Both listings are identical and match the fixtures line for line.

As a cross-check, the same clang route on the #738 per-lane source reproduces the llc-15 listing from the Ubuntu probe (the LANE_EXIT fixture) instruction for instruction. The only difference is the spelling of a zero SMEM offset, 0x0 instead of null. The guard fixtures keep the clang spelling; lower() accepts both.

Evidence and follow-up

  • Fixtures: original sources written for this test, compiled with LLVM 15 and kept as gfx1013 assembly. MIT. No game files.
  • Assumption: the console compiler masks per-lane bounds the same way. The fixtures show only what LLVM 15 emits. A console program with a different shape still stops at its first unsupported instruction, and nothing new is accepted by default.
  • Not covered: nested or repeated guards, s_cbranch_execnz, wave64, masked ALU whose results are used after the restore, and the audit. The audit needs b0 candidates and branch labels to try guarded programs. I'd do that together with a CS rescan, so that counts stay separate from expected coverage, as for shader: extract two-exit compute programs with the #477 check #738.
  • Next on compute_store_aot: accept two-exit compute programs, then lower a guarded read–compute–write kernel #721: vector reads, then the small ALU subset.

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed.
  • I did not include game files, dumps, distribution links or secrets.

AI-assisted: yes. Code, tests and this description were prepared with an AI coding agent and checked by running the commands above.

LLVM 15 compiles a per-lane bound around a raw-UAV store to v_cmp into
vcc_lo, s_and_saveexec_b32, an optional s_cbranch_execz over the masked
block, and s_or_b32 restoring exec or the exit. The compute store profile
now lowers that form to an HLSL if around the stores issued under the
mask. The CLI labels decoded branch targets, which must land exactly
where the masked block ends, and the restore must read an SGPR that
holds the saved mask on the skipped path too.

Refs R0Y00#721
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants