Skip to content

Recompiler: collapse 1-dword bindless waterfall loops - #3643

Open
Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:pr/waterfall-1dword
Open

Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:pr/waterfall-1dword

Conversation

@Kalmarv

@Kalmarv Kalmarv commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

What is in it

Extends the direct-DXIL waterfall pass (crates/xcl/src/gpu/dxil/waterfall.rs) to collapse 1-dword bindless descriptor-index waterfall loops into straight-line per-lane code alongside the existing 4-dword S# sampler waterfall collapse, unifying both on per-lane V_READFIRSTLANE_B32 lowering.

  • Why: Bindless shaders frequently wrap descriptor-index loads and texture/buffer samples in single or nested (outer sampler + inner texture) V_READFIRSTLANE_B32 / V_CMP(X)_EQ_U32 / S_AND_SAVEEXEC (or S_ANDN2_WREXEC) / S_CBRANCH_EXECNZ waterfall loops. Because direct DXIL already represents SGPRs as per-lane SSA values and lowers dynamic SRSRC/SSAMP accesses through NonUniformResourceIndex heap handles, those loops add unnecessary ballots, quad reads, control-flow branches, and DXIL size.
  • How:
    • Runs an inner-to-outer fixpoint collapse in waterfall::collapse handling both 4-dword S# sampler waterfalls and 1-dword bindless descriptor-index waterfalls (wave32 B32 and wave64 B64, both WREXEC and SAVEEXEC/XOR forms, including nested outer/inner pairs via try_merge_into_outer_header, clearing pc = u64::MAX on emptied merged blocks so PC-based lookups skip them).
    • Keeps collapsed V_READFIRSTLANE_B32 instructions in place as EXEC-masked per-lane copies (lower_valu.rs, sel(act, a, 0)) for both 4-dword S# and 1-dword waterfalls so inactive lanes (EXEC=0) get 0 instead of uninitialized VGPR keys. All four S# words (s[sb..sb+3]) remain valid per lane (including for mimg_gather4_lod), removing Lw::waterfall_ssamp and mimg_s3 in lower_image.rs.
    • Skips waterfall collapse for Entry::Kernel in kernel.rs so store_registers lane-0 register dumps at s_endpgm keep exact HLSL parity.
    • Preserves pre-collapse CFG leaders in kernel.rs so recomp::constant_samplers keeps branch-following even when a collapsed loop strips leading noops or merges an inner block.
    • Excludes collapsed V_READFIRSTLANE_B32 PCs from split-wave64 mask_exchange EXEC demand, may_meet, and lane_read tracking, taints SGPRs derived from collapsed V_READFIRSTLANE_B32s in mask_exchange::known_step and idioms::uniform_reads_with_rfl so post-waterfall VGPR reads are never misclassified as wave-uniform or How::OwnFirst, and adds waterfall_rfl_per_lane to compact.rs block deduplication keys.
    • Refuses collapse on side effects, coherent ENC_SMEM loads (GLC=1 or DLC=1), RMW/loop-carried scalar dependencies (S_ADDK_I32, S_MULK_I32, S_CMOV*, S_BITSET*), ENC_VOP2 OPR_VCC reads/writes (V_CNDMASK_B32, V_ADD/SUB*_CO_CI_U32), upward-exposed SCC or mask_reg/iter_reg reads, invalid ENC_VOP3 compare destinations (EXEC_LO, NULL, M0, or unaligned 64-bit pairs), VOPC VGPR-vs-VGPR compares in match_vcmp_eq_u64, live-out temporaries, or intra-block reads of save_reg/rem_reg in pre[pos+1..].
  • Size note (>800 lines): The diff is +2242/-294 across 8 files (+130/-64 across the 7 wiring files, +2112/-230 in waterfall.rs). Inside waterfall.rs, 1291 lines are unit, DXIL validation, and RTX 5070 Ti GPU parity/regression tests, and 1067 total non-test lines cover the unified 4-dword + 1-dword matcher, liveness/soundness guards, and nested-merge rewriter. Keeping the matcher, soundness guards, wiring, and tests in one commit ensures the pass is never partially wired or missing its guards.

Tested

  • Hardware & toolchain: NVIDIA GeForce RTX 5070 Ti (driver 610.74), AMD Ryzen 9 9950X, Windows 11 Pro 26200, rustc 1.99.0 (b940084d7 2026-09-28), DXC 1.9.2609.5 (debug + release).
  • cargo build --release -p xcl: clean (39 warnings — identical to origin/main 5eaadb54c, 0 new warnings).
  • scripts/test.ps1 (cargo build --workspace, cargo bench -p xcl --bench '*' -- --test, cargo test --workspace -- --test-threads=4, with XCL_DXC_DIR set to DXC 1.9.2609.5): 2982 passed, 0 failed, 52 ignored across 43 test targets (24 SKIPPED GPU tests on this adapter: 22 no wave64, 2 no heap windows).
  • Waterfall tests in gpu::dxil::waterfall::tests (11/11 passing, 0 skipped):
    • collapses_sampler_waterfall_self_loop_and_preserves_s3_vgpr
    • refuses_collapse_when_waterfall_sgpr_is_live_out
    • collapsed_waterfall_translates_and_validates_direct_dxil
    • collapses_nested_1dword_bindless_waterfall_pair
    • refuses_1dword_collapse_on_loop_carried_accumulator_or_live_out_sgpr (accumulator and live-out SGPR refusal)
    • collapses_1dword_saveexec_xor_and_wave32_b32_forms (wave64 SAVEEXEC/XOR + FallExec::Ends, Entry::Kernel skip for register-dump parity, jump-hop fallthrough exit, wave32 B32 WREXEC + GLOBAL_LOAD_DWORD under ENC_FLAT_GLBL, wave32 B32 SAVEEXEC/XOR)
    • refuses_1dword_collapse_on_soundness_edge_cases (GLC/DLC SMEM, V_CNDMASK_B32/V_ADD_CO_CI_U32 OPR_VCC, RMW S_ADDK_I32/S_CMOV_B32, iter_reg read, upward-exposed SCC read, unaligned/EXEC_LO V_CMP_EQ_U32 SDST, VOPC VGPR-vs-VGPR V_CMP_EQ_U64 refusal, intra-block save_reg read in pre[pos+1..], and pc == u64::MAX on emptied merged blocks when the outer loop refuses collapse)
    • split_wave64_post_waterfall_readfirstlane_is_not_uniform_or_own_first (proves mask_exchange::known_step and idioms::uniform_reads_with_rfl do not classify post-waterfall v_readfirstlane_b32 reads of VGPRs loaded/moved from per-lane waterfall SGPRs as How::OwnFirst or uniform_reads, and that split-wave64 DXIL emits a cross-half barrier)
    • gpu_nested_1dword_bindless_waterfall_matches_uncollapsed (renders 8 distinct 2x1 textures × 2 CLAMP/WRAP samplers across an 8x8 RT on RTX 5070 Ti with x==0 pixels masked to EXEC=0 and garbage 0x7FFF_FFE0 keys; bit-for-bit identical to uncollapsed with 0 quadReadLaneAt and 0 waveReadLaneFirst)
    • gpu_4dword_sampler_waterfall_gather4_lod_uses_all_four_words (renders a collapsed 4-dword S# waterfall with IMAGE_GATHER4_L where lanes share S# word 3 = 0 and differ only in S# word 0 CLAMP vs WRAP; bit-for-bit identical to uncollapsed with 0 quadReadLaneAt and 0 waveReadLaneFirst)
    • gpu_static_sampler_retained_across_collapsed_waterfall_and_branch (2x1 texture at u=1.25, static CLAMP vs heap slot 0 WRAP across a collapsed waterfall + zero-offset s_branch; verified it fails with 0 static bindings when post-collapse leaders are rebuilt and passes with 1 static binding and red 22.0 across all 16 pixels with the fix).

Regression run

Baseline (main):

xcl-smoke v1
commit: 5eaadb54c14e0fc29597b2a1689d7dbd83491303
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1392 (PresentX 1392)
presents per 2 s (last 3): 60 61 60
device removals: 0
crashes: 0
peak commit: 16644 MB

PR head:

xcl-smoke v1
commit: e56629641c05c6f372864d72f36c8afdd1914a35
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1647 (PresentX 1647)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 16176 MB

Not tested

  • AMD and Intel GPUs, including native wave64 hardware paths (22 wave64 GPU tests skipped on RTX 5070 Ti).
  • Opt-in XCL_HEAP_WINDOWS=1 GPU tests (2 skipped under default scripts/test.ps1).
  • Multi-minute in-world frame-time benchmarks beyond the 60 s title smoke run.

AI use

  • Antigravity (Gemini 4 Neon) rebased the branch onto origin/main (5eaadb54c), implemented all review fixes across waterfall.rs, kernel.rs, lower.rs, lower_image.rs, lower_valu.rs, mask_exchange.rs, idioms.rs, and compact.rs, added the unit and GPU regression tests, ran the build/test/smoke checks, and updated this description.

@github-actions github-actions Bot added area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) labels Dec 2, 2026
@Decodere

Decodere commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Diff review (head a28f48f69, read-only code review — not a #3041 merge-check):

Strong perf/memory win on bindless waterfall collapse, and the compact.rs, mask_exchange.rs, and lower_valu.rs wiring looks clean. Reading the full diff in crates/xcl/src/gpu/dxil/waterfall.rs turned up 5 soundness edge cases worth fixing before merge:

  1. Split-wave64 GLC=1 / DLC=1 SMEM loads corrupt upper-half lanes 32..63 (crates/xcl/src/gpu/dxil/waterfall.rs:442):
    is_pure_waterfall_body_inst admits all S_LOAD_DWORD* / S_BUFFER_LOAD_DWORD* without rejecting GLC=1 or DLC=1. In crates/xcl/src/gpu/dxil/lower_mem.rs:1295-1303, if self.split && coherent exchanges lane 0–31's loaded values into lanes 32–63 assuming the load is wave-uniform. Once collapsed, s_key is per-lane, so coherent SMEM loads in split-wave64 compute/mesh silently overwrite lanes 32–63 with lanes 0–31's values. Rejecting GLC == 1 || DLC == 1 in ENC_SMEM inside is_pure_waterfall_body_inst closes this.

  2. ENC_VOP2 OPR_VCC operands (V_CNDMASK_B32, V_ADD_CO_CI_U32, V_SUB_CO_CI_U32, V_SUBREV_CO_CI_U32) are invisible to scalar_uses_defs (crates/xcl/src/gpu/dxil/waterfall.rs:128, :495):
    In rdna2_spec.rs, these ENC_VOP2 instructions encode OPR_VCC with field: None, implicit: false. rdna2::sgpr_uses skips field: None (rdna2.rs:550) and scalar_uses_defs only inspects o.implicit, so both suses and sdefs come back empty. That lets carry-in/out ops pass sdefs.is_empty() (waterfall.rs:495) and hides VCC reads/writes from scalar_live_in (so Style 2 deleting V_CMP_EQ_U32 vcc, ... feeds stale VCC to V_CNDMASK_B32 / carry-in ops and misses clobbering live-out VCC). Scanning all operands with o.field.is_none() (not just o.implicit) for VCC/SCC/EXEC fixes both.

  3. Read-modify-write scalar ops (S_ADDK_I32, S_MULK_I32, S_CMOVK_I32, S_CMOV_B32, S_CMOV_B64) bypass the loop-carried accumulator check (crates/xcl/src/gpu/dxil/waterfall.rs:128, :460):
    In rdna2_spec.rs, SDST on these instructions has input: false, output: true, so rdna2::sgpr_uses records SDST only in sdefs, not suses. Since is_pure_waterfall_body_inst allows ENC_SOPK and ENC_SOP1 (waterfall.rs:460), a loop-carried accumulator like S_ADDK_I32 s8, 1 does not appear in upward_used_scalars and collapses into a single iteration. Treating SDST on these RMW ops as both read and written in scalar_uses_defs (or rejecting them in is_pure_waterfall_body_inst) prevents this.

  4. Style 2 omits mask_reg, iter_reg, and SCC_REG from is_forbidden_reg / s_key overlap checks (crates/xcl/src/gpu/dxil/waterfall.rs:267, :747, :781-820):

    • is_forbidden_reg checks EXEC and rem_reg (Style 1), but omits Style 2's iter_reg and mask_reg (unlike try_collapse_4dword_sampler), allowing body ops to read/write iter_reg or read mask_reg set by the deleted V_CMP_EQ_U32, or mask_reg/iter_reg to overlap s_key.
    • match_vcmp_eq_u32 (waterfall.rs:267) does not reject ENC_VOP3 SDST == EXEC_LO (126) / NULL (125) or unaligned 64-bit pairs.
    • Neither Style 1 nor Style 2 refuses when upward_used_scalars contains SCC_REG (e.g. S_CSELECT_B32/S_ADDC_U32/S_CMOV_*), even though deleting S_AND_SAVEEXEC / S_ANDN2_WREXEC changes SCC seen by the body from 1 back to the pre-loop value.
  5. try_merge_into_outer_header deletes s_mov s[save/rem], exec in pre without checking intra-block reads in pre[pos+1..] (crates/xcl/src/gpu/dxil/waterfall.rs:402, :900-930):
    find_tail_save_from_exec checks that nothing in pre[pos+1..] writes reg or EXEC, and is_dead_after_pre checks only post_live[b] (after pre). If an instruction in pre[pos+1..] reads save_reg or rem_reg, deleting the s_mov leaves that read undefined. Checking that pre[pos+1..] has no reads of reg..reg+width fixes this.

Minor note: is_pure_waterfall_body_inst (waterfall.rs:456) checks n.starts_with("GLOBAL_LOAD_") under "ENC_FLAT", whereas GLOBAL_LOAD_* uses "ENC_FLAT_GLBL" (conservative only — misses matches rather than miscompiling).

AI use: Antigravity (Gemini 4 Neon) audited the full diff against main and drafted this review.

@Foniass

Foniass commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Review (head a28f48f, diff read, not a merge-check):

  • Static samplers lose branch following in any VS/PS with a collapsed loop. kernel.rs ~330 now rebuilds leaders from the blocks after waterfall::collapse, and only constant_samplers (kernel.rs ~797) uses it. That analysis reads the original linear cfg.insts, where the removed s_cbranch_execnz is still there. A 4-dword collapse removes the loop head (the first v_readfirstlane) from the block, and a nested merge empties b. Either way the branch target is no longer a leader, at.get(&t)? (recomp/mod.rs ~1863) returns None for the whole program, and it falls back to reading block by block. A static S# set before the loop and sampled in a later block then goes through the heap at word3 & 0x7FF, so the wrong sampler is used. On main the leaders come from before the collapse. Keeping those (dropping the second let leaders) avoids this.
  • The 4-dword path keeps the stale-S# bug that Recompiler: read the whole per-lane S# in collapsed sampler waterfalls #3663 fixes, and the two PRs conflict on the map's meaning. try_collapse_4dword_sampler still removes the four v_readfirstlane and records only vb + 3 (waterfall.rs ~605), and this PR leaves lower_image.rs unchanged. So mimg_gather4_lod still reads S# words 0-2 from the SGPRs nothing writes anymore (lower_image.rs ~513), and gathers stay allowed in the body (~445). Recompiler: read the whole per-lane S# in collapsed sampler waterfalls #3663 changes the value to vb and reads v[vb+k]. If this PR lands after Recompiler: read the whole per-lane S# in collapsed sampler waterfalls #3663 without switching to vb, every collapsed sampler reads v[vb+3+k], word 3 (the heap index) included. A simpler fix is to do what the 1-dword path already does: keep the four v_readfirstlane as per-lane copies, so s[sb..sb+3] are right per lane and ssamp_vgpr is no longer needed.
  • The 1-dword body check misses values that came from the loop head. In the SAVEEXEC/XOR form, the v_cmp_eq_u32 and s_and_saveexec are dropped. A body instruction that reads mask_reg (often VCC, e.g. v_cndmask_b32), iter_reg or SCC passes is_pure_waterfall_body_inst, and upward_used_scalars is compared only with the body's own definitions (waterfall.rs ~830). After the collapse that instruction reads the value from before the loop. Separately, a GLC s_load is accepted (~442), but in split wave64 smem gives the upper half the lower half's values through one slot per half (lower_mem.rs ~1297). That is wrong once the address depends on the per-lane key.
  • Tests cover one shape only. All the new tests use the wave64 WREXEC form. Nothing covers the SAVEEXEC/XOR form, the B32 (wave32) forms, the FallExec::Ends/jump-hop exits, or refusal when a temporary is live out. refuses_1dword_collapse_on_loop_carried_accumulator_or_live_out_sgpr tests only the accumulator.
  • Size. +1209/-207 in one commit. The description says it cannot be split, but it contains separable parts: the compact.rs key fix for the collapse already on main (Recompiler: read the whole per-lane S# in collapsed sampler waterfalls #3663 has the same fix), the rewrite of the 4-dword matcher, the single-loop 1-dword collapse, and the nested merge that rewrites the CFG (try_merge_into_outer_header). The single-loop collapse works and can be tested without the merge.
  • AI use. The commit trailer names Gemini 3.1 Pro, and the description names "Gemini 4 Neon".

Fine: dynamic T#/S# heap handles are already created with NonUniformResourceIndex (lower_image.rs), and SMEM addresses go through per-lane window selection, so a per-lane key gives a correct per-lane descriptor. The EXEC entry state is checked (preheader_inits_reg_from_exec). Cross-lane VALU, writes and LDS are rejected. Collapsed v_readfirstlane is now part of the compact key, and mask_exchange no longer counts it as an EXEC reader.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

@Foniass

Foniass commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: 1c8b551
head: a28f48f
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2912 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: read by one reviewer at this same head; the review is at #3643 (comment) and its findings stand. Most serious: rebuilding leaders after the collapse breaks branch following in constant_samplers, so the wrong static sampler can be used.
performance: 60 s smoke of a retail title, main 1c8b551 vs this merge (a28f48f): 1652 -> 1685 frames shown (101 %; last presents per 2 s: 60 60 60), peak commit 18228 -> 16136 MB, 0 device removals, 0 crashes.
verdict: not yet: rebuilding leaders after the collapse breaks branch following in constant_samplers, so the wrong static sampler can be used (see the review)
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

@Gevroska

Gevroska commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

I reproduced the static-sampler issue on an RTX 3080. I ran the same synthetic pixel shader on base 1c8b5514 and PR head a28f48f6. It samples a two-texel texture at u = 1.25: the static clamp sampler returns red 22, while heap slot zero uses wrap and returns 11. I waited for the GPU fence and read back all 16 pixels.

Shader case Base 1c8b5514 PR head a28f48f6
No-waterfall control 1 static binding, red 22 1 static binding, red 22
One waterfall iteration followed by a zero-offset branch 1 static binding, red 22 0 static bindings, red 11

All 16 pixels agreed in each case. The head drops the static binding and samples the wrap texel. Both test processes passed because the fixture checks the pixel value expected from the binding it observes. For a regression test, I’d assert that this shader retains its static binding and returns 22.

This covers the uniform, single-iteration case on driver 32.0.16.1692. I didn’t test divergent loops or retail game rendering. OpenAI Codex GPT-6 Sol (Daybreak) wrote and ran the GPU fixture, a separate GPT-6 Sol agent reviewed the source and logs, and GPT-6.2 Sol verified the saved results. GPT-6.2 Astra drafted this comment.

I reviewed and approved this comment before posting.

@Kalmarv
Kalmarv force-pushed the pr/waterfall-1dword branch from a28f48f to 9c903a2 Compare December 2, 2026 14:47
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (5eaadb54c) and updated to 9c903a2e7, addressing all points from @Gevroska, @Foniass, and @Decodere:

  1. Static-sampler leaders regression (@Foniass, @Gevroska): Dropped the second let leaders after waterfall::collapse in crates/xcl/src/gpu/dxil/kernel.rs so recomp::constant_samplers keeps pre-collapse CFG leaders and branch following. Added gpu_static_sampler_retained_across_collapsed_waterfall_and_branch (2x1 texture at u = 1.25, static CLAMP vs heap slot 0 WRAP across a collapsed waterfall + zero-offset s_branch, asserting 1 static binding and red 22.0 across all 16 pixels) — verified it fails (0 static bindings) with post-collapse leaders restored and passes with the fix.
  2. 4-dword S# stale words 0–2 / #3663 conflict (@Foniass): Updated try_collapse_4dword_sampler to keep all four V_READFIRSTLANE_B32 instructions as per-lane copies (rfl_per_lane), matching the 1-dword path so s[sb..sb+3] stay valid per lane (including for mimg_gather4_lod). Removed Lw::waterfall_ssamp and mimg_s3 (lower.rs, lower_image.rs, compact.rs).
  3. Soundness edge cases (@Decodere, @Foniass):
    • Rejected GLC == 1 || DLC == 1 on ENC_SMEM loads in is_pure_waterfall_body_inst and try_collapse_4dword_sampler.
    • Updated scalar_uses_defs to inspect all o.field.is_none() operands (not only o.implicit) for VCC/SCC/EXEC (fixing ENC_VOP2 V_CNDMASK_B32 and V_ADD/SUB*_CO_CI_U32) plus inline VCCZ/EXECZ/SCC codes.
    • Treated RMW scalar SDST ops (S_ADDK_I32, S_MULK_I32, S_CMOVK_I32, S_CMOV_B32, S_CMOV_B64, S_BITSET*) as both read and written in scalar_uses_defs.
    • Added mask_reg, iter_reg, and EXEC_HI to is_forbidden_reg, refused upward-exposed SCC_REG reads, and validated match_vcmp_eq_u32/match_vcmp_eq_u64/iter_reg/mask_reg against M0/NULL/EXEC and unaligned 64-bit pairs.
    • Checked pre[pos+1..] for intra-block reads of save_reg/rem_reg (has_read_in_tail) before deleting s_mov in try_merge_into_outer_header, and added "ENC_FLAT_GLBL" for GLOBAL_LOAD_*.
    • Rebased cleanly with #3655 in mask_exchange.rs, excluding rfl_per_lane from uses, may_meet, and lane_read as well as checking waterfall_rfl_per_lane first in lower_valu.rs.
  4. Tests, size note, and AI attribution (@Foniass): Added tests for wave64 SAVEEXEC/XOR + FallExec::Ends, wave32 B32 forms + GLOBAL_LOAD_DWORD, live-out SGPR refusal, all 5 soundness edge cases, and the static-sampler GPU regression test. Updated the commit trailer (Assisted-by: Antigravity (Gemini 4 Neon)) and PR AI use consistently, and updated the size rationale and fresh 60 s smoke pair (5eaadb54c vs 9c903a2e7) in the PR description.

AI-written reply (Antigravity, Gemini 4 Neon).

@github-actions github-actions Bot added needs-pr-check Failing the PR description check (CONTRIBUTING.md) and removed needs-pr-check Failing the PR description check (CONTRIBUTING.md) labels Dec 2, 2026

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of 9c903a2e: 3 finding(s) (1 critical, 1 high, 1 medium), most severe first.

  1. Critical crates/xcl/src/gpu/dxil/lower_valu.rs:1057: Not certain about this one: a collapsed v_readfirstlane_b32 is lowered as a per-lane copy for every lane, including lanes with EXEC=0, while scalar SMEM loads and descriptor-heap index math aren't EXEC-guarded. (inline)
  2. High crates/xcl/src/gpu/dxil/waterfall.rs:286: see below.
  3. Medium crates/xcl/src/gpu/dxil/waterfall.rs:389: FallExec::Ends and scalar_live_in (Term::End => empty) assume no scalar register is observable at program end, but for Entry::Kernel store_registers (kernel.rs:1104) dumps EXEC, VCC and every touched SGPR from lane 0 after the pr.... (inline)

On lines outside the diff:

  1. High crates/xcl/src/gpu/dxil/waterfall.rs:286: In match_vcmp_eq_u64 (used for the 4-dword match), the swapped-operand test (s1 == s_base && s0 == 256 + v_base) also applies to VOPC, where VSRC1 is a raw VGPR index, so a VGPR-vs-VGPR compare is accepted as the S#-vs-VGPR waterfall compare. After v_readfirstlane s[8..11], v[85..88], a VOPC v_cmp_eq_u64 vcc, v[85:86], v[8:9] (SRC0=256+85, VSRC1=8) matches sb=8, vb=85. That loop isn't a waterfall over s[8..11], yet it's collapsed to one pass and the iterations the compare controlled are dropped. Checking the encoding (VOPC's VSRC1 is a VGPR, not an SGPR) before accepting the swapped form would fix it.

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

}
"v_readfirstlane_b32" => {
// Collapsed waterfall: SGPRs are already per-lane SSA values.
if self.waterfall_rfl_per_lane.contains(&self.pc) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Critical: Not certain about this one: a collapsed v_readfirstlane_b32 is lowered as a per-lane copy for every lane, including lanes with EXEC=0, while scalar SMEM loads and descriptor-heap index math aren't EXEC-guarded. Inactive lanes now compute descriptors from their own, possibly uninitialized, v_key instead of the first active lane's valid key. In a pixel or compute wave with EXEC narrowed before the waterfall (killed, helper or never-launched lanes whose v_key VGPR was never written), those lanes run s_load_dwordx8 s[t], s[base], s_key with a garbage offset and build a NonUniformResourceIndex from a garbage descriptor. Before, the real readfirstlane gave every lane an active lane's in-range key. The result is an out-of-range heap index: undefined behaviour and possible device removal. Selecting the key from an active lane for inactive lanes (or keeping the readfirstlane for them) would avoid it.

}
match blk.term {
Term::Jump(next) if next != cur => cur = next,
Term::End => return Some(FallExec::Ends),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: FallExec::Ends and scalar_live_in (Term::End => empty) assume no scalar register is observable at program end, but for Entry::Kernel store_registers (kernel.rs:1104) dumps EXEC, VCC and every touched SGPR from lane 0 after the program. In a kernel-mode program whose waterfall falls straight through to s_endpgm, the uncollapsed dump shows EXEC=0 and s_key/rem as of the last iteration, while the collapsed one shows EXEC = the entry mask, rem = the initial exec and s_key = lane 0's own key. Kernel-mode register dumps of such shaders then diverge from the HLSL path. Treating the dumped registers as live at End for kernels would keep them equal.

@bmjask

bmjask commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.

@Foniass

Foniass commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: 5eaadb5
head: 9c903a2
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2980 passed, 0 failed, 52 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: follow-up on 9c903a2 (reworked and rebased from a28f48f, my last review's head). Still one commit, now +1783/-263. The 4-dword S# path now keeps its four v_readfirstlane as per-lane copies like the 1-dword path, so Lw::waterfall_ssamp / mimg_s3 are gone and lower_image.rs reads s[ssamp..ssamp+3] (~506, ~701, ~1251, ~1436); kernel.rs no longer rebuilds leaders after the collapse; the 1-dword matcher gained more refusals and tests; AI use names the model. Earlier findings: (1) static samplers losing branch following: fixed; leaders comes from the CFG before the collapse again (kernel.rs ~341), covered by gpu_static_sampler_retained_across_collapsed_waterfall_and_branch. (2) stale S# words 0-2 in the 4-dword path: fixed in the code (try_collapse_4dword_sampler keeps active[..4], waterfall.rs ~752), but open #3663 fixes the same bug another way and a test merge of the two heads conflicts in compact.rs, lower.rs, lower_image.rs and waterfall.rs; and no test checks the result (collapses_sampler_waterfall_self_loop_and_preserves_s3_vgpr only checks the returned PC set; nothing covers a gather or S# words 0-2 after a collapse). (3) loop-head values in the 1-dword body: fixed; mask_reg, iter_reg, rem_reg and EXEC are refused (~857), an upward-exposed SCC read is refused (~906), GLC/DLC SMEM is refused (~497), with tests. (4) tests: partly fixed; SAVEEXEC/XOR, wave32 B32, FallExec::Ends, the live-out refusal and edge cases are covered, plus a GPU parity test of the nested pair (wave64 without split, NVIDIA only); the jump-hop exit in find_fallthrough_exec_restore (~362) and the 4-dword gather case are untested. (5) size: still open and grown: one commit with about 860 non-test lines bundling four parts that could be separate PRs (the 4-dword S# fix, i.e. the #3663 duplicate; the rewritten 4-dword matcher; the single-loop 1-dword collapse; and the nested-merge CFG rewrite in try_merge_into_outer_header, ~965-1063). New: when the outer loop can't be collapsed, try_merge_into_outer_header still deletes the inner s_mov exec, s[save] and merges three blocks into pre (sound given its checks), but leaves empty, unreachable blocks that keep their pc in cfg.blocks, which pc lookups such as idioms::entry_at still see; no test covers a merge without an outer collapse. The 1-dword collapse is on by default for every title (off with XCL_WATERFALL_COLLAPSE=0); split wave64 is checked only by DXIL validation, and AMD / wave64 hardware wasn't tested. Fine: a per-lane v_readfirstlane is excluded from the mask-exchange EXEC demand, may_meet and lane_read and is part of the compact key; RMW SOPK / CMOV / BITSET count as reads; live-out temporaries and save_reg clobbers are refused; the XOR form can't change EXEC after the restore.
performance: 60 s smoke of a retail title, main 5eaadb5 vs this merge (9c903a2): 1422 -> 1659 frames shown (116 %; last presents per 2 s: 61 60 60), peak commit 17184 -> 16369 MB, 0 device removals, 0 crashes.
verdict: not yet: the 4-dword S# fix duplicates open #3663 (they conflict) and has no test that checks the result, bundled with the new 1-dword / nested collapse in one ~1780-line commit that could be split (see the review)
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

@Kalmarv
Kalmarv force-pushed the pr/waterfall-1dword branch from 9c903a2 to 6f6cbd3 Compare December 2, 2026 18:24
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Updated to 6f6cbd380 addressing all findings from @bmjask and @Foniass:

  1. Inactive lanes (EXEC=0) in collapsed v_readfirstlane_b32 (@bmjask, Critical): Masked the per-lane copy with self.act() (lower_valu.rs: sel(act, a, 0)) so lanes with EXEC=0 receive 0 instead of uninitialized VGPR keys, and tightened safe_tw0 in lower_image.rs from sel(valid, tw0, 0) to sel(run, tw0, 0) (run = act && valid) so inactive lanes in implicit-LOD pixel samples and get_lod always index null SRV slot 0. Extended gpu_nested_1dword_bindless_waterfall_matches_uncollapsed to mask x==0 pixels to EXEC=0 with garbage 0x7FFF_FFE0 keys and verify bit-for-bit parity with uncollapsed output.
  2. VOPC VGPR-vs-VGPR compare in match_vcmp_eq_u64 (@bmjask, High): Restricted ENC_VOPC in match_vcmp_eq_u64 (waterfall.rs) to the non-swapped SRC0 == s_base && VSRC1 == v_base form (since VSRC1 is always a raw VGPR index), keeping the swapped form only for ENC_VOP3. Added a regression test rejecting v_cmp_eq_u64 vcc, v[85:86], v[8:9] (SRC0=256+85, VSRC1=8).
  3. Entry::Kernel register-dump parity at s_endpgm (@bmjask, Medium): Skipped waterfall::collapse when kernel (Entry::Kernel) in kernel.rs so store_registers dumps of EXEC, VCC, SCC, and touched SGPRs remain exact with the HLSL path, and added a test checking that Entry::Kernel stays uncollapsed while Entry::Compute collapses.
  4. 4-dword S# gather test, jump-hop exit test, emptied block PCs, and #3663 (@Foniass):
    • Added gpu_4dword_sampler_waterfall_gather4_lod_uses_all_four_words: a GPU parity test on a collapsed 4-dword S# waterfall with IMAGE_GATHER4_L (mimg_gather4_lod) where lanes share S# word 3 = 0 and differ only in S# word 0 (CLAMP vs WRAP), asserting 0 quadReadLaneAt/0 waveReadLaneFirst and bit-for-bit parity with uncollapsed output.
    • Added a test for the jump-hop fallthrough exit (s_nop; s_branch -> s_mov_b64 exec, s[32:33]) in collapses_1dword_saveexec_xor_and_wave32_b32_forms.
    • Cleared cfg.blocks[b].pc = u64::MAX and cfg.blocks[fallthrough].pc = u64::MAX in try_merge_into_outer_header so PC lookups (idioms::entry_at) skip emptied blocks, with a test covering a merged inner loop whose outer loop refuses collapse.
    • Re #3663: this PR includes the unified per-lane rfl_per_lane 4-dword S# fix (so it supersedes #3663; if #3663 lands first, I can rebase cleanly onto it).

Re-verified on 6f6cbd380 (RTX 5070 Ti, DXC 1.9.2609.5): cargo build --release -p xcl clean (39 warnings, 0 new), scripts/test.ps1 2981 passed, 0 failed, 52 ignored (24 SKIPPED: 22 no wave64, 2 no heap windows), and fresh 60 s smoke (1392 -> 1697 frames shown, 60 61 63 presents/2s, 16644 -> 16007 MB peak commit, 0 removals, 0 crashes).

AI-written reply (Antigravity, Gemini 4 Neon).

@Kalmarv Kalmarv closed this Dec 2, 2026
@Kalmarv Kalmarv reopened this Dec 2, 2026

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of 6f6cbd38: 3 finding(s) (2 high, 1 medium), most severe first.

Re-review at 6f6cbd38. The three findings from the 9c903a2e review (inactive lanes using their own v_key after the collapse, the VOPC swapped-operand match, kernel-mode register dumps at End) weren't flagged again at this head and look addressed. The findings below are new, and the first, second and fourth come from the changes made to address them.

  1. High crates/xcl/src/gpu/dxil/mask_exchange.rs:526: see below.
  2. High crates/xcl/src/gpu/dxil/lower_image.rs:1158: safe_tw0 changed from sel(valid, tw0, 0) to sel(run, tw0, 0) for every image op, not only collapsed waterfalls, so in the unguarded implicit-LOD paths (unorm_body / sample_body / get_lod) lanes outside EXEC now use heap slot .... (inline)
  3. Medium crates/xcl/src/gpu/dxil/waterfall.rs:1007: see below.

On lines outside the diff:

  1. High crates/xcl/src/gpu/dxil/mask_exchange.rs:526: After a collapse, SGPRs written in the waterfall body hold a different value in each lane, but the split-wave64 known_step still treats a VALU or buffer load with no VGPR inputs, run under the launch EXEC, as giving one value in every lane (k.all). A later v_readfirstlane of that VGPR is then lowered as How::OwnFirst, where each 32-lane half reads its own first lane. Take a wave64 split compute shader with full EXEC and a top-level 1-dword waterfall s_load_dwordx4 s[8:11], s[0:1], s_key; buffer_load_dword v5, off, s[8:11], 0, followed after the loop by v_readfirstlane_b32 s9, v5. Before the collapse, the V_CMPX narrowed EXEC, so v5 wasn't 'known'. Now v5 lands in k.all, and the upper half gets its own first lane's v5 instead of console lane 0's, so the result is wrong whenever the keys differ between the halves. rfl_per_lane is threaded through the exchange helpers but not through known_step.

  2. Medium crates/xcl/src/gpu/dxil/waterfall.rs:1007: try_merge_into_outer_header deletes the fallthrough's s_mov exec, s[save] and merges pre + b + fallthrough into one block, but idioms::uniform_reads resets its uniform-VGPR set only per block and on EXEC writes. So VGPRs computed in the collapsed body from per-lane SGPRs now look uniform to a later v_readfirstlane in the merged block. In a nested waterfall where the collapsed inner body does v_mov_b32 v5, s_t0 and the inner fallthrough later has v_readfirstlane_b32 s9, v5, the read lands in uniform_reads. In split wave64, read_first_lane_uniform then reads each half's own first lane, so the upper half gets its own per-key value instead of the wave's first lane's.


These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

Comment thread crates/xcl/src/gpu/dxil/lower_image.rs Outdated
let run = self.land(act, valid);
let z0 = self.c(0);
let safe_tw0 = self.sel(valid, tw0, z0);
let safe_tw0 = self.sel(run, tw0, z0);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: safe_tw0 changed from sel(valid, tw0, 0) to sel(run, tw0, 0) for every image op, not only collapsed waterfalls, so in the unguarded implicit-LOD paths (unorm_body / sample_body / get_lod) lanes outside EXEC now use heap slot 0 instead of the shader's own valid, wave-uniform T#. For a non-waterfall UNORM image_sample inside a divergent branch in a pixel shader, the inactive lanes of a quad take slot 0's dimensions, so their normalized coords are u/dims0 while active lanes use u/dimsA. The quad derivatives, and so the active pixels' mip/LOD, come out wrong. On the non-UNORM path, if slot 0 is a different resource type than kind (e.g. Texture3D vs Texture2D), those lanes access a mismatched descriptor, which is undefined behaviour and can hang some drivers. Limiting the run select to collapsed waterfalls would keep the old behaviour elsewhere.

Extend the direct-DXIL waterfall pass to collapse 1-dword bindless descriptor-index waterfall loops (single loops and nested outer/inner pairs, wave32 and wave64, both WREXEC and SAVEEXEC/XOR forms) into straight-line per-lane code alongside the existing 4-dword S# sampler waterfall collapse.

Both 4-dword S# and 1-dword bindless waterfalls keep their V_READFIRSTLANE_B32 instructions lowered as EXEC-masked per-lane copies (inactive lanes receive 0 instead of uninitialized VGPR keys), are excluded from split-wave64 mask_exchange EXEC/meet/lane-read tracking, taint SGPRs derived from collapsed V_READFIRSTLANE_B32s in mask_exchange::known_step and idioms::uniform_reads so post-waterfall VGPR reads are not misclassified as wave-uniform, and participate in compact block deduplication keys while preserving pre-collapse CFG leaders for constant_samplers branch following. Entry::Kernel skips collapse so lane-0 register dumps at s_endpgm remain exact.

Refuse collapse on side effects, coherent (GLC/DLC) SMEM loads, RMW/loop-carried scalar dependencies, upward-exposed SCC/VCC/mask/iter reads, invalid or VOPC VGPR-vs-VGPR compare encodings, or live-out temporaries, and clear PCs on emptied merged blocks.

Assisted-by: Antigravity (Gemini 4 Neon)
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Updated to e56629641 addressing all three findings from @bmjask's re-review of 6f6cbd38:

  1. mask_exchange::known_step uniformity tracking across collapsed waterfalls (High): Added non_uniform_sgpr: u128 to Known (mask_exchange.rs), threaded rfl_per_lane through known/known_step, tainted SGPRs written by collapsed v_readfirstlane_b32s and propagated taint through scalar ops/loads (including RMW scalar SDST ops), and gated same (VALU and BUFFER_LOAD_DWORD) plus How::LaneBit scalar checks on !reads_non_uniform. Post-waterfall v_readfirstlane_b32 reads of VGPRs loaded through per-lane descriptors are no longer misclassified as How::OwnFirst.
  2. safe_tw0 in lower_image.rs:1158 (High): Reverted safe_tw0 back to self.sel(valid, tw0, z0) so non-waterfall implicit-LOD pixel samples and get_lod preserve exact quad-derivative and descriptor behavior on inactive lanes (collapsed waterfalls remain guarded by sel(act, a, 0) on v_readfirstlane_b32 in lower_valu.rs and self.guarded(run, ...) on non-implicit-LOD image ops).
  3. idioms::uniform_reads after try_merge_into_outer_header (Medium): Added idioms::uniform_reads_with_rfl(cfg, rfl_per_lane) (idioms.rs), tracking non_uniform_sgprs: u128 through collapsed v_readfirstlane_b32s and scalar ops/loads so VGPRs derived from per-lane waterfall SGPRs in merged blocks are not marked uniform for later v_readfirstlane_b32 reads.
  4. Tests: Added split_wave64_post_waterfall_readfirstlane_is_not_uniform_or_own_first in waterfall.rs covering both the s_load_dwordx4 + buffer_load_dword -> v_readfirstlane_b32 (known_step + split-wave64 DXIL cross-half barrier) and nested merged-block v_mov_b32 v5, s_t0 -> v_readfirstlane_b32 (uniform_reads_with_rfl) cases.

Re-verified on e56629641 (RTX 5070 Ti, DXC 1.9.2609.5): cargo build --release -p xcl clean (39 warnings, 0 new), scripts/test.ps1 2982 passed, 0 failed, 52 ignored (24 SKIPPED: 22 no wave64, 2 no heap windows), and fresh 60 s smoke (1392 -> 1647 frames shown, 60 60 60 presents/2s, 16644 -> 16176 MB peak commit, 0 removals, 0 crashes).

AI-written reply (Antigravity, Gemini 4 Neon).

@Kalmarv
Kalmarv force-pushed the pr/waterfall-1dword branch from 6f6cbd3 to e566296 Compare December 2, 2026 19:05
@Kalmarv Kalmarv closed this Dec 2, 2026
@Kalmarv Kalmarv reopened this Dec 2, 2026
@Kalmarv Kalmarv closed this Dec 2, 2026
@Kalmarv Kalmarv reopened this Dec 2, 2026
@github-actions github-actions Bot added the needs-1st-check Passes gates; needs first independent merge-check (#3041) label Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) needs-1st-check Passes gates; needs first independent merge-check (#3041)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants