Recompiler: a wave64 compute program folds into one 32-lane wave #3562

Open
Royalflamejlh wants to merge 6 commits from upstream-pr/3562 into main
Royalflamejlh commented 2026-12-01 06:34:32 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-01T06:34:32Z.


(Edited: head 2196dfd10, rebased onto main 5ad98adbc, after three rounds of review: a v_cmpx no longer joins a run that reads EXEC as data; a negative inline mask gives -1 to the upper half; a folded loop's cap divides by the console group's threads; buffer accesses that count the lane (ADD_TID, global_*_addtid) count console lane t + 32 in their upper copies; SDWA scalar operands are not taken as spares; LWE counts towards N; s_subvector_loop is refused; a DPP16 upper copy takes the console's row mask bits 2..3; an SDWA compare into EXEC updates E; a panic in the rewrite falls back to the split form, and a compare into a constant is refused; a folded program with a returning atomic gets the compact plan a split one gets; the GPU test also compares with the split form on the same GPU. A test for each. Before: rebased onto main 38ad22da, after #3655; head 8f236eca4.)

On a GPU with 32-lane waves only, a wave64 compute program now runs folded where it can: each host lane carries two console lanes (t and t + 32), so the whole console wave is one host wave and nothing is exchanged between halves. The split form's exchange is what #3114 measures at 2.6x a program's GPU time, and its spin wait ended runs on Linux here in a GPU hang (NVIDIA Xid 109) at the title's world start.

The form is ported from VIctory-NVIDIA (crates/victory-shader/src/fold.rs at 5fabb46e, GPL-3.0-or-later, https://github.com/trustno1-coder/VIctory-NVIDIA), as a rewrite of the console code into a wave32 program before translation. The provenance note is in the file and THIRD_PARTY.md has the entry.

Folding is opt-in: XCL_WAVE64_FOLD=1 turns it on, and without it nothing changes. Its GPU time against the split form is not measured here; #3543, a port of the same idea, measured a median 1.27 times the split form's time on an RTX 4080 with a run-to-run spread as large as the difference.

What is in it

  • crates/xcl/src/gpu/dxil/fold.rs (new, 1,195 lines): the rewrite. VGPR v of console lane t + 32 is VGPR v + N of host lane t; a run of vector instructions is written twice, under each half of EXEC; a mask is the two copies' 32-bit ballots; v_readlane, v_writelane, v_readfirstlane and v_mbcnt name the copy that holds the lane. Scalar code is unchanged, since XCL keeps the console's scalar branches.
  • crates/xcl/src/gpu/dxil/fold_tests.rs (new, 871 lines): the tests, with a small RDNA2 interpreter that runs a console program in 64-lane waves and its folded code in 32-lane waves and compares.
  • gpu/dxil/kernel.rs (translate_compute_rodata): the folded form is tried for a split wave64 compute program; any refusal logs one line and the split form runs. It is tried only with XCL_WAVE64_FOLD=1, which is part of the translated cache's identity.
  • gpu/dxil/lower_mem.rs, lower_window.rs, lower.rs: in a folded program's upper copies of buffer accesses that count the lane (ADD_TID, global_*_addtid), the lane is console lane t + 32 (Lw::tid_lane, from fold::Twins::upper_tid).
  • It refuses: more than 127 VGPRs, ds_bpermute / ds_permute, ds_append / ds_consume, GDS, scratch, s_movrel* / v_movrel*, calls and indirect jumps, s_subvector_loop, EXEC or VCC as a memory operand, fewer than seven spare SGPRs, and a few rarer forms.
  • gpu/dxil/kernel.rs, compact.rs: a folded program whose compact plan is refused only for its table's size is not folded, and a folded program is chosen for the compact form as its split form would be. On that other tree (compact table limit 12,288 words) two programs of about 122,000 instructions lost their compact form by folding and became 4.3 MB of DXIL each, which NVIDIA's compiler did not finish in ten minutes; with main's 32,768 words both still fit, so on main this changes no program of that pack.
  • fold.rs: a program folds only when its VGPRs and their twins fit 255 registers (2N <= 255); the rewrite uses no VGPR beyond the twins.
  • docs/wave64-on-wave32.md: a section on the form.

Why it is one pull request. 2,220 changed lines in six commits, over the ~800 the contributing guide asks a reason for. Of them, 1,198 are fold.rs and 872 its tests; the rest (150 lines) are the wiring behind XCL_WAVE64_FOLD=1, the compact-limit check and its test, the warm setting, the docs and the provenance entry.

  • fold.rs is one rewrite pass over the instruction set: every instruction it accepts is rewritten in the same loop, against the same register plan and the same EXEC handling, so a part of it (say, the lane primitives without the driver) would be code nothing calls and nothing can test on its own: the tests run whole console programs through the interpreter and the folded form.
  • Splitting it as preparation / fold.rs not yet called / turning it on / the census would give three PRs whose diffs are each under 150 lines and one of ~1,900 that is this one: the review of fold.rs would be the same review.
  • It is a port: the provenance note names the source, and the closed #3529 / #3530 / #3543 stack split the same port into context, lane primitives and driver and none of the parts could be merged without the others.
  • It changes nothing unless XCL_WAVE64_FOLD=1 is set: with the switch off the translation and the caches are as on main.
    The commits are kept apart so each part can be read on its own: the rewrite (4779e9a96), its GPU tests and the pack count (09d2623ac), the docs (da0d2f01b), the compact-limit check (cc2d5fe79), the register limit (17e1504e4) and the opt-in switch (2196dfd10).

Tested

  • RTX 2070 SUPER 8 GB, Windows 11, MSVC, head 2196dfd10: cargo test --workspace -- --test-threads=4 3022 passed, 0 failed, 53 ignored. The new and changed tests passed there, on the GPU too: gpu_folded_wave64_matches_the_console_wave (now also against the split form), gpu_folded_wave64_counts_the_console_lane_in_add_tid_accesses, gpu_folded_wave64_keeps_the_thread_limits, the DPP16, SDWA, LWE and refusal tests, and a_folded_program_with_a_returning_atomic_takes_the_compact_form.
  • RTX 4060 Ti 16 GB, NVIDIA 615.71.09, AMD Ryzen 9 9950X3D, Linux, Wine 11.21 Staging, vkd3d-proton master with local patches, x86_64-pc-windows-gnu, release. Head 913af192c (XCL_WAVE64_FOLD is also a warm pipeline library setting since; the fold and shaders:: tests there, under Wine on the CPU: 122 passed, 0 failed, 1 ignored. Earlier head 0c6bd4c0: the form made opt-in; the tests switch it on themselves).
  • cargo test -p xcl --release --lib gpu::dxil -- --test-threads=2: 315 passed, 1 failed, 4 ignored. SKIPPED: dispatch_chain_native_wave64_builds_whole (no wave64). The failure is round_tests::directed_reference_basics, which fails the same way on main.
  • On the GPU: gpu_folded_wave64_matches_the_console_wave (seven programs: masks and lane reads; nested saveexec branches; LDS across a barrier; a loop with divergent exits; a carry chain with lane writes and v_cmpx; EXEC read as data and as a mask before a v_cmpx; negative inline masks; in groups of 64, 128, 8x8, 8x8x4, 40 and 16x6 threads, against a small RDNA2 interpreter of the console wave) and gpu_folded_wave64_keeps_the_thread_limits passed.
  • the_folded_form_is_taken_for_a_split_program_and_has_no_exchange: the folded DXIL validates and has no atomic, compare-exchange or group-shared storage.
  • A retail title, on another tree that carries these commits beside other unmerged pull requests: 1 run of 855 s with folding on, no crash, no device removal. That run had XCL_GPU_PROFILE=1, which makes a queue run its draws and dispatches one after the other; on a later head of that tree the title lost its device at the world start without the switch (2 of 2 runs, with folding on and with it off) and ran 600 s with it (1 of 1), so the run says nothing about this change with the GPU's work overlapping. In a cold launch pass of that tree, of the 1,151 wave64 compute programs it translated, 732 folded, 351 ran as lone halves (another unmerged change) and 68 stayed split. Translated offline, folded DXIL was 1.11 times the split form's at the median and 1.73 times at the 95th percentile.

Regression run
RTX 2070 SUPER 8 GB (driver 621.01), Ryzen 7 5700X3D, Windows 11 Pro 26200, release builds by scripts/smoke.ps1, the same retail title for 60 s each.

main at 078358a05, the newer main (this PR is on 5ad98adbc and merges cleanly into 078358a05):

xcl-smoke v1
commit: 078358a058f7ba5d16690dba8dc4e55d2c88ae0a
gpu: NVIDIA GeForce RTX 2070 SUPER
title: 5330474d
seconds: 60
exit: 0x0
frames shown: 1468 (PresentX 1468)
presents per 2 s (last 3): 60 60 61
device removals: 0
crashes: 0
peak commit: 15631 MB

this PR's head:

xcl-smoke v1
commit: 2196dfd10d9250c205127508af390b315017bf1d
gpu: NVIDIA GeForce RTX 2070 SUPER
title: 5330474d
seconds: 60
exit: 0x0
frames shown: 1556 (PresentX 1556)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15283 MB

Not tested

  • AMD, any other NVIDIA card, a title from this branch with XCL_WAVE64_FOLD=1. The smoke runs below are without the switch, so they show only that nothing changes when it is off.
  • The form assumes a hardware wave of a one-dimensional group holds 32 consecutive SV_GroupIndex values, as the existing wave32 path does.
  • SDWA and DPP copies, v_div_fmas, MIMG/NSA and buffer instructions are ported but no test program uses them. The reference interpreter is this PR's own.
  • GPU time against the split form: not measured. Folded code is about twice the instructions.

AI use

  • Claude Code. Claude Fable 5.2 ported the code and wrote the tests and this description. Claude Opus 5.5 found why two programs lost their compact form and wrote that change (6cec7afd) and the VGPR limit (bda4766f).
<!-- greyfinch-sync:ivall/xcl:issue:5580441529 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-01T06:34:32Z. --- (Edited: head `2196dfd10`, rebased onto `main` 5ad98adbc, after three rounds of review: a `v_cmpx` no longer joins a run that reads EXEC as data; a negative inline mask gives -1 to the upper half; a folded loop's cap divides by the console group's threads; buffer accesses that count the lane (ADD_TID, `global_*_addtid`) count console lane t + 32 in their upper copies; SDWA scalar operands are not taken as spares; LWE counts towards N; `s_subvector_loop` is refused; a DPP16 upper copy takes the console's row mask bits 2..3; an SDWA compare into EXEC updates E; a panic in the rewrite falls back to the split form, and a compare into a constant is refused; a folded program with a returning atomic gets the compact plan a split one gets; the GPU test also compares with the split form on the same GPU. A test for each. Before: rebased onto `main` 38ad22da, after #3655; head `8f236eca4`.) On a GPU with 32-lane waves only, a wave64 compute program now runs folded where it can: each host lane carries two console lanes (t and t + 32), so the whole console wave is one host wave and nothing is exchanged between halves. The split form's exchange is what #3114 measures at 2.6x a program's GPU time, and its spin wait ended runs on Linux here in a GPU hang (NVIDIA Xid 109) at the title's world start. The form is ported from VIctory-NVIDIA (`crates/victory-shader/src/fold.rs` at `5fabb46e`, GPL-3.0-or-later, https://github.com/trustno1-coder/VIctory-NVIDIA), as a rewrite of the console code into a wave32 program before translation. The provenance note is in the file and `THIRD_PARTY.md` has the entry. Folding is opt-in: `XCL_WAVE64_FOLD=1` turns it on, and without it nothing changes. Its GPU time against the split form is not measured here; #3543, a port of the same idea, measured a median 1.27 times the split form's time on an RTX 4080 with a run-to-run spread as large as the difference. **What is in it** - `crates/xcl/src/gpu/dxil/fold.rs` (new, 1,195 lines): the rewrite. VGPR v of console lane t + 32 is VGPR v + N of host lane t; a run of vector instructions is written twice, under each half of EXEC; a mask is the two copies' 32-bit ballots; `v_readlane`, `v_writelane`, `v_readfirstlane` and `v_mbcnt` name the copy that holds the lane. Scalar code is unchanged, since XCL keeps the console's scalar branches. - `crates/xcl/src/gpu/dxil/fold_tests.rs` (new, 871 lines): the tests, with a small RDNA2 interpreter that runs a console program in 64-lane waves and its folded code in 32-lane waves and compares. - `gpu/dxil/kernel.rs` (`translate_compute_rodata`): the folded form is tried for a split wave64 compute program; any refusal logs one line and the split form runs. It is tried only with `XCL_WAVE64_FOLD=1`, which is part of the translated cache's identity. - `gpu/dxil/lower_mem.rs`, `lower_window.rs`, `lower.rs`: in a folded program's upper copies of buffer accesses that count the lane (ADD_TID, `global_*_addtid`), the lane is console lane t + 32 (`Lw::tid_lane`, from `fold::Twins::upper_tid`). - It refuses: more than 127 VGPRs, `ds_bpermute` / `ds_permute`, `ds_append` / `ds_consume`, GDS, scratch, `s_movrel*` / `v_movrel*`, calls and indirect jumps, `s_subvector_loop`, EXEC or VCC as a memory operand, fewer than seven spare SGPRs, and a few rarer forms. - `gpu/dxil/kernel.rs`, `compact.rs`: a folded program whose compact plan is refused only for its table's size is not folded, and a folded program is chosen for the compact form as its split form would be. On that other tree (compact table limit 12,288 words) two programs of about 122,000 instructions lost their compact form by folding and became 4.3 MB of DXIL each, which NVIDIA's compiler did not finish in ten minutes; with `main`'s 32,768 words both still fit, so on `main` this changes no program of that pack. - `fold.rs`: a program folds only when its VGPRs and their twins fit 255 registers (2N <= 255); the rewrite uses no VGPR beyond the twins. - `docs/wave64-on-wave32.md`: a section on the form. **Why it is one pull request.** 2,220 changed lines in six commits, over the ~800 the contributing guide asks a reason for. Of them, 1,198 are `fold.rs` and 872 its tests; the rest (150 lines) are the wiring behind `XCL_WAVE64_FOLD=1`, the compact-limit check and its test, the warm setting, the docs and the provenance entry. - `fold.rs` is one rewrite pass over the instruction set: every instruction it accepts is rewritten in the same loop, against the same register plan and the same EXEC handling, so a part of it (say, the lane primitives without the driver) would be code nothing calls and nothing can test on its own: the tests run whole console programs through the interpreter and the folded form. - Splitting it as preparation / `fold.rs` not yet called / turning it on / the census would give three PRs whose diffs are each under 150 lines and one of ~1,900 that is this one: the review of `fold.rs` would be the same review. - It is a port: the provenance note names the source, and the closed #3529 / #3530 / #3543 stack split the same port into context, lane primitives and driver and none of the parts could be merged without the others. - It changes nothing unless `XCL_WAVE64_FOLD=1` is set: with the switch off the translation and the caches are as on `main`. The commits are kept apart so each part can be read on its own: the rewrite (`4779e9a96`), its GPU tests and the pack count (`09d2623ac`), the docs (`da0d2f01b`), the compact-limit check (`cc2d5fe79`), the register limit (`17e1504e4`) and the opt-in switch (`2196dfd10`). **Tested** - RTX 2070 SUPER 8 GB, Windows 11, MSVC, head `2196dfd10`: `cargo test --workspace -- --test-threads=4` 3022 passed, 0 failed, 53 ignored. The new and changed tests passed there, on the GPU too: `gpu_folded_wave64_matches_the_console_wave` (now also against the split form), `gpu_folded_wave64_counts_the_console_lane_in_add_tid_accesses`, `gpu_folded_wave64_keeps_the_thread_limits`, the DPP16, SDWA, LWE and refusal tests, and `a_folded_program_with_a_returning_atomic_takes_the_compact_form`. - RTX 4060 Ti 16 GB, NVIDIA 615.71.09, AMD Ryzen 9 9950X3D, Linux, Wine 11.21 Staging, vkd3d-proton master with local patches, `x86_64-pc-windows-gnu`, release. Head `913af192c` (`XCL_WAVE64_FOLD` is also a warm pipeline library setting since; the fold and `shaders::` tests there, under Wine on the CPU: 122 passed, 0 failed, 1 ignored. Earlier head `0c6bd4c0`: the form made opt-in; the tests switch it on themselves). - `cargo test -p xcl --release --lib gpu::dxil -- --test-threads=2`: 315 passed, 1 failed, 4 ignored. SKIPPED: `dispatch_chain_native_wave64_builds_whole` (no wave64). The failure is `round_tests::directed_reference_basics`, which fails the same way on `main`. - On the GPU: `gpu_folded_wave64_matches_the_console_wave` (seven programs: masks and lane reads; nested saveexec branches; LDS across a barrier; a loop with divergent exits; a carry chain with lane writes and `v_cmpx`; EXEC read as data and as a mask before a `v_cmpx`; negative inline masks; in groups of 64, 128, 8x8, 8x8x4, 40 and 16x6 threads, against a small RDNA2 interpreter of the console wave) and `gpu_folded_wave64_keeps_the_thread_limits` passed. - `the_folded_form_is_taken_for_a_split_program_and_has_no_exchange`: the folded DXIL validates and has no atomic, compare-exchange or group-shared storage. - A retail title, on another tree that carries these commits beside other unmerged pull requests: 1 run of 855 s with folding on, no crash, no device removal. That run had `XCL_GPU_PROFILE=1`, which makes a queue run its draws and dispatches one after the other; on a later head of that tree the title lost its device at the world start without the switch (2 of 2 runs, with folding on and with it off) and ran 600 s with it (1 of 1), so the run says nothing about this change with the GPU's work overlapping. In a cold launch pass of that tree, of the 1,151 wave64 compute programs it translated, 732 folded, 351 ran as lone halves (another unmerged change) and 68 stayed split. Translated offline, folded DXIL was 1.11 times the split form's at the median and 1.73 times at the 95th percentile. **Regression run** RTX 2070 SUPER 8 GB (driver 621.01), Ryzen 7 5700X3D, Windows 11 Pro 26200, release builds by `scripts/smoke.ps1`, the same retail title for 60 s each. `main` at 078358a05, the newer `main` (this PR is on 5ad98adbc and merges cleanly into 078358a05): ``` xcl-smoke v1 commit: 078358a058f7ba5d16690dba8dc4e55d2c88ae0a gpu: NVIDIA GeForce RTX 2070 SUPER title: 5330474d seconds: 60 exit: 0x0 frames shown: 1468 (PresentX 1468) presents per 2 s (last 3): 60 60 61 device removals: 0 crashes: 0 peak commit: 15631 MB ``` this PR's head: ``` xcl-smoke v1 commit: 2196dfd10d9250c205127508af390b315017bf1d gpu: NVIDIA GeForce RTX 2070 SUPER title: 5330474d seconds: 60 exit: 0x0 frames shown: 1556 (PresentX 1556) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 15283 MB ``` **Not tested** - AMD, any other NVIDIA card, a title from this branch with `XCL_WAVE64_FOLD=1`. The smoke runs below are without the switch, so they show only that nothing changes when it is off. - The form assumes a hardware wave of a one-dimensional group holds 32 consecutive `SV_GroupIndex` values, as the existing wave32 path does. - SDWA and DPP copies, `v_div_fmas`, MIMG/NSA and buffer instructions are ported but no test program uses them. The reference interpreter is this PR's own. - GPU time against the split form: not measured. Folded code is about twice the instructions. **AI use** - Claude Code. Claude Fable 5.2 ported the code and wrote the tests and this description. Claude Opus 5.5 found why two programs lost their compact form and wrote that change (`6cec7afd`) and the VGPR limit (`bda4766f`).
Foniass commented 2026-12-01 07:11:47 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T07:11:47Z.


Review (head 988b2987, diff read, not a merge-check; draft with PR description red, so not built or run here):

  • On by default without a GPU-time measurement. Every split wave64 compute program is tried folded first (kernel.rs ~219, fold.rs ~54). The same idea from the same VIctory-NVIDIA source (throny's #3529 / #3530 / #3543, closed today) was measured in the world on an RTX 4080 at a median 1.27x the split form's time ("no measurable gain"). Please measure against the split form on the GPU, on Windows, before making it the default, or keep it opt-in.
  • VGPR limit: it only refuses above 128 VGPRs (2N > 256, fold.rs ~1112), while the closed stack refused at 2N + 16 > 255, the limit VIctory-NVIDIA hit at 2 x 129 VGPRs, so programs near 128 VGPRs probably spill on NVIDIA.
  • Size: 1,951 lines (fold.rs 1,157, tests 716). The closed stack shows the work can be split (context, lane primitives, driver, wiring).
  • The GPU tests compare only with this PR's own interpreter; adding the split form on the same GPU as a second reference (as #3561 does) would help.
  • Still owed: both xcl-smoke blocks and the whole suite on Windows (only gpu::dxil ran, on Linux / Wine with windows-gnu). It conflicts with #3504, #3561 and #3563 in kernel.rs.

Fine: the rewrites of v_readfirstlane / v_readlane / v_writelane / v_mbcnt, run ordering (stores and EXEC writes end a run, upper_first for scalar hazards), the s_getpc remap to the console address, the NSA remap, and the provenance note plus THIRD_PARTY entry. It covers more than the closed stack (memory, LDS, barriers, DPP).

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

<!-- greyfinch-sync:ivall/xcl:comment:7303757534 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7303757534). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T07:11:47Z. --- Review (head 988b2987, diff read, not a merge-check; draft with `PR description` red, so not built or run here): - **On by default without a GPU-time measurement.** Every split wave64 compute program is tried folded first (`kernel.rs` ~219, `fold.rs` ~54). The same idea from the same VIctory-NVIDIA source (throny's #3529 / #3530 / #3543, closed today) was measured in the world on an RTX 4080 at a median 1.27x the split form's time ("no measurable gain"). Please measure against the split form on the GPU, on Windows, before making it the default, or keep it opt-in. - **VGPR limit:** it only refuses above 128 VGPRs (2N > 256, `fold.rs` ~1112), while the closed stack refused at 2N + 16 > 255, the limit VIctory-NVIDIA hit at 2 x 129 VGPRs, so programs near 128 VGPRs probably spill on NVIDIA. - **Size:** 1,951 lines (fold.rs 1,157, tests 716). The closed stack shows the work can be split (context, lane primitives, driver, wiring). - The GPU tests compare only with this PR's own interpreter; adding the split form on the same GPU as a second reference (as #3561 does) would help. - Still owed: both xcl-smoke blocks and the whole suite on Windows (only `gpu::dxil` ran, on Linux / Wine with windows-gnu). It conflicts with #3504, #3561 and #3563 in `kernel.rs`. Fine: the rewrites of `v_readfirstlane` / `v_readlane` / `v_writelane` / `v_mbcnt`, run ordering (stores and EXEC writes end a run, `upper_first` for scalar hazards), the `s_getpc` remap to the console address, the NSA remap, and the provenance note plus THIRD_PARTY entry. It covers more than the closed stack (memory, LDS, barriers, DPP). AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Royalflamejlh commented 2026-12-01 08:05:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-01T08:05:00Z.


Thanks for the read. On the points:

  • VGPR limit: right in principle. The rewrite uses no VGPR beyond the twins (its scratch registers are SGPRs), so a host lane holds exactly 2N, and the old check let 2N = 256 through. It is now 2N <= 255 (bda4766fb), with a test at the boundary. In the pack tested no program has 120 to 128 VGPRs; the ones at 129 were already refused.
  • Default without a GPU-time measurement: true, it is not measured here. The description now says so and names #3543's figure. I can make it opt-in if that is what should merge.
  • New since your read (6cec7afd): a folded program whose compact plan is refused only for its table's size is not folded. On a tree with a 12,288-word table limit, two programs of about 122,000 instructions became 4.3 MB of DXIL each when folded and NVIDIA's compiler did not finish them in ten minutes. With main's 32,768 words both still fit.
  • A second reference in the GPU tests (the split form on the same GPU): not added yet.

gpu::dxil on the new head, RTX 4060 Ti under Wine: 315 passed, 1 failed (directed_reference_basics, as on main), 4 ignored.

AI use: Claude Code. Claude Opus 5.5 checked the limit against the code and wrote the two changes; Claude Fable 5.2 ran the tests on the card and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:comment:7304849807 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7304849807). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-01T08:05:00Z. --- Thanks for the read. On the points: - **VGPR limit:** right in principle. The rewrite uses no VGPR beyond the twins (its scratch registers are SGPRs), so a host lane holds exactly 2N, and the old check let 2N = 256 through. It is now 2N <= 255 (`bda4766fb`), with a test at the boundary. In the pack tested no program has 120 to 128 VGPRs; the ones at 129 were already refused. - **Default without a GPU-time measurement:** true, it is not measured here. The description now says so and names #3543's figure. I can make it opt-in if that is what should merge. - **New since your read** (`6cec7afd`): a folded program whose compact plan is refused only for its table's size is not folded. On a tree with a 12,288-word table limit, two programs of about 122,000 instructions became 4.3 MB of DXIL each when folded and NVIDIA's compiler did not finish them in ten minutes. With `main`'s 32,768 words both still fit. - **A second reference in the GPU tests** (the split form on the same GPU): not added yet. `gpu::dxil` on the new head, RTX 4060 Ti under Wine: 315 passed, 1 failed (`directed_reference_basics`, as on `main`), 4 ignored. **AI use:** Claude Code. Claude Opus 5.5 checked the limit against the code and wrote the two changes; Claude Fable 5.2 ran the tests on the card and wrote this reply.
Foniass commented 2026-12-01 08:18:37 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T08:18:37Z.


Re-review (head bda4766f, diff read, not a merge-check: PR description still fails (no xcl-smoke blocks), so not built or run here). Follow-up to my review of 988b2987.

  • Still on by default without a GPU-time measurement against the split form, while #3543 measured the same idea at 1.27x; please make it opt-in until it's measured, as the description now offers.
  • VGPR limit: partly addressed. It's now 2N > 255 (fold.rs ~1112), and the commit argues the rewrite needs no extra VGPRs because its scratch registers are SGPRs (spare_sgprs), which matches the code. The description's "refuses: more than 128 VGPRs" is now stale (the limit is 127).
  • New (6cec7afd): a folded program whose compact tables pass the limit now keeps the split compact form (kernel.rs ~454-456, compact::wanted_plan / fits), with a test; it refuses folding even when the split form's tables don't fit either.
  • Still open: about 2,000 lines now, tests that compare only with the PR's own interpreter, the smoke pair and a Windows suite run. The "owed before this leaves draft" wording and the missing Opus 5.5 in AI use need updating.

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

<!-- greyfinch-sync:ivall/xcl:comment:7305148549 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7305148549). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T08:18:37Z. --- Re-review (head bda4766f, diff read, not a merge-check: `PR description` still fails (no xcl-smoke blocks), so not built or run here). Follow-up to my review of 988b2987. - **Still on by default without a GPU-time measurement** against the split form, while #3543 measured the same idea at 1.27x; please make it opt-in until it's measured, as the description now offers. - **VGPR limit: partly addressed.** It's now `2N > 255` (`fold.rs` ~1112), and the commit argues the rewrite needs no extra VGPRs because its scratch registers are SGPRs (`spare_sgprs`), which matches the code. The description's "refuses: more than 128 VGPRs" is now stale (the limit is 127). - New (6cec7afd): a folded program whose compact tables pass the limit now keeps the split compact form (`kernel.rs` ~454-456, `compact::wanted_plan` / `fits`), with a test; it refuses folding even when the split form's tables don't fit either. - Still open: about 2,000 lines now, tests that compare only with the PR's own interpreter, the smoke pair and a Windows suite run. The "owed before this leaves draft" wording and the missing Opus 5.5 in AI use need updating. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Foniass commented 2026-12-01 10:17:02 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T10:17:02Z.


Triage (#1607) – head 0c6bd4c

No open PR makes the same change. #3543 (throny) was a port of the same fold and was closed by its author on 2026-11-30 because it measured no gain on an RTX 4080. #3561 (same author) is a different approach to the same exchange cost: a lane loop for small programs.
The provenance note and the THIRD_PARTY.md entry for VIctory-NVIDIA (GPL-3.0-or-later) are present. Since 0c6bd4c0 folding is opt-in (XCL_WAVE64_FOLD=1). It has not been run on Windows or on any GPU other than the RTX 4060 Ti, and its GPU time against the split form is not measured, so it should stay opt-in until that is settled.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

<!-- greyfinch-sync:ivall/xcl:comment:7307948773 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7307948773). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T10:17:02Z. --- **Triage (#1607)** – head 0c6bd4c No open PR makes the same change. #3543 (throny) was a port of the same fold and was closed by its author on 2026-11-30 because it measured no gain on an RTX 4080. #3561 (same author) is a different approach to the same exchange cost: a lane loop for small programs. The provenance note and the THIRD_PARTY.md entry for VIctory-NVIDIA (GPL-3.0-or-later) are present. Since 0c6bd4c0 folding is opt-in (XCL_WAVE64_FOLD=1). It has not been run on Windows or on any GPU other than the RTX 4060 Ti, and its GPU time against the split form is not measured, so it should stay opt-in until that is settled. Recommendation: keep open. AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.
Royalflamejlh commented 2026-12-01 14:19:17 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-01T14:19:17Z.


Folding is opt-in now (head 0c6bd4c0): XCL_WAVE64_FOLD=1 turns it on, and without it no program changes form. The description says so, and why: no GPU-time measurement against the split form here, and #3543's figure.

cargo test --lib gpu::dxil on that head, RTX 4060 Ti under Wine: 315 passed, 1 failed (directed_reference_basics, as on main), 4 ignored; both GPU tests of the form passed.

AI use: Claude Code with Claude Fable 5.2 made the change, ran the tests and wrote this.

<!-- greyfinch-sync:ivall/xcl:comment:7314059752 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7314059752). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-01T14:19:17Z. --- Folding is opt-in now (head `0c6bd4c0`): `XCL_WAVE64_FOLD=1` turns it on, and without it no program changes form. The description says so, and why: no GPU-time measurement against the split form here, and #3543's figure. `cargo test --lib gpu::dxil` on that head, RTX 4060 Ti under Wine: 315 passed, 1 failed (`directed_reference_basics`, as on `main`), 4 ignored; both GPU tests of the form passed. **AI use:** Claude Code with Claude Fable 5.2 made the change, ran the tests and wrote this.
Royalflamejlh commented 2026-12-01 20:47:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-01T20:47:10Z.


XCL_WAVE64_FOLD is now a warm pipeline library setting as well (head 913af192c): with it left out, a warm library built with folding on was reused with it off. Found while checking bmjask's point on #3563.

AI use: Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:ivall/xcl:comment:7325268046 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7325268046). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-01T20:47:10Z. --- `XCL_WAVE64_FOLD` is now a warm pipeline library setting as well (head `913af192c`): with it left out, a warm library built with folding on was reused with it off. Found while checking bmjask's point on #3563. AI use: Claude Code (Claude Opus 5.5).
Foniass commented 2026-12-01 21:15:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T21:15:44Z.


Follow-up review (head 913af192, since bda4766, diff read, not a merge-check; checks red):

  • On by default without a GPU-time measurement: fixed. Folding runs only with XCL_WAVE64_FOLD=1 (fold.rs ~49-56); the translated cache tag is xcl-wave64-fold-1 (kernel.rs ~110); the switch is a warm pipeline setting (shaders.rs ~40) with a test; README and docs/wave64-on-wave32.md say it is off and not measured.
  • VGPR limit: fixed. It refuses at 2 * n > HOST_REGISTERS (fold.rs ~1112), and the description says "more than 127 VGPRs".
  • Compact-limit refusal: unchanged. kernel.rs ~454 still refuses folding whenever the folded wanted_plan does not fit, even when the split form's tables would not fit either; it only loses a fold, and only with the switch on.
  • GPU tests compare only with the PR's own interpreter: still open. gpu_folded_wave64_matches_the_console_wave (fold_tests.rs ~504-522) takes want from the run interpreter, not from the split form on the same GPU.
  • Smoke pair, Windows suite run, conflicts: still open. Regression run has no xcl-smoke blocks (the reason PR description is red), and #3504, #3561 and #3563 each still conflict with this branch in gpu/dxil/kernel.rs. The draft wording and AI use are fixed.

New:

  • Please split it. 2,016 changed lines, none generated or test data, over the CONTRIBUTING.md limits; fold.rs alone is 1,158 lines. A natural split, stacked: (1) preparation with no behaviour change: compact::wanted_plan / fits and the groups / last fields of ComputeStart; (2) fold.rs with fold_tests.rs, not yet called (the closed #3529 / #3530 / #3543 stack split the same port into context, lane primitives and driver); (3) turning it on: translate_folded and its call in translate_compute_rodata behind XCL_WAVE64_FOLD=1, the compact-limit refusal, the warm setting, README and docs; (4) the wave64_fold_census count.

Not reviewed line by line again because of the size; the 20 lines changed since the last review (the opt-in switch, warm setting, test, docs) are correct. The provenance note and THIRD_PARTY.md entry are in place.

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

<!-- greyfinch-sync:ivall/xcl:comment:7325988442 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7325988442). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T21:15:44Z. --- Follow-up review (head 913af192, since bda4766, diff read, not a merge-check; checks red): - **On by default without a GPU-time measurement:** fixed. Folding runs only with `XCL_WAVE64_FOLD=1` (`fold.rs` ~49-56); the translated cache tag is `xcl-wave64-fold-1` (`kernel.rs` ~110); the switch is a warm pipeline setting (`shaders.rs` ~40) with a test; README and `docs/wave64-on-wave32.md` say it is off and not measured. - **VGPR limit:** fixed. It refuses at `2 * n > HOST_REGISTERS` (`fold.rs` ~1112), and the description says "more than 127 VGPRs". - **Compact-limit refusal:** unchanged. `kernel.rs` ~454 still refuses folding whenever the folded `wanted_plan` does not fit, even when the split form's tables would not fit either; it only loses a fold, and only with the switch on. - **GPU tests compare only with the PR's own interpreter:** still open. `gpu_folded_wave64_matches_the_console_wave` (`fold_tests.rs` ~504-522) takes `want` from the `run` interpreter, not from the split form on the same GPU. - **Smoke pair, Windows suite run, conflicts:** still open. **Regression run** has no `xcl-smoke` blocks (the reason `PR description` is red), and #3504, #3561 and #3563 each still conflict with this branch in `gpu/dxil/kernel.rs`. The draft wording and **AI use** are fixed. New: - **Please split it.** 2,016 changed lines, none generated or test data, over the CONTRIBUTING.md limits; `fold.rs` alone is 1,158 lines. A natural split, stacked: (1) preparation with no behaviour change: `compact::wanted_plan` / `fits` and the `groups` / `last` fields of `ComputeStart`; (2) `fold.rs` with `fold_tests.rs`, not yet called (the closed #3529 / #3530 / #3543 stack split the same port into context, lane primitives and driver); (3) turning it on: `translate_folded` and its call in `translate_compute_rodata` behind `XCL_WAVE64_FOLD=1`, the compact-limit refusal, the warm setting, README and docs; (4) the `wave64_fold_census` count. Not reviewed line by line again because of the size; the 20 lines changed since the last review (the opt-in switch, warm setting, test, docs) are correct. The provenance note and `THIRD_PARTY.md` entry are in place. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Royalflamejlh commented 2026-12-01 21:52:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-01T21:52:58Z.


@Foniass thanks for the follow-up. I'd rather keep it as one pull request, and the description now says why, under Why it is one pull request: fold.rs is one rewrite pass whose parts nothing could call or test alone (the tests run whole console programs through it), so the split would leave one ~1,900-line PR that is this one, beside three small ones; the closed #3529 / #3530 / #3543 stack split the same port and none of its parts could merge alone. The six commits are kept apart so each part reads on its own, and nothing changes without XCL_WAVE64_FOLD=1.

The other open points stand as you list them: the smoke pair and a Windows run are owed (no Windows machine of ours answered today), the GPU tests compare with the interpreter rather than the split form on the same GPU, and the compact_nest_tag conflict with #3561 / #3563.

AI use: Claude Code (Claude Opus 5.5) drafted this reply and the description section.

<!-- greyfinch-sync:ivall/xcl:comment:7326954634 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7326954634). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-01T21:52:58Z. --- @Foniass thanks for the follow-up. I'd rather keep it as one pull request, and the description now says why, under **Why it is one pull request**: `fold.rs` is one rewrite pass whose parts nothing could call or test alone (the tests run whole console programs through it), so the split would leave one ~1,900-line PR that is this one, beside three small ones; the closed #3529 / #3530 / #3543 stack split the same port and none of its parts could merge alone. The six commits are kept apart so each part reads on its own, and nothing changes without `XCL_WAVE64_FOLD=1`. The other open points stand as you list them: the smoke pair and a Windows run are owed (no Windows machine of ours answered today), the GPU tests compare with the interpreter rather than the split form on the same GPU, and the `compact_nest_tag` conflict with #3561 / #3563. AI use: Claude Code (Claude Opus 5.5) drafted this reply and the description section.
Decodere commented 2026-12-02 11:49:15 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Decodere on 2026-12-02T11:49:15Z.


merge-check
base: 1c8b551475
head: 913af192c7
merge: clean (d6993aa0d7f42f8bedf2c6ae93ede6cb7f790b08; 9 files, +2004/-12; git diff --check ok)
build: cargo build --workspace ok; cargo build --release -p xcl ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 --nocapture -> 2918 passed, 1 failed, 52 ignored across 43 targets (28 SKIPPED lines matching clean base 1c8b551475: 22 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 2 no heap windows, 1 cannot disable the driver cache). The sole failure is the pre-existing Issue #3441 flake in tests/gpu_two_pass_cache_e2e.rs:584 (two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs, releasing the title PSOs releases their two-pass state: left: 1, right: 0), reproduced on clean base 1c8b551475. All 10 new runnable tests passed on RTX 4060 with 0 skips (including both live GPU tests gpu_folded_wave64_matches_the_console_wave and gpu_folded_wave64_keeps_the_thread_limits, 7 unit tests in gpu::dxil::fold::tests, and shaders::warm_settings_keep_the_wave64_fold_switch_on_both_backends; wave64_fold_census is marked #[ignore]).
review: Full 9-file diff (+2004/-12) audited. The opt-in plumbing (XCL_WAVE64_FOLD=1, off by default, keyed into kernel::compact_nest_tag and shaders::semantic_pipeline_setting), fold::init / compute_gate (leave = false), and GPL-3.0-or-later attribution in THIRD_PARTY.md and fold.rs are clean. However, code audit of crates/xcl/src/gpu/dxil/fold.rs found three concrete silent miscompilation bugs where fold accepts the program and emits wrong code instead of ordering correctly or failing closed:

  1. Missing EXEC writes in valu_copy (fold.rs:405, fold.rs:434, fold.rs:455): all three t.exec = true paths (SDWA v_cmpx, plain ENC_VOPC v_cmpx, and ENC_VOP3 v_cmp* with dst == EXEC_LO) omit side.writes.push(mask_console(EXEC_LO, half)). Because t.a.writes is empty: (a) joins (fold.rs:708-713) merges a preceding vector instruction reading EXEC_LO (e.g. v_mov_b32 v0, exec_lo) with a following v_cmpx_* into one run, so lower_copies writes the post-v_cmpx EXEC_LO back into x.e before upper_copies runs v_mov_b32 v0+N, e, giving console lanes 32..63 the overwritten EXEC.lo instead of the pre-v_cmpx value; (b) single-instruction v_cmpx_* exec_lo, v0 or VOP3 v_cmp_* exec, exec_lo, v0 fails to set upper_first = true in Twin::ordered (clobbering x.e before upper_copies reads it); and (c) 64-bit v_cmpx_* exec, v[0:1] fails to be rejected by Twin::ordered.
  2. Silently dropped EXEC write on SDWA v_cmp with SD=1, SDST=EXEC_LO (fold.rs:407-412): when sd == EXEC_LO (126), mask(sd, half, x) rewrites SDST to host EXEC_LO for both halves, but t.exec is never set to true, so neither lower_copies nor upper_copies copies host EXEC_LO back into x.e/x.e + 1 and the write to console EXEC is lost.
  3. Missed SDWA SGPR and SCC operands in spare_sgprs (fold.rs:993-1000) and scc_use (fold.rs:627-632): spare_sgprs relies solely on rdna2::sgpr_uses, which skips SDWA VSRC0 (S0=1), VSRC1 (S1=1), and VOPC_VOP_SDWA_SDST_ENC SDST (SD=1) (rdna2.rs:554-559), allowing live SDWA-only SGPRs (such as a VOPC SDWA destination pair) to be allocated as spare x.e/jp/save/swap/t. Likewise scc_use (fold.rs:630) checks VSRC0 == 253 (d.words[1] & 0xFF) but misses S1=1 with VSRC1 == 253 (d.words[0] >> 9 & 0xFF), allowing SCC-clobbering rewrites while SCC is live into an SDWA VSRC1.
    performance: Two 60 s release smokes on title 29640639 vs clean base 1c8b551475 (1462 frames, presents per 2 s last 3: 48 53 59, peak commit 16043 MB): default (switch unset) ran 1638 frames (+12.0%, steady 60 60 61, peak commit 16563 MB, +3.2%, 0 removals, 0 crashes); opt-in XCL_WAVE64_FOLD=1 ran 1651 frames (+12.9% vs base, +0.8% vs default, steady 60 60 60, peak commit 14953 MB, -6.8% vs base, 0 removals, 0 crashes; 1 logged fallback [SHADER] wave64 fold: no spare scalar registers).

Default (switch unset):

xcl-smoke v1
commit: d6993aa0d7f42f8bedf2c6ae93ede6cb7f790b08
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1638 (PresentX 1638)
presents per 2 s (last 3): 60 60 61
device removals: 0
crashes: 0
peak commit: 16563 MB

Opt-in (XCL_WAVE64_FOLD=1):

xcl-smoke v1
commit: d6993aa0d7f42f8bedf2c6ae93ede6cb7f790b08
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1651 (PresentX 1651)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14953 MB

verdict: not yet: silent miscompilations in fold.rs (missing EXEC side.writes on v_cmpx/v_cmp-to-exec at lines 405/434/455, missing t.exec on SDWA v_cmp SDST=EXEC_LO at lines 407-412, and missed SDWA SGPR/SCC operands in spare_sgprs and scc_use)
hardware / tool and model: NVIDIA GeForce RTX 4060 8 GB (driver 621.40), Intel Core i5-11400F, 32 GB RAM, Windows 11 Build 26200, Rust 1.100.1 MSVC, DXC 1.9.2602.17 / Antigravity (Gemini 4 Neon)

<!-- greyfinch-sync:ivall/xcl:comment:7344451757 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7344451757). Originally posted by [Decodere](https://github.com/Decodere) on 2026-12-02T11:49:15Z. --- merge-check base: 1c8b551475e1e7bfe48f94448492a4c3544a2e0f head: 913af192c7c67e82bfd2daa5d8c50fc48f7e5173 merge: clean (d6993aa0d7f42f8bedf2c6ae93ede6cb7f790b08; 9 files, +2004/-12; git diff --check ok) build: cargo build --workspace ok; cargo build --release -p xcl ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 --nocapture -> 2918 passed, 1 failed, 52 ignored across 43 targets (28 SKIPPED lines matching clean base 1c8b551475e1: 22 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 2 no heap windows, 1 cannot disable the driver cache). The sole failure is the pre-existing Issue #3441 flake in tests/gpu_two_pass_cache_e2e.rs:584 (`two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs`, `releasing the title PSOs releases their two-pass state: left: 1, right: 0`), reproduced on clean base 1c8b551475e1. All 10 new runnable tests passed on RTX 4060 with 0 skips (including both live GPU tests `gpu_folded_wave64_matches_the_console_wave` and `gpu_folded_wave64_keeps_the_thread_limits`, 7 unit tests in `gpu::dxil::fold::tests`, and `shaders::warm_settings_keep_the_wave64_fold_switch_on_both_backends`; `wave64_fold_census` is marked `#[ignore]`). review: Full 9-file diff (+2004/-12) audited. The opt-in plumbing (`XCL_WAVE64_FOLD=1`, off by default, keyed into `kernel::compact_nest_tag` and `shaders::semantic_pipeline_setting`), `fold::init` / `compute_gate` (`leave = false`), and GPL-3.0-or-later attribution in `THIRD_PARTY.md` and `fold.rs` are clean. However, code audit of `crates/xcl/src/gpu/dxil/fold.rs` found three concrete silent miscompilation bugs where `fold` accepts the program and emits wrong code instead of ordering correctly or failing closed: 1. Missing `EXEC` writes in `valu_copy` (`fold.rs:405`, `fold.rs:434`, `fold.rs:455`): all three `t.exec = true` paths (SDWA `v_cmpx`, plain `ENC_VOPC` `v_cmpx`, and `ENC_VOP3` `v_cmp*` with `dst == EXEC_LO`) omit `side.writes.push(mask_console(EXEC_LO, half))`. Because `t.a.writes` is empty: (a) `joins` (`fold.rs:708-713`) merges a preceding vector instruction reading `EXEC_LO` (e.g. `v_mov_b32 v0, exec_lo`) with a following `v_cmpx_*` into one run, so `lower_copies` writes the post-`v_cmpx` `EXEC_LO` back into `x.e` before `upper_copies` runs `v_mov_b32 v0+N, e`, giving console lanes 32..63 the overwritten `EXEC.lo` instead of the pre-`v_cmpx` value; (b) single-instruction `v_cmpx_* exec_lo, v0` or VOP3 `v_cmp_* exec, exec_lo, v0` fails to set `upper_first = true` in `Twin::ordered` (clobbering `x.e` before `upper_copies` reads it); and (c) 64-bit `v_cmpx_* exec, v[0:1]` fails to be rejected by `Twin::ordered`. 2. Silently dropped `EXEC` write on SDWA `v_cmp` with `SD=1, SDST=EXEC_LO` (`fold.rs:407-412`): when `sd == EXEC_LO` (`126`), `mask(sd, half, x)` rewrites `SDST` to host `EXEC_LO` for both halves, but `t.exec` is never set to `true`, so neither `lower_copies` nor `upper_copies` copies host `EXEC_LO` back into `x.e`/`x.e + 1` and the write to console `EXEC` is lost. 3. Missed SDWA SGPR and SCC operands in `spare_sgprs` (`fold.rs:993-1000`) and `scc_use` (`fold.rs:627-632`): `spare_sgprs` relies solely on `rdna2::sgpr_uses`, which skips SDWA `VSRC0` (`S0=1`), `VSRC1` (`S1=1`), and `VOPC_VOP_SDWA_SDST_ENC` `SDST` (`SD=1`) (`rdna2.rs:554-559`), allowing live SDWA-only SGPRs (such as a `VOPC` SDWA destination pair) to be allocated as spare `x.e`/`jp`/`save`/`swap`/`t`. Likewise `scc_use` (`fold.rs:630`) checks `VSRC0 == 253` (`d.words[1] & 0xFF`) but misses `S1=1` with `VSRC1 == 253` (`d.words[0] >> 9 & 0xFF`), allowing SCC-clobbering rewrites while `SCC` is live into an SDWA `VSRC1`. performance: Two 60 s release smokes on title 29640639 vs clean base 1c8b551475e1 (1462 frames, presents per 2 s last 3: 48 53 59, peak commit 16043 MB): default (switch unset) ran 1638 frames (+12.0%, steady 60 60 61, peak commit 16563 MB, +3.2%, 0 removals, 0 crashes); opt-in `XCL_WAVE64_FOLD=1` ran 1651 frames (+12.9% vs base, +0.8% vs default, steady 60 60 60, peak commit 14953 MB, -6.8% vs base, 0 removals, 0 crashes; 1 logged fallback `[SHADER] wave64 fold: no spare scalar registers`). Default (switch unset): ``` xcl-smoke v1 commit: d6993aa0d7f42f8bedf2c6ae93ede6cb7f790b08 gpu: NVIDIA GeForce RTX 4060 title: 29640639 seconds: 60 exit: 0x0 frames shown: 1638 (PresentX 1638) presents per 2 s (last 3): 60 60 61 device removals: 0 crashes: 0 peak commit: 16563 MB ``` Opt-in (`XCL_WAVE64_FOLD=1`): ``` xcl-smoke v1 commit: d6993aa0d7f42f8bedf2c6ae93ede6cb7f790b08 gpu: NVIDIA GeForce RTX 4060 title: 29640639 seconds: 60 exit: 0x0 frames shown: 1651 (PresentX 1651) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 14953 MB ``` verdict: not yet: silent miscompilations in fold.rs (missing EXEC side.writes on v_cmpx/v_cmp-to-exec at lines 405/434/455, missing t.exec on SDWA v_cmp SDST=EXEC_LO at lines 407-412, and missed SDWA SGPR/SCC operands in spare_sgprs and scc_use) hardware / tool and model: NVIDIA GeForce RTX 4060 8 GB (driver 621.40), Intel Core i5-11400F, 32 GB RAM, Windows 11 Build 26200, Rust 1.100.1 MSVC, DXC 1.9.2602.17 / Antigravity (Gemini 4 Neon)
Foniass commented 2026-12-02 13:48:45 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T13:48:45Z.


Follow-up review (head 8f236eca, since 913af192, diff read, not a merge-check; checks red):

  • Earlier points: unchanged. git range-diff shows the own commit changed only where main moved under it (the XCL_WAVE64_IDIOMS warm setting and cache tag now sit next to this PR's own in shaders.rs / kernel.rs); this push is a rebase.

New: none.

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

<!-- greyfinch-sync:ivall/xcl:comment:7347500100 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7347500100). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T13:48:45Z. --- Follow-up review (head 8f236eca, since 913af192, diff read, not a merge-check; checks red): - **Earlier points:** unchanged. `git range-diff` shows the own commit changed only where `main` moved under it (the `XCL_WAVE64_IDIOMS` warm setting and cache tag now sit next to this PR's own in `shaders.rs` / `kernel.rs`); this push is a rebase. New: none. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
bmjask commented 2026-12-02 14:53:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T14:53:50Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 712

@@ -0,0 +1,1158 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))

High: A v_cmpx (or a VOP3 v_cmp into EXEC) only sets t.exec and never adds EXEC_LO to its lower copy's writes, so joins lets it join a run whose earlier instructions read the console's EXEC_LO. Their upper copies read it through x.e, which lower_copies has already overwritten with the post-cmpx EXEC. In the run v_mbcnt_lo_u32_b32 v0, exec_lo, 0; v_mbcnt_hi_u32_b32 v0, exec_hi, v0; v_cmpx_gt_u32 16, v0, the order is lower copies, then s_mov e, exec_lo (the new E.lo), then the upper copy of mbcnt_lo, which is v_bcnt(x.e) and counts the post-cmpx mask instead of the original. Lanes 32..63 get the wrong prefix count and the wrong lanes pass the v_cmpx. The same happens for v_mov_b32 v1, exec_lo or v_cndmask ..., exec followed by a v_cmpx in one run. Adding EXEC_LO to the cmpx's writes would keep it out of such runs.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771456158 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4771456158). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T14:53:50Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 712 ~~~~diff @@ -0,0 +1,1158 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) ~~~~ --- **High**: A v_cmpx (or a VOP3 v_cmp into EXEC) only sets `t.exec` and never adds EXEC_LO to its lower copy's `writes`, so `joins` lets it join a run whose earlier instructions read the console's EXEC_LO. Their upper copies read it through `x.e`, which `lower_copies` has already overwritten with the post-cmpx EXEC. In the run `v_mbcnt_lo_u32_b32 v0, exec_lo, 0; v_mbcnt_hi_u32_b32 v0, exec_hi, v0; v_cmpx_gt_u32 16, v0`, the order is lower copies, then `s_mov e, exec_lo` (the new E.lo), then the upper copy of mbcnt_lo, which is `v_bcnt(x.e)` and counts the post-cmpx mask instead of the original. Lanes 32..63 get the wrong prefix count and the wrong lanes pass the v_cmpx. The same happens for `v_mov_b32 v1, exec_lo` or `v_cndmask ..., exec` followed by a v_cmpx in one run. Adding EXEC_LO to the cmpx's `writes` would keep it out of such runs.
bmjask commented 2026-12-02 14:53:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T14:53:50Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 368

@@ -0,0 +1,1158 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 => Ok(code),

High: In mask9, negative inline integers (codes 193..=208) are kept as they are for the upper half, but a 64-bit mask from an inline -k sign-extends, so its high dword is always 0xFFFFFFFF (code 193), not -k. v_cndmask_b32_e64 v0, v1, v2, -2 (mask 0xFFFF_FFFF_FFFF_FFFE) gives the upper copy selector 0xFFFFFFFE, so console lane 32 takes v1 instead of v2. The same goes for v_add_co_ci_u32_e64 with a carry-in of -2..-16. The SAVEEXEC path (~923) maps these codes to int(-1) correctly, so mapping 193..=208 to 193 here would match it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771456166 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4771456166). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T14:53:50Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 368 ~~~~diff @@ -0,0 +1,1158 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 => Ok(code), ~~~~ --- **High**: In `mask9`, negative inline integers (codes 193..=208) are kept as they are for the upper half, but a 64-bit mask from an inline -k sign-extends, so its high dword is always 0xFFFFFFFF (code 193), not -k. `v_cndmask_b32_e64 v0, v1, v2, -2` (mask 0xFFFF_FFFF_FFFF_FFFE) gives the upper copy selector 0xFFFFFFFE, so console lane 32 takes v1 instead of v2. The same goes for `v_add_co_ci_u32_e64` with a carry-in of -2..-16. The SAVEEXEC path (~923) maps these codes to `int(-1)` correctly, so mapping 193..=208 to 193 here would match it.
bmjask commented 2026-12-02 14:53:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T14:53:50Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 1151

@@ -0,0 +1,1158 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))
+    }
+
+    fn push(&mut self, t: Twin) {
+        if !self.joins(&t) {
+            self.flush();
+        }
+        let last = t.exec || t.store || t.upper_first;
+        self.run.push(t);
+        if last {
+            self.flush();
+        }
+    }
+
+    /// Writes the run: lanes 0..31, then 32..63.
+    fn flush(&mut self) {
+        let run = std::mem::take(&mut self.run);
+        if run.is_empty() {
+            return;
+        }
+        let exec = run.iter().any(|t| t.exec);
+        let vcc = run.iter().any(|t| t.vcc);
+        if run.iter().any(|t| t.upper_first) {
+            self.upper_copies(&run, exec, vcc);
+            self.lower_copies(&run, exec);
+        } else {
+            self.lower_copies(&run, exec);
+            self.upper_copies(&run, exec, vcc);
+        }
+    }
+
+    fn lower_copies(&mut self, run: &[Twin], exec: bool) {
+        let e = self.x.e;
+        self.out.mov(EXEC_LO, e);
+        for t in run {
+            self.out.words.extend(&t.a.words);
+        }
+        if exec {
+            self.out.mov(e, EXEC_LO);
+        }
+    }
+
+    fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) {
+        let e = self.x.e;
+        if vcc {
+            self.swap_vcc();
+        }
+        self.out.mov(EXEC_LO, e + 1);
+        for t in run {
+            self.out.words.extend(&t.b.words);
+        }
+        if exec {
+            self.out.mov(e + 1, EXEC_LO);
+        }
+        if vcc {
+            self.swap_vcc();
+        }
+    }
+
+    /// Lane reads and writes: each half's lane is in its own twin.
+    fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> {
+        let x = self.x;
+        let (n, e) = (x.n, x.e);
+        let [t0, t1, t2] = x.t;
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        let src = |code: u32| -> Result<Src, Why> {
+            match code {
+                0..=127 => Ok(sgpr(scalar(code as u8, &x))),
+                255 => Ok(Src::Lit(d.literal.unwrap_or(0))),
+                128..=208 | 240..=248 => Ok(Src::Code(code as u16)),
+                _ => Err("an operand a lane instruction cannot have"),
+            }
+        };
+        // the lane's half (1: the twins) and number there, for a constant lane
+        let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32));
+        let (s0, lane) = (f("SRC0"), f("SRC1"));
+        match d.inst.name {
+            "V_WRITELANE_B32" => {
+                let reg = f("VDST");
+                twin(reg, Half::B, &x)?;
+                let s = src(s0)?;
+                if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s);
+                    self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1));
+                    self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2));
+                    self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2));
+                    self.restore(live);
+                } else {
+                    return Err("a lane write to a lane given otherwise");
+                }
+            }
+            name => {
+                let dst = scalar(f("VDST") as u8, &x);
+                if s0 < 256 {
+                    self.out.sop1("S_MOV_B32", dst, src(s0)?);
+                    return Ok(());
+                }
+                let reg = s0 - 256;
+                twin(reg, Half::B, &x)?;
+                if name == "V_READFIRSTLANE_B32" {
+                    self.out.mov(EXEC_LO, e);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg));
+                    self.out.mov(EXEC_LO, e + 1);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n));
+                    self.save(live);
+                    // the upper half's only where no lane of the lower half is active
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0));
+                    self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1));
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else {
+                    return Err("a lane read of a lane given otherwise");
+                }
+            }
+        }
+        Ok(())
+    }
+
+    /// A scalar instruction (the console's EXEC renamed to E).
+    fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> {
+        let name = d.inst.name;
+        let x = self.x;
+        let e = x.e;
+        let [t0, t1, t2] = x.t;
+        let next = d.pc + d.len as u64;
+        match (d.enc.name, flow) {
+            ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live),
+            ("ENC_SOPP", Flow::Branch(t)) => {
+                let (lo, hi) = match name {
+                    "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live),
+                    "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1),
+                    "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI),
+                    _ => return Err("a debug branch"),
+                };
+                let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ");
+                let on_zero = if name.ends_with("NZ") { nzb } else { zb };
+                if !live {
+                    self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi));
+                    return self.jump(on_zero, t, d.pc, live);
+                }
+                // SCC stays the console's: one dword at a time
+                self.out.mov(EXEC_LO, lo);
+                if on_zero == zb {
+                    self.out.branch(nzb, next, d.pc);
+                } else {
+                    self.jump(nzb, t, d.pc, live)?;
+                }
+                self.out.mov(EXEC_LO, hi);
+                return self.jump(on_zero, t, d.pc, live);
+            }
+            ("ENC_SOPP", _) => {
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SMEM", _) => {
+                let (r, w) = rdna2::sgpr_uses(d);
+                if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) {
+                    return Err("EXEC as a scalar memory operand");
+                }
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {}
+            _ => return Err("an unexpected scalar encoding"),
+        }
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        if name == "S_GETPC_B64" {
+            // the console's address, which its constant data is found from
+            let dst = scalar(f("SDST") as u8, &x);
+            let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1);
+            self.out.sop1("S_GETPC_B64", dst, int(0));
+            self.save(live);
+            self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32));
+            self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 }));
+            self.restore(live);
+            return Ok(());
+        }
+        if let Flow::Jump(t) = flow {
+            return self.jump("S_BRANCH", t, d.pc, live);
+        }
+        if name.starts_with("S_MOVREL") {
+            return Err("a relative register move");
+        }
+        if name.ends_with("EXEC_B32") {
+            return Err("a wave32 EXEC operation in a wave64 program");
+        }
+        if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) {
+            let (lo, hi) = match f("SSRC0") {
+                c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)),
+                c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)),
+                c @ 128..=192 => (Src::Code(c as u16), int(0)),
+                c @ 193..=208 => (Src::Code(c as u16), int(-1)),
+                255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)),
+                _ => return Err("a float or special constant as a 64-bit scalar operand"),
+            };
+            // (operation, whether EXEC is its first operand)
+            let (op, exec_first) = match stem {
+                "S_AND" => ("S_AND_B32", false),
+                "S_OR" => ("S_OR_B32", false),
+                "S_XOR" => ("S_XOR_B32", false),
+                "S_ANDN2" => ("S_ANDN2_B32", false),
+                "S_ORN2" => ("S_ORN2_B32", false),
+                "S_NAND" => ("S_NAND_B32", false),
+                "S_NOR" => ("S_NOR_B32", false),
+                "S_XNOR" => ("S_XNOR_B32", false),
+                "S_ANDN1" => ("S_ANDN2_B32", true),
+                "S_ORN1" => ("S_ORN2_B32", true),
+                _ => return Err("an EXEC operation the rewrite does not know"),
+            };
+            for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() {
+                let ek = sgpr(e + k as u8);
+                if exec_first {
+                    self.out.sop2(op, t, ek, s);
+                } else {
+                    self.out.sop2(op, t, s, ek);
+                }
+            }
+            let dst = f("SDST") as u8;
+            let old = name.contains("SAVEEXEC");
+            if old && dst != NULL {
+                self.out.mov(scalar(dst, &x), e);
+                self.out.mov(scalar(dst, &x) + 1, e + 1);
+            }
+            self.out.mov(e, t0);
+            self.out.mov(e + 1, t1);
+            if !old && dst != NULL {
+                self.out.mov(scalar(dst, &x), t0);
+                self.out.mov(scalar(dst, &x) + 1, t1);
+            }
+            if live {
+                self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1));
+            }
+            return Ok(());
+        }
+        let mut w = d.words.clone();
+        let mut rename = |shift: u32, bits: u32| -> Result<(), Why> {
+            let m = (1 << bits) - 1;
+            let c = w[0] >> shift & m;
+            let c = match c {
+                251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"),
+                0..=127 => u32::from(scalar(c as u8, &x)),
+                _ => c,
+            };
+            w[0] = w[0] & !(m << shift) | c << shift;
+            Ok(())
+        };
+        if d.enc.name != "ENC_SOPC" {
+            rename(16, 7)?;
+        }
+        if d.enc.name != "ENC_SOPK" {
+            rename(0, 8)?;
+        }
+        if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") {
+            rename(8, 8)?;
+        }
+        self.out.words.extend(&w);
+        Ok(())
+    }
+}
+
+/// Seven scalar registers no instruction of the program names: two pairs, five single ones.
+fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> {
+    let mut used = [false; 128];
+    for d in list {
+        let (r, w) = rdna2::sgpr_uses(d);
+        for c in r.into_iter().chain(w) {
+            used[c as usize] = true;
+        }
+    }
+    let mut free = (0..=105u8).rev().filter(|&c| !used[usize::from(c)]);
+    let mut pairs = [0u8; 2];
+    let mut rest = Vec::new();
+    let mut k = 0;
+    while k < 2 || rest.len() < 5 {
+        let c = free.next().ok_or("no spare scalar registers")?;
+        if k < 2 && c % 2 == 1 && c > 0 && !used[usize::from(c - 1)] {
+            free.next();
+            pairs[k] = c - 1;
+            k += 1;
+        } else {
+            rest.push(c);
+        }
+    }
+    Ok((pairs, [rest[0], rest[1], rest[2], rest[3], rest[4]]))
+}
+
+/// The program's VGPR count: one past the highest it names.
+fn vgprs(list: &[Decoded]) -> u32 {
+    list.iter()
+        .flat_map(|d| {
+            let (r, w) = rdna2::vgpr_uses(d);
+            let tfe = u64::from(field_value(d.enc, &d.words, "TFE") == Some(1));
+            r.into_iter().chain(w.into_iter().map(move |v| v + tfe))
+        })
+        .max()
+        .map_or(0, |v| v as u32 + 1)
+}
+
+fn emit(list: &[Decoded], flows: &[Flow], leaders: &HashSet<u64>, live: &[bool], x: Spare, far: &HashSet<u64>) -> Result<(Vec<u32>, Vec<u64>), Why> {
+    let mut f = Fold { x, out: Asm::default(), run: Vec::new(), far };
+    f.out.mov(x.e, EXEC_LO);
+    f.out.mov(x.e + 1, EXEC_HI);
+    let mut at: HashMap<u64, usize> = HashMap::new();
+    for (i, d) in list.iter().enumerate() {
+        if leaders.contains(&d.pc) {
+            f.flush();
+        }
+        at.insert(d.pc, f.out.words.len());
+        let name = d.inst.name;
+        if matches!(name, "S_NOP" | "S_INST_PREFETCH" | "S_CLAUSE" | "V_NOP" | "V_PIPEFLUSH" | "V_CLREXCP") || name.starts_with("S_WAITCNT") {
+            continue;
+        }
+        match d.enc.name {
+            "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" | "ENC_VOP3" | "ENC_VOP3P" | "VOP3_SDST_ENC" => match name {
+                "V_READLANE_B32" | "V_WRITELANE_B32" | "V_READFIRSTLANE_B32" => {
+                    f.flush();
+                    f.lanes(d, live[i])?;
+                }
+                "V_MBCNT_LO_U32_B32" | "V_MBCNT_HI_U32_B32" => f.push(mbcnt(d, &x)?),
+                _ if name.starts_with("V_INTERP") || name.starts_with("V_MOVREL") || name == "V_SWAPREL_B32" => {
+                    return Err("an interpolation or a relative register move");
+                }
+                _ => {
+                    let mut t = Twin::default();
+                    t.a = valu_copy(d, Half::A, &x, &mut t)?;
+                    t.b = match valu_copy(d, Half::B, &x, &mut t) {
+                        Err(NEEDS_SWAP) => {
+                            t.vcc = true;
+                            t.store = true;
+                            valu_copy(d, Half::BSwap, &x, &mut t)?
+                        }
+                        b => b?,
+                    };
+                    f.push(t.ordered()?);
+                }
+            },
+            "ENC_DS" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => {
+                let t = Twin { a: memory_copy(d, Half::A, &x)?, b: memory_copy(d, Half::B, &x)?, store: writes_memory(d), ..Twin::default() };
+                f.push(t);
+            }
+            "ENC_VINTRP" | "ENC_EXP" => return Err("an interpolation or export"),
+            _ => {
+                f.flush();
+                f.scalar_inst(d, live[i], flows[i])?;
+            }
+        }
+    }
+    f.flush();
+    // branches; the console instructions whose branches do not reach
+    let mut words = f.out.words;
+    let mut short = Vec::new();
+    for &(w, to, origin) in &f.out.branches {
+        let to = *at.get(&to).ok_or("a branch into an instruction")?;
+        match i16::try_from(to as i64 - (w as i64 + 1)) {
+            Ok(delta) => words[w] = words[w] & 0xFFFF_0000 | u32::from(delta as u16),
+            Err(_) => short.push(origin),
+        }
+    }
+    for &(w, to) in &f.out.far {
+        let to = *at.get(&to).ok_or("a branch into an instruction")?;
+        // from the address `s_getpc_b64` gives, the next instruction's
+        let delta = 4 * (to as i64 - (w as i64 + 1));
+        words[w + 2] = delta as u32;
+        words[w + 3] = words[w + 3] & !0xFF00 | if delta < 0 { 193 } else { 128 } << 8;
+    }
+    Ok((words, short))
+}
+
+/// `code` (a console wave64 compute program of interface `cs`) as a wave32 program of the
+/// same effects (see the module), or what the rewrite does not cover.
+pub fn fold(code: &[u8], cs: &CsInterface) -> Result<Folded, Why> {
+    let mut list = Vec::new();
+    let mut off = 0;
+    while off + 4 <= code.len() {
+        let d = rdna2::decode(&code[off..], off as u64).map_err(|_| "code that does not decode")?;
+        off += d.len;
+        list.push(d);
+    }
+    rdna2::resolve_far_jumps(&mut list);
+    let n = vgprs(&list).max(cs.tid_components);
+    if 2 * n > HOST_REGISTERS {
+        return Err("too many VGPRs for two lanes per host lane");
+    }
+    let index: HashMap<u64, usize> = list.iter().enumerate().map(|(i, d)| (d.pc, i)).collect();
+    let mut flows = Vec::with_capacity(list.len());
+    let mut succs = Vec::with_capacity(list.len());
+    let mut leaders = HashSet::new();
+    for (i, d) in list.iter().enumerate() {
+        let fl = flow(d)?;
+        let next = (i + 1 < list.len()).then_some(i + 1);
+        let to = |t: u64| index.get(&t).copied().ok_or("a branch into an instruction");
+        succs.push(match fl {
+            Flow::Next => next.into_iter().collect(),
+            Flow::Stop => vec![],
+            Flow::Jump(t) => vec![to(t)?],
+            Flow::Branch(t) => std::iter::once(to(t)?).chain(next).collect(),
+        });
+        if let Flow::Jump(t) | Flow::Branch(t) = fl {
+            leaders.insert(t);
+        }
+        if fl != Flow::Next {
+            leaders.insert(d.pc + d.len as u64);
+        }
+        flows.push(fl);
+    }
+    let live = scc_live(&list, &succs);
+    let ([e, jp], rest) = spare_sgprs(&list)?;
+    let x = Spare { n, e, save: rest[0], swap: rest[1], t: [rest[2], rest[3], rest[4]], jp };
+    let mut far = HashSet::new();
+    let words = loop {
+        let (words, short) = emit(&list, &flows, &leaders, &live, x, &far)?;
+        if short.is_empty() {
+            break words;
+        }
+        far.extend(short);
+    };
+    let total: u32 = cs.threads.iter().product();
+    Ok(Folded {
+        code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
+        cs: CsInterface { threads: [total.div_ceil(64) * 32, 1, 1], tid_components: 1, ..cs.clone() },

Medium: The folded host group has half the console's threads (total.div_ceil(64) * 32), and loop_passes (kernel.rs:558) divides the dispatch's loop budget by the host's numthreads, so each loop of a folded program gets about twice the split form's pass cap while each pass does two console lanes' work. For a 256-thread wave64 program with a runaway or very long loop, the split form caps it at share/256 passes and the folded form at share/128. The GPU-time bound IO_LOOP_BUDGET gives roughly doubles, which makes a TDR / device removal more likely on the hang-prone titles this form targets. Dividing by the console thread count would keep the cap the same.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771456178 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4771456178). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T14:53:50Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 1151 ~~~~diff @@ -0,0 +1,1158 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) + } + + fn push(&mut self, t: Twin) { + if !self.joins(&t) { + self.flush(); + } + let last = t.exec || t.store || t.upper_first; + self.run.push(t); + if last { + self.flush(); + } + } + + /// Writes the run: lanes 0..31, then 32..63. + fn flush(&mut self) { + let run = std::mem::take(&mut self.run); + if run.is_empty() { + return; + } + let exec = run.iter().any(|t| t.exec); + let vcc = run.iter().any(|t| t.vcc); + if run.iter().any(|t| t.upper_first) { + self.upper_copies(&run, exec, vcc); + self.lower_copies(&run, exec); + } else { + self.lower_copies(&run, exec); + self.upper_copies(&run, exec, vcc); + } + } + + fn lower_copies(&mut self, run: &[Twin], exec: bool) { + let e = self.x.e; + self.out.mov(EXEC_LO, e); + for t in run { + self.out.words.extend(&t.a.words); + } + if exec { + self.out.mov(e, EXEC_LO); + } + } + + fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) { + let e = self.x.e; + if vcc { + self.swap_vcc(); + } + self.out.mov(EXEC_LO, e + 1); + for t in run { + self.out.words.extend(&t.b.words); + } + if exec { + self.out.mov(e + 1, EXEC_LO); + } + if vcc { + self.swap_vcc(); + } + } + + /// Lane reads and writes: each half's lane is in its own twin. + fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> { + let x = self.x; + let (n, e) = (x.n, x.e); + let [t0, t1, t2] = x.t; + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + let src = |code: u32| -> Result<Src, Why> { + match code { + 0..=127 => Ok(sgpr(scalar(code as u8, &x))), + 255 => Ok(Src::Lit(d.literal.unwrap_or(0))), + 128..=208 | 240..=248 => Ok(Src::Code(code as u16)), + _ => Err("an operand a lane instruction cannot have"), + } + }; + // the lane's half (1: the twins) and number there, for a constant lane + let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32)); + let (s0, lane) = (f("SRC0"), f("SRC1")); + match d.inst.name { + "V_WRITELANE_B32" => { + let reg = f("VDST"); + twin(reg, Half::B, &x)?; + let s = src(s0)?; + if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s); + self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1)); + self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2)); + self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2)); + self.restore(live); + } else { + return Err("a lane write to a lane given otherwise"); + } + } + name => { + let dst = scalar(f("VDST") as u8, &x); + if s0 < 256 { + self.out.sop1("S_MOV_B32", dst, src(s0)?); + return Ok(()); + } + let reg = s0 - 256; + twin(reg, Half::B, &x)?; + if name == "V_READFIRSTLANE_B32" { + self.out.mov(EXEC_LO, e); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg)); + self.out.mov(EXEC_LO, e + 1); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n)); + self.save(live); + // the upper half's only where no lane of the lower half is active + self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0)); + self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1)); + self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else { + return Err("a lane read of a lane given otherwise"); + } + } + } + Ok(()) + } + + /// A scalar instruction (the console's EXEC renamed to E). + fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> { + let name = d.inst.name; + let x = self.x; + let e = x.e; + let [t0, t1, t2] = x.t; + let next = d.pc + d.len as u64; + match (d.enc.name, flow) { + ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live), + ("ENC_SOPP", Flow::Branch(t)) => { + let (lo, hi) = match name { + "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live), + "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1), + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI), + _ => return Err("a debug branch"), + }; + let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ"); + let on_zero = if name.ends_with("NZ") { nzb } else { zb }; + if !live { + self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi)); + return self.jump(on_zero, t, d.pc, live); + } + // SCC stays the console's: one dword at a time + self.out.mov(EXEC_LO, lo); + if on_zero == zb { + self.out.branch(nzb, next, d.pc); + } else { + self.jump(nzb, t, d.pc, live)?; + } + self.out.mov(EXEC_LO, hi); + return self.jump(on_zero, t, d.pc, live); + } + ("ENC_SOPP", _) => { + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SMEM", _) => { + let (r, w) = rdna2::sgpr_uses(d); + if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) { + return Err("EXEC as a scalar memory operand"); + } + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {} + _ => return Err("an unexpected scalar encoding"), + } + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + if name == "S_GETPC_B64" { + // the console's address, which its constant data is found from + let dst = scalar(f("SDST") as u8, &x); + let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1); + self.out.sop1("S_GETPC_B64", dst, int(0)); + self.save(live); + self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32)); + self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 })); + self.restore(live); + return Ok(()); + } + if let Flow::Jump(t) = flow { + return self.jump("S_BRANCH", t, d.pc, live); + } + if name.starts_with("S_MOVREL") { + return Err("a relative register move"); + } + if name.ends_with("EXEC_B32") { + return Err("a wave32 EXEC operation in a wave64 program"); + } + if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) { + let (lo, hi) = match f("SSRC0") { + c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)), + c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)), + c @ 128..=192 => (Src::Code(c as u16), int(0)), + c @ 193..=208 => (Src::Code(c as u16), int(-1)), + 255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)), + _ => return Err("a float or special constant as a 64-bit scalar operand"), + }; + // (operation, whether EXEC is its first operand) + let (op, exec_first) = match stem { + "S_AND" => ("S_AND_B32", false), + "S_OR" => ("S_OR_B32", false), + "S_XOR" => ("S_XOR_B32", false), + "S_ANDN2" => ("S_ANDN2_B32", false), + "S_ORN2" => ("S_ORN2_B32", false), + "S_NAND" => ("S_NAND_B32", false), + "S_NOR" => ("S_NOR_B32", false), + "S_XNOR" => ("S_XNOR_B32", false), + "S_ANDN1" => ("S_ANDN2_B32", true), + "S_ORN1" => ("S_ORN2_B32", true), + _ => return Err("an EXEC operation the rewrite does not know"), + }; + for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() { + let ek = sgpr(e + k as u8); + if exec_first { + self.out.sop2(op, t, ek, s); + } else { + self.out.sop2(op, t, s, ek); + } + } + let dst = f("SDST") as u8; + let old = name.contains("SAVEEXEC"); + if old && dst != NULL { + self.out.mov(scalar(dst, &x), e); + self.out.mov(scalar(dst, &x) + 1, e + 1); + } + self.out.mov(e, t0); + self.out.mov(e + 1, t1); + if !old && dst != NULL { + self.out.mov(scalar(dst, &x), t0); + self.out.mov(scalar(dst, &x) + 1, t1); + } + if live { + self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1)); + } + return Ok(()); + } + let mut w = d.words.clone(); + let mut rename = |shift: u32, bits: u32| -> Result<(), Why> { + let m = (1 << bits) - 1; + let c = w[0] >> shift & m; + let c = match c { + 251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"), + 0..=127 => u32::from(scalar(c as u8, &x)), + _ => c, + }; + w[0] = w[0] & !(m << shift) | c << shift; + Ok(()) + }; + if d.enc.name != "ENC_SOPC" { + rename(16, 7)?; + } + if d.enc.name != "ENC_SOPK" { + rename(0, 8)?; + } + if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") { + rename(8, 8)?; + } + self.out.words.extend(&w); + Ok(()) + } +} + +/// Seven scalar registers no instruction of the program names: two pairs, five single ones. +fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> { + let mut used = [false; 128]; + for d in list { + let (r, w) = rdna2::sgpr_uses(d); + for c in r.into_iter().chain(w) { + used[c as usize] = true; + } + } + let mut free = (0..=105u8).rev().filter(|&c| !used[usize::from(c)]); + let mut pairs = [0u8; 2]; + let mut rest = Vec::new(); + let mut k = 0; + while k < 2 || rest.len() < 5 { + let c = free.next().ok_or("no spare scalar registers")?; + if k < 2 && c % 2 == 1 && c > 0 && !used[usize::from(c - 1)] { + free.next(); + pairs[k] = c - 1; + k += 1; + } else { + rest.push(c); + } + } + Ok((pairs, [rest[0], rest[1], rest[2], rest[3], rest[4]])) +} + +/// The program's VGPR count: one past the highest it names. +fn vgprs(list: &[Decoded]) -> u32 { + list.iter() + .flat_map(|d| { + let (r, w) = rdna2::vgpr_uses(d); + let tfe = u64::from(field_value(d.enc, &d.words, "TFE") == Some(1)); + r.into_iter().chain(w.into_iter().map(move |v| v + tfe)) + }) + .max() + .map_or(0, |v| v as u32 + 1) +} + +fn emit(list: &[Decoded], flows: &[Flow], leaders: &HashSet<u64>, live: &[bool], x: Spare, far: &HashSet<u64>) -> Result<(Vec<u32>, Vec<u64>), Why> { + let mut f = Fold { x, out: Asm::default(), run: Vec::new(), far }; + f.out.mov(x.e, EXEC_LO); + f.out.mov(x.e + 1, EXEC_HI); + let mut at: HashMap<u64, usize> = HashMap::new(); + for (i, d) in list.iter().enumerate() { + if leaders.contains(&d.pc) { + f.flush(); + } + at.insert(d.pc, f.out.words.len()); + let name = d.inst.name; + if matches!(name, "S_NOP" | "S_INST_PREFETCH" | "S_CLAUSE" | "V_NOP" | "V_PIPEFLUSH" | "V_CLREXCP") || name.starts_with("S_WAITCNT") { + continue; + } + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" | "ENC_VOP3" | "ENC_VOP3P" | "VOP3_SDST_ENC" => match name { + "V_READLANE_B32" | "V_WRITELANE_B32" | "V_READFIRSTLANE_B32" => { + f.flush(); + f.lanes(d, live[i])?; + } + "V_MBCNT_LO_U32_B32" | "V_MBCNT_HI_U32_B32" => f.push(mbcnt(d, &x)?), + _ if name.starts_with("V_INTERP") || name.starts_with("V_MOVREL") || name == "V_SWAPREL_B32" => { + return Err("an interpolation or a relative register move"); + } + _ => { + let mut t = Twin::default(); + t.a = valu_copy(d, Half::A, &x, &mut t)?; + t.b = match valu_copy(d, Half::B, &x, &mut t) { + Err(NEEDS_SWAP) => { + t.vcc = true; + t.store = true; + valu_copy(d, Half::BSwap, &x, &mut t)? + } + b => b?, + }; + f.push(t.ordered()?); + } + }, + "ENC_DS" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => { + let t = Twin { a: memory_copy(d, Half::A, &x)?, b: memory_copy(d, Half::B, &x)?, store: writes_memory(d), ..Twin::default() }; + f.push(t); + } + "ENC_VINTRP" | "ENC_EXP" => return Err("an interpolation or export"), + _ => { + f.flush(); + f.scalar_inst(d, live[i], flows[i])?; + } + } + } + f.flush(); + // branches; the console instructions whose branches do not reach + let mut words = f.out.words; + let mut short = Vec::new(); + for &(w, to, origin) in &f.out.branches { + let to = *at.get(&to).ok_or("a branch into an instruction")?; + match i16::try_from(to as i64 - (w as i64 + 1)) { + Ok(delta) => words[w] = words[w] & 0xFFFF_0000 | u32::from(delta as u16), + Err(_) => short.push(origin), + } + } + for &(w, to) in &f.out.far { + let to = *at.get(&to).ok_or("a branch into an instruction")?; + // from the address `s_getpc_b64` gives, the next instruction's + let delta = 4 * (to as i64 - (w as i64 + 1)); + words[w + 2] = delta as u32; + words[w + 3] = words[w + 3] & !0xFF00 | if delta < 0 { 193 } else { 128 } << 8; + } + Ok((words, short)) +} + +/// `code` (a console wave64 compute program of interface `cs`) as a wave32 program of the +/// same effects (see the module), or what the rewrite does not cover. +pub fn fold(code: &[u8], cs: &CsInterface) -> Result<Folded, Why> { + let mut list = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + let d = rdna2::decode(&code[off..], off as u64).map_err(|_| "code that does not decode")?; + off += d.len; + list.push(d); + } + rdna2::resolve_far_jumps(&mut list); + let n = vgprs(&list).max(cs.tid_components); + if 2 * n > HOST_REGISTERS { + return Err("too many VGPRs for two lanes per host lane"); + } + let index: HashMap<u64, usize> = list.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let mut flows = Vec::with_capacity(list.len()); + let mut succs = Vec::with_capacity(list.len()); + let mut leaders = HashSet::new(); + for (i, d) in list.iter().enumerate() { + let fl = flow(d)?; + let next = (i + 1 < list.len()).then_some(i + 1); + let to = |t: u64| index.get(&t).copied().ok_or("a branch into an instruction"); + succs.push(match fl { + Flow::Next => next.into_iter().collect(), + Flow::Stop => vec![], + Flow::Jump(t) => vec![to(t)?], + Flow::Branch(t) => std::iter::once(to(t)?).chain(next).collect(), + }); + if let Flow::Jump(t) | Flow::Branch(t) = fl { + leaders.insert(t); + } + if fl != Flow::Next { + leaders.insert(d.pc + d.len as u64); + } + flows.push(fl); + } + let live = scc_live(&list, &succs); + let ([e, jp], rest) = spare_sgprs(&list)?; + let x = Spare { n, e, save: rest[0], swap: rest[1], t: [rest[2], rest[3], rest[4]], jp }; + let mut far = HashSet::new(); + let words = loop { + let (words, short) = emit(&list, &flows, &leaders, &live, x, &far)?; + if short.is_empty() { + break words; + } + far.extend(short); + }; + let total: u32 = cs.threads.iter().product(); + Ok(Folded { + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + cs: CsInterface { threads: [total.div_ceil(64) * 32, 1, 1], tid_components: 1, ..cs.clone() }, ~~~~ --- **Medium**: The folded host group has half the console's threads (`total.div_ceil(64) * 32`), and `loop_passes` (kernel.rs:558) divides the dispatch's loop budget by the host's numthreads, so each loop of a folded program gets about twice the split form's pass cap while each pass does two console lanes' work. For a 256-thread wave64 program with a runaway or very long loop, the split form caps it at share/256 passes and the folded form at share/128. The GPU-time bound IO_LOOP_BUDGET gives roughly doubles, which makes a TDR / device removal more likely on the hang-prone titles this form targets. Dividing by the console thread count would keep the cap the same.
bmjask commented 2026-12-02 14:53:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T14:53:50Z.

Review: COMMENTED


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

  1. High crates/xcl/src/gpu/dxil/fold.rs:712: A v_cmpx (or a VOP3 v_cmp into EXEC) only sets t.exec and never adds EXEC_LO to its lower copy's writes, so joins lets it join a run whose earlier instructions read the console's EXEC_LO. (inline)
  2. High crates/xcl/src/gpu/dxil/fold.rs:368: In mask9, negative inline integers (codes 193..=208) are kept as they are for the upper half, but a 64-bit mask from an inline -k sign-extends, so its high dword is always 0xFFFFFFFF (code 193), not -k. (inline)
  3. Medium crates/xcl/src/gpu/dxil/fold.rs:1151: The folded host group has half the console's threads (total.div_ceil(64) * 32), and loop_passes (kernel.rs:558) divides the dispatch's loop budget by the host's numthreads, so each loop of a folded program gets about twice the split .... (inline)

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.

<!-- greyfinch-sync:ivall/xcl:review:6153222637 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#pullrequestreview-6153222637). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T14:53:50Z. **Review:** COMMENTED --- Review of `8f236eca`: 3 finding(s) (2 high, 1 medium), most severe first. 1. **High** `crates/xcl/src/gpu/dxil/fold.rs:712`: A v_cmpx (or a VOP3 v_cmp into EXEC) only sets `t.exec` and never adds EXEC_LO to its lower copy's `writes`, so `joins` lets it join a run whose earlier instructions read the console's EXEC_LO. (inline) 2. **High** `crates/xcl/src/gpu/dxil/fold.rs:368`: In `mask9`, negative inline integers (codes 193..=208) are kept as they are for the upper half, but a 64-bit mask from an inline -k sign-extends, so its high dword is always 0xFFFFFFFF (code 193), not -k. (inline) 3. **Medium** `crates/xcl/src/gpu/dxil/fold.rs:1151`: The folded host group has half the console's threads (`total.div_ceil(64) * 32`), and `loop_passes` (kernel.rs:558) divides the dispatch's loop budget by the host's numthreads, so each loop of a folded program gets about twice the split .... (inline) --- _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._
bmjask commented 2026-12-02 14:53:52 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T14:53:52Z.


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

<!-- greyfinch-sync:ivall/xcl:comment:7349325250 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7349325250). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T14:53:52Z. --- @Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
Foniass commented 2026-12-02 21:01:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T21:01:44Z.


Follow-up review of ee2c186e, since 8f236eca (code reading only, not a merge-check; PR description red) · 1 high, 1 medium, 2 nits

In short: Since 8f236eca the first commit has three real fixes, each with a test:

  • a v_cmpx now records its EXEC write, so an earlier instruction in the same run that reads EXEC no longer has its upper copy see the new value (fold.rs ~512);
  • a negative inline integer used as a 64-bit mask now gives an all-ones upper dword (~368);
  • a folded program's loop-pass share is divided by the console group's thread count (kernel.rs ~558).

The code reads right. The size, the interpreter-only GPU tests and the compact-limit refusal are still open. The smoke blocks name 8f236eca, not this head (PR description is red).

High

  1. Please split it (still open). 2,056 changed lines (fold.rs 1,162, fold_tests.rs 793), none generated. The new "Why it is one pull request" section argues against splitting off the preparation and the wiring, but not against splitting fold.rs itself, which the closed #3529 / #3530 / #3543 stack did with the same port. One possible stack:
    • preparation with no behaviour change: compact::wanted_plan / fits, the groups / last fields of ComputeStart, and the fold parameter of translate_entry_with;
    • the rewrite of scalar code and vector runs, refusing lane instructions, with the interpreter tests for the programs it covers;
    • v_readlane / v_writelane / v_readfirstlane / v_mbcnt with their test programs;
    • turning it on: translate_folded behind XCL_WAVE64_FOLD=1, the compact-limit refusal, the warm setting, README and docs;
    • the wave64_fold_census count.

Medium

  1. GPU tests compare only with the PR's own interpreter (still open). gpu_folded_wave64_matches_the_console_wave (fold_tests.rs ~542-561) takes want from this PR's interpreter, not from the split form's output on the same GPU. The interpreter and the rewrite can agree on the same misreading of an instruction.

Nit

  1. Compact-limit refusal (still open). kernel.rs ~492 refuses folding whenever the folded wanted_plan does not fit, even when the split form's tables do not fit either. It only loses a fold, and only with the switch on.
  2. Stale text.
    • The first commit (ef027c50a) still says "XCL_WAVE64_FOLD=0 turns the form off" and "more than 128 VGPRs"; both are wrong at this head.
    • The description says the GPU test runs "five programs", but programs() (~238) now has seven.
    • Not tested lists "Native Windows" although the Regression run was on Windows 11, and it does not say whether XCL_WAVE64_FOLD=1 was set for the PR's smoke run.
Checked and fine
  • Earlier finding fixed: folding is opt-in with XCL_WAVE64_FOLD=1 (fold.rs ~47-56), part of the translated cache tag (kernel.rs ~117) and of the warm settings, with a test.
  • Earlier finding fixed: the VGPR limit is 2 * n > HOST_REGISTERS (~1116).
  • The v_cmpx EXEC write in side.writes (~512-514) makes joins flush the run when an earlier upper copy reads EXEC. Covered by exec_read_then_cmpx.
  • mask9 maps inline -1..-16 to -1 for the upper dword, and the interpreter now reads an inline or literal SRC2 mask through src64, so inline_masks compares against the right value.
  • loop_passes divides by the console group's threads when folded, like the split form. Covered by a_folded_loop_has_the_passes_of_the_console_threads.
  • Commits 2-6 are unchanged since 8f236eca. No other open PR makes this change; #3561 is a different form for the same exchange cost.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7358684390 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7358684390). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T21:01:44Z. --- **Follow-up review** of `ee2c186e`, since `8f236eca` (code reading only, not a merge-check; `PR description` red) · 1 high, 1 medium, 2 nits **In short:** Since `8f236eca` the first commit has three real fixes, each with a test: - a `v_cmpx` now records its EXEC write, so an earlier instruction in the same run that reads EXEC no longer has its upper copy see the new value (`fold.rs` ~512); - a negative inline integer used as a 64-bit mask now gives an all-ones upper dword (~368); - a folded program's loop-pass share is divided by the console group's thread count (`kernel.rs` ~558). The code reads right. The size, the interpreter-only GPU tests and the compact-limit refusal are still open. The smoke blocks name `8f236eca`, not this head (`PR description` is red). #### High 1. **Please split it (still open).** 2,056 changed lines (`fold.rs` 1,162, `fold_tests.rs` 793), none generated. The new "Why it is one pull request" section argues against splitting off the preparation and the wiring, but not against splitting `fold.rs` itself, which the closed #3529 / #3530 / #3543 stack did with the same port. One possible stack: - preparation with no behaviour change: `compact::wanted_plan` / `fits`, the `groups` / `last` fields of `ComputeStart`, and the `fold` parameter of `translate_entry_with`; - the rewrite of scalar code and vector runs, refusing lane instructions, with the interpreter tests for the programs it covers; - `v_readlane` / `v_writelane` / `v_readfirstlane` / `v_mbcnt` with their test programs; - turning it on: `translate_folded` behind `XCL_WAVE64_FOLD=1`, the compact-limit refusal, the warm setting, README and docs; - the `wave64_fold_census` count. #### Medium 2. **GPU tests compare only with the PR's own interpreter (still open).** `gpu_folded_wave64_matches_the_console_wave` (`fold_tests.rs` ~542-561) takes `want` from this PR's interpreter, not from the split form's output on the same GPU. The interpreter and the rewrite can agree on the same misreading of an instruction. #### Nit 3. **Compact-limit refusal (still open).** `kernel.rs` ~492 refuses folding whenever the folded `wanted_plan` does not fit, even when the split form's tables do not fit either. It only loses a fold, and only with the switch on. 4. **Stale text.** - The first commit (`ef027c50a`) still says "XCL_WAVE64_FOLD=0 turns the form off" and "more than 128 VGPRs"; both are wrong at this head. - The description says the GPU test runs "five programs", but `programs()` (~238) now has seven. - **Not tested** lists "Native Windows" although the **Regression run** was on Windows 11, and it does not say whether `XCL_WAVE64_FOLD=1` was set for the PR's smoke run. <details><summary>Checked and fine</summary> - Earlier finding fixed: folding is opt-in with `XCL_WAVE64_FOLD=1` (`fold.rs` ~47-56), part of the translated cache tag (`kernel.rs` ~117) and of the warm settings, with a test. - Earlier finding fixed: the VGPR limit is `2 * n > HOST_REGISTERS` (~1116). - The `v_cmpx` EXEC write in `side.writes` (~512-514) makes `joins` flush the run when an earlier upper copy reads EXEC. Covered by `exec_read_then_cmpx`. - `mask9` maps inline -1..-16 to -1 for the upper dword, and the interpreter now reads an inline or literal SRC2 mask through `src64`, so `inline_masks` compares against the right value. - `loop_passes` divides by the console group's threads when folded, like the split form. Covered by `a_folded_loop_has_the_passes_of_the_console_threads`. - Commits 2-6 are unchanged since `8f236eca`. No other open PR makes this change; #3561 is a different form for the same exchange cost. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
bmjask commented 2026-12-02 21:10:43 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T21:10:43Z.

Review: COMMENTED


Review of ee2c186e: 5 finding(s) (2 high, 3 medium), most severe first.

  1. High crates/xcl/src/gpu/dxil/fold.rs:593: MUBUF/MTBUF accesses without IDXEN are folded as-is, but the translator takes an ADD_TID_ENABLE buffer's index from self.lane (lower_mem.rs:1347-1356, 2029-2038), which in the folded wave32 program is the host lane 0..31 for both copie.... (inline)
  2. High crates/xcl/src/gpu/dxil/fold.rs:563: The ADDTID refusal is inside the "ENC_DS" match arm only, so GLOBAL_LOAD_DWORD_ADDTID and GLOBAL_STORE_DWORD_ADDTID (ENC_FLAT_GLBL) are folded, although their address comes from the implicit lane id (self.lane, lower_mem.rs:2153-2156.... (inline)
  3. Medium crates/xcl/src/gpu/dxil/fold.rs:1000: spare_sgprs gets its 'used' set from rdna2::sgpr_uses, which skips SRC0 for non-Plain variants (rdna2.rs:557) and never sees an SDWA S1 SGPR source or an SDWA VOPC SDST, so an SGPR the program uses only through SDWA can be chosen as .... (inline)
  4. Medium crates/xcl/src/gpu/dxil/fold.rs:898: SOPK branches such as S_SUBVECTOR_LOOP_BEGIN/END (F_BRANCH, so flow returns Flow::Branch) fall into the generic SOPK path and are copied verbatim. (inline)
  5. Medium crates/xcl/src/gpu/dxil/fold.rs:1027: vgprs() adds the extra write dword for TFE but not for MIMG LWE, and mimg_vgpr_uses counts neither, so N can be one too small and the status dword lands on a twin register. (inline)

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.

<!-- greyfinch-sync:ivall/xcl:review:6159079294 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#pullrequestreview-6159079294). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T21:10:43Z. **Review:** COMMENTED --- Review of `ee2c186e`: 5 finding(s) (2 high, 3 medium), most severe first. 1. **High** `crates/xcl/src/gpu/dxil/fold.rs:593`: MUBUF/MTBUF accesses without IDXEN are folded as-is, but the translator takes an ADD_TID_ENABLE buffer's index from `self.lane` (lower_mem.rs:1347-1356, 2029-2038), which in the folded wave32 program is the host lane 0..31 for both copie.... (inline) 2. **High** `crates/xcl/src/gpu/dxil/fold.rs:563`: The ADDTID refusal is inside the `"ENC_DS"` match arm only, so GLOBAL_LOAD_DWORD_ADDTID and GLOBAL_STORE_DWORD_ADDTID (ENC_FLAT_GLBL) are folded, although their address comes from the implicit lane id (`self.lane`, lower_mem.rs:2153-2156.... (inline) 3. **Medium** `crates/xcl/src/gpu/dxil/fold.rs:1000`: `spare_sgprs` gets its 'used' set from `rdna2::sgpr_uses`, which skips SRC0 for non-Plain variants (rdna2.rs:557) and never sees an SDWA S1 SGPR source or an SDWA VOPC SDST, so an SGPR the program uses only through SDWA can be chosen as .... (inline) 4. **Medium** `crates/xcl/src/gpu/dxil/fold.rs:898`: SOPK branches such as S_SUBVECTOR_LOOP_BEGIN/END (F_BRANCH, so `flow` returns Flow::Branch) fall into the generic SOPK path and are copied verbatim. (inline) 5. **Medium** `crates/xcl/src/gpu/dxil/fold.rs:1027`: `vgprs()` adds the extra write dword for TFE but not for MIMG LWE, and `mimg_vgpr_uses` counts neither, so N can be one too small and the status dword lands on a twin register. (inline) --- _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._
bmjask commented 2026-12-02 21:10:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T21:10:44Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 593

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {

High: MUBUF/MTBUF accesses without IDXEN are folded as-is, but the translator takes an ADD_TID_ENABLE buffer's index from self.lane (lower_mem.rs:1347-1356, 2029-2038), which in the folded wave32 program is the host lane 0..31 for both copies, so console lanes 32..63 use lanes 0..31's slots. A wave64 program that spills or keeps a private array through a swizzled scratch V# (ADD_TID_ENABLE=1, IDXEN=0, the usual MUBUF scratch form) gets, from the upper copy of buffer_store_dword for console lane t+32, a write into lane t's slot, overwriting the lower half's private data, and both halves read back wrong values. The 'scratch' refusal covers only ENC_FLAT_SCRATCH. Refusing (or offsetting the lane by 32 in the upper copy) for ADD_TID buffers would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776103105 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776103105). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T21:10:44Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 593 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { ~~~~ --- **High**: MUBUF/MTBUF accesses without IDXEN are folded as-is, but the translator takes an ADD_TID_ENABLE buffer's index from `self.lane` (lower_mem.rs:1347-1356, 2029-2038), which in the folded wave32 program is the host lane 0..31 for both copies, so console lanes 32..63 use lanes 0..31's slots. A wave64 program that spills or keeps a private array through a swizzled scratch V# (ADD_TID_ENABLE=1, IDXEN=0, the usual MUBUF scratch form) gets, from the upper copy of `buffer_store_dword` for console lane t+32, a write into lane t's slot, overwriting the lower half's private data, and both halves read back wrong values. The 'scratch' refusal covers only ENC_FLAT_SCRATCH. Refusing (or offsetting the lane by 32 in the upper copy) for ADD_TID buffers would fix it.
bmjask commented 2026-12-02 21:10:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T21:10:44Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 563

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {

High: The ADDTID refusal is inside the "ENC_DS" match arm only, so GLOBAL_LOAD_DWORD_ADDTID and GLOBAL_STORE_DWORD_ADDTID (ENC_FLAT_GLBL) are folded, although their address comes from the implicit lane id (self.lane, lower_mem.rs:2153-2156), which is the host lane 0..31 for both halves. For global_store_dword_addtid v1, s[0:1] in a wave64 program, the upper copy for console lanes 32..63 stores at lane*4 for lanes 0..31: lanes 32..63's data overwrites lanes 0..31's, and lanes 32..63's addresses are never written. Moving the ADDTID check out of the DS arm would cover both.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776103118 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776103118). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T21:10:44Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 563 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { ~~~~ --- **High**: The ADDTID refusal is inside the `"ENC_DS"` match arm only, so GLOBAL_LOAD_DWORD_ADDTID and GLOBAL_STORE_DWORD_ADDTID (ENC_FLAT_GLBL) are folded, although their address comes from the implicit lane id (`self.lane`, lower_mem.rs:2153-2156), which is the host lane 0..31 for both halves. For `global_store_dword_addtid v1, s[0:1]` in a wave64 program, the upper copy for console lanes 32..63 stores at lane*4 for lanes 0..31: lanes 32..63's data overwrites lanes 0..31's, and lanes 32..63's addresses are never written. Moving the ADDTID check out of the DS arm would cover both.
bmjask commented 2026-12-02 21:10:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T21:10:44Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 1000

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))
+    }
+
+    fn push(&mut self, t: Twin) {
+        if !self.joins(&t) {
+            self.flush();
+        }
+        let last = t.exec || t.store || t.upper_first;
+        self.run.push(t);
+        if last {
+            self.flush();
+        }
+    }
+
+    /// Writes the run: lanes 0..31, then 32..63.
+    fn flush(&mut self) {
+        let run = std::mem::take(&mut self.run);
+        if run.is_empty() {
+            return;
+        }
+        let exec = run.iter().any(|t| t.exec);
+        let vcc = run.iter().any(|t| t.vcc);
+        if run.iter().any(|t| t.upper_first) {
+            self.upper_copies(&run, exec, vcc);
+            self.lower_copies(&run, exec);
+        } else {
+            self.lower_copies(&run, exec);
+            self.upper_copies(&run, exec, vcc);
+        }
+    }
+
+    fn lower_copies(&mut self, run: &[Twin], exec: bool) {
+        let e = self.x.e;
+        self.out.mov(EXEC_LO, e);
+        for t in run {
+            self.out.words.extend(&t.a.words);
+        }
+        if exec {
+            self.out.mov(e, EXEC_LO);
+        }
+    }
+
+    fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) {
+        let e = self.x.e;
+        if vcc {
+            self.swap_vcc();
+        }
+        self.out.mov(EXEC_LO, e + 1);
+        for t in run {
+            self.out.words.extend(&t.b.words);
+        }
+        if exec {
+            self.out.mov(e + 1, EXEC_LO);
+        }
+        if vcc {
+            self.swap_vcc();
+        }
+    }
+
+    /// Lane reads and writes: each half's lane is in its own twin.
+    fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> {
+        let x = self.x;
+        let (n, e) = (x.n, x.e);
+        let [t0, t1, t2] = x.t;
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        let src = |code: u32| -> Result<Src, Why> {
+            match code {
+                0..=127 => Ok(sgpr(scalar(code as u8, &x))),
+                255 => Ok(Src::Lit(d.literal.unwrap_or(0))),
+                128..=208 | 240..=248 => Ok(Src::Code(code as u16)),
+                _ => Err("an operand a lane instruction cannot have"),
+            }
+        };
+        // the lane's half (1: the twins) and number there, for a constant lane
+        let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32));
+        let (s0, lane) = (f("SRC0"), f("SRC1"));
+        match d.inst.name {
+            "V_WRITELANE_B32" => {
+                let reg = f("VDST");
+                twin(reg, Half::B, &x)?;
+                let s = src(s0)?;
+                if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s);
+                    self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1));
+                    self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2));
+                    self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2));
+                    self.restore(live);
+                } else {
+                    return Err("a lane write to a lane given otherwise");
+                }
+            }
+            name => {
+                let dst = scalar(f("VDST") as u8, &x);
+                if s0 < 256 {
+                    self.out.sop1("S_MOV_B32", dst, src(s0)?);
+                    return Ok(());
+                }
+                let reg = s0 - 256;
+                twin(reg, Half::B, &x)?;
+                if name == "V_READFIRSTLANE_B32" {
+                    self.out.mov(EXEC_LO, e);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg));
+                    self.out.mov(EXEC_LO, e + 1);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n));
+                    self.save(live);
+                    // the upper half's only where no lane of the lower half is active
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0));
+                    self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1));
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else {
+                    return Err("a lane read of a lane given otherwise");
+                }
+            }
+        }
+        Ok(())
+    }
+
+    /// A scalar instruction (the console's EXEC renamed to E).
+    fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> {
+        let name = d.inst.name;
+        let x = self.x;
+        let e = x.e;
+        let [t0, t1, t2] = x.t;
+        let next = d.pc + d.len as u64;
+        match (d.enc.name, flow) {
+            ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live),
+            ("ENC_SOPP", Flow::Branch(t)) => {
+                let (lo, hi) = match name {
+                    "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live),
+                    "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1),
+                    "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI),
+                    _ => return Err("a debug branch"),
+                };
+                let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ");
+                let on_zero = if name.ends_with("NZ") { nzb } else { zb };
+                if !live {
+                    self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi));
+                    return self.jump(on_zero, t, d.pc, live);
+                }
+                // SCC stays the console's: one dword at a time
+                self.out.mov(EXEC_LO, lo);
+                if on_zero == zb {
+                    self.out.branch(nzb, next, d.pc);
+                } else {
+                    self.jump(nzb, t, d.pc, live)?;
+                }
+                self.out.mov(EXEC_LO, hi);
+                return self.jump(on_zero, t, d.pc, live);
+            }
+            ("ENC_SOPP", _) => {
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SMEM", _) => {
+                let (r, w) = rdna2::sgpr_uses(d);
+                if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) {
+                    return Err("EXEC as a scalar memory operand");
+                }
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {}
+            _ => return Err("an unexpected scalar encoding"),
+        }
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        if name == "S_GETPC_B64" {
+            // the console's address, which its constant data is found from
+            let dst = scalar(f("SDST") as u8, &x);
+            let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1);
+            self.out.sop1("S_GETPC_B64", dst, int(0));
+            self.save(live);
+            self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32));
+            self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 }));
+            self.restore(live);
+            return Ok(());
+        }
+        if let Flow::Jump(t) = flow {
+            return self.jump("S_BRANCH", t, d.pc, live);
+        }
+        if name.starts_with("S_MOVREL") {
+            return Err("a relative register move");
+        }
+        if name.ends_with("EXEC_B32") {
+            return Err("a wave32 EXEC operation in a wave64 program");
+        }
+        if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) {
+            let (lo, hi) = match f("SSRC0") {
+                c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)),
+                c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)),
+                c @ 128..=192 => (Src::Code(c as u16), int(0)),
+                c @ 193..=208 => (Src::Code(c as u16), int(-1)),
+                255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)),
+                _ => return Err("a float or special constant as a 64-bit scalar operand"),
+            };
+            // (operation, whether EXEC is its first operand)
+            let (op, exec_first) = match stem {
+                "S_AND" => ("S_AND_B32", false),
+                "S_OR" => ("S_OR_B32", false),
+                "S_XOR" => ("S_XOR_B32", false),
+                "S_ANDN2" => ("S_ANDN2_B32", false),
+                "S_ORN2" => ("S_ORN2_B32", false),
+                "S_NAND" => ("S_NAND_B32", false),
+                "S_NOR" => ("S_NOR_B32", false),
+                "S_XNOR" => ("S_XNOR_B32", false),
+                "S_ANDN1" => ("S_ANDN2_B32", true),
+                "S_ORN1" => ("S_ORN2_B32", true),
+                _ => return Err("an EXEC operation the rewrite does not know"),
+            };
+            for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() {
+                let ek = sgpr(e + k as u8);
+                if exec_first {
+                    self.out.sop2(op, t, ek, s);
+                } else {
+                    self.out.sop2(op, t, s, ek);
+                }
+            }
+            let dst = f("SDST") as u8;
+            let old = name.contains("SAVEEXEC");
+            if old && dst != NULL {
+                self.out.mov(scalar(dst, &x), e);
+                self.out.mov(scalar(dst, &x) + 1, e + 1);
+            }
+            self.out.mov(e, t0);
+            self.out.mov(e + 1, t1);
+            if !old && dst != NULL {
+                self.out.mov(scalar(dst, &x), t0);
+                self.out.mov(scalar(dst, &x) + 1, t1);
+            }
+            if live {
+                self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1));
+            }
+            return Ok(());
+        }
+        let mut w = d.words.clone();
+        let mut rename = |shift: u32, bits: u32| -> Result<(), Why> {
+            let m = (1 << bits) - 1;
+            let c = w[0] >> shift & m;
+            let c = match c {
+                251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"),
+                0..=127 => u32::from(scalar(c as u8, &x)),
+                _ => c,
+            };
+            w[0] = w[0] & !(m << shift) | c << shift;
+            Ok(())
+        };
+        if d.enc.name != "ENC_SOPC" {
+            rename(16, 7)?;
+        }
+        if d.enc.name != "ENC_SOPK" {
+            rename(0, 8)?;
+        }
+        if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") {
+            rename(8, 8)?;
+        }
+        self.out.words.extend(&w);
+        Ok(())
+    }
+}
+
+/// Seven scalar registers no instruction of the program names: two pairs, five single ones.
+fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> {
+    let mut used = [false; 128];
+    for d in list {
+        let (r, w) = rdna2::sgpr_uses(d);

Medium: spare_sgprs gets its 'used' set from rdna2::sgpr_uses, which skips SRC0 for non-Plain variants (rdna2.rs:557) and never sees an SDWA S1 SGPR source or an SDWA VOPC SDST, so an SGPR the program uses only through SDWA can be chosen as E, a temp, the swap register or the far-jump pair. If the program uses s104/s105 only as an SDWA operand (e.g. v_cmp_eq_u32_sdwa s[104:105], v0, v1 with SD=1), spare_sgprs treats them as free and makes them E, so the console's mask overwrites EXEC or the moves into E overwrite the program's value, and lanes run with the wrong EXEC or read corrupted data. Including SDWA operands in the used set would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776103126 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776103126). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T21:10:44Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 1000 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) + } + + fn push(&mut self, t: Twin) { + if !self.joins(&t) { + self.flush(); + } + let last = t.exec || t.store || t.upper_first; + self.run.push(t); + if last { + self.flush(); + } + } + + /// Writes the run: lanes 0..31, then 32..63. + fn flush(&mut self) { + let run = std::mem::take(&mut self.run); + if run.is_empty() { + return; + } + let exec = run.iter().any(|t| t.exec); + let vcc = run.iter().any(|t| t.vcc); + if run.iter().any(|t| t.upper_first) { + self.upper_copies(&run, exec, vcc); + self.lower_copies(&run, exec); + } else { + self.lower_copies(&run, exec); + self.upper_copies(&run, exec, vcc); + } + } + + fn lower_copies(&mut self, run: &[Twin], exec: bool) { + let e = self.x.e; + self.out.mov(EXEC_LO, e); + for t in run { + self.out.words.extend(&t.a.words); + } + if exec { + self.out.mov(e, EXEC_LO); + } + } + + fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) { + let e = self.x.e; + if vcc { + self.swap_vcc(); + } + self.out.mov(EXEC_LO, e + 1); + for t in run { + self.out.words.extend(&t.b.words); + } + if exec { + self.out.mov(e + 1, EXEC_LO); + } + if vcc { + self.swap_vcc(); + } + } + + /// Lane reads and writes: each half's lane is in its own twin. + fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> { + let x = self.x; + let (n, e) = (x.n, x.e); + let [t0, t1, t2] = x.t; + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + let src = |code: u32| -> Result<Src, Why> { + match code { + 0..=127 => Ok(sgpr(scalar(code as u8, &x))), + 255 => Ok(Src::Lit(d.literal.unwrap_or(0))), + 128..=208 | 240..=248 => Ok(Src::Code(code as u16)), + _ => Err("an operand a lane instruction cannot have"), + } + }; + // the lane's half (1: the twins) and number there, for a constant lane + let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32)); + let (s0, lane) = (f("SRC0"), f("SRC1")); + match d.inst.name { + "V_WRITELANE_B32" => { + let reg = f("VDST"); + twin(reg, Half::B, &x)?; + let s = src(s0)?; + if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s); + self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1)); + self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2)); + self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2)); + self.restore(live); + } else { + return Err("a lane write to a lane given otherwise"); + } + } + name => { + let dst = scalar(f("VDST") as u8, &x); + if s0 < 256 { + self.out.sop1("S_MOV_B32", dst, src(s0)?); + return Ok(()); + } + let reg = s0 - 256; + twin(reg, Half::B, &x)?; + if name == "V_READFIRSTLANE_B32" { + self.out.mov(EXEC_LO, e); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg)); + self.out.mov(EXEC_LO, e + 1); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n)); + self.save(live); + // the upper half's only where no lane of the lower half is active + self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0)); + self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1)); + self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else { + return Err("a lane read of a lane given otherwise"); + } + } + } + Ok(()) + } + + /// A scalar instruction (the console's EXEC renamed to E). + fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> { + let name = d.inst.name; + let x = self.x; + let e = x.e; + let [t0, t1, t2] = x.t; + let next = d.pc + d.len as u64; + match (d.enc.name, flow) { + ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live), + ("ENC_SOPP", Flow::Branch(t)) => { + let (lo, hi) = match name { + "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live), + "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1), + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI), + _ => return Err("a debug branch"), + }; + let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ"); + let on_zero = if name.ends_with("NZ") { nzb } else { zb }; + if !live { + self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi)); + return self.jump(on_zero, t, d.pc, live); + } + // SCC stays the console's: one dword at a time + self.out.mov(EXEC_LO, lo); + if on_zero == zb { + self.out.branch(nzb, next, d.pc); + } else { + self.jump(nzb, t, d.pc, live)?; + } + self.out.mov(EXEC_LO, hi); + return self.jump(on_zero, t, d.pc, live); + } + ("ENC_SOPP", _) => { + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SMEM", _) => { + let (r, w) = rdna2::sgpr_uses(d); + if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) { + return Err("EXEC as a scalar memory operand"); + } + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {} + _ => return Err("an unexpected scalar encoding"), + } + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + if name == "S_GETPC_B64" { + // the console's address, which its constant data is found from + let dst = scalar(f("SDST") as u8, &x); + let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1); + self.out.sop1("S_GETPC_B64", dst, int(0)); + self.save(live); + self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32)); + self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 })); + self.restore(live); + return Ok(()); + } + if let Flow::Jump(t) = flow { + return self.jump("S_BRANCH", t, d.pc, live); + } + if name.starts_with("S_MOVREL") { + return Err("a relative register move"); + } + if name.ends_with("EXEC_B32") { + return Err("a wave32 EXEC operation in a wave64 program"); + } + if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) { + let (lo, hi) = match f("SSRC0") { + c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)), + c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)), + c @ 128..=192 => (Src::Code(c as u16), int(0)), + c @ 193..=208 => (Src::Code(c as u16), int(-1)), + 255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)), + _ => return Err("a float or special constant as a 64-bit scalar operand"), + }; + // (operation, whether EXEC is its first operand) + let (op, exec_first) = match stem { + "S_AND" => ("S_AND_B32", false), + "S_OR" => ("S_OR_B32", false), + "S_XOR" => ("S_XOR_B32", false), + "S_ANDN2" => ("S_ANDN2_B32", false), + "S_ORN2" => ("S_ORN2_B32", false), + "S_NAND" => ("S_NAND_B32", false), + "S_NOR" => ("S_NOR_B32", false), + "S_XNOR" => ("S_XNOR_B32", false), + "S_ANDN1" => ("S_ANDN2_B32", true), + "S_ORN1" => ("S_ORN2_B32", true), + _ => return Err("an EXEC operation the rewrite does not know"), + }; + for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() { + let ek = sgpr(e + k as u8); + if exec_first { + self.out.sop2(op, t, ek, s); + } else { + self.out.sop2(op, t, s, ek); + } + } + let dst = f("SDST") as u8; + let old = name.contains("SAVEEXEC"); + if old && dst != NULL { + self.out.mov(scalar(dst, &x), e); + self.out.mov(scalar(dst, &x) + 1, e + 1); + } + self.out.mov(e, t0); + self.out.mov(e + 1, t1); + if !old && dst != NULL { + self.out.mov(scalar(dst, &x), t0); + self.out.mov(scalar(dst, &x) + 1, t1); + } + if live { + self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1)); + } + return Ok(()); + } + let mut w = d.words.clone(); + let mut rename = |shift: u32, bits: u32| -> Result<(), Why> { + let m = (1 << bits) - 1; + let c = w[0] >> shift & m; + let c = match c { + 251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"), + 0..=127 => u32::from(scalar(c as u8, &x)), + _ => c, + }; + w[0] = w[0] & !(m << shift) | c << shift; + Ok(()) + }; + if d.enc.name != "ENC_SOPC" { + rename(16, 7)?; + } + if d.enc.name != "ENC_SOPK" { + rename(0, 8)?; + } + if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") { + rename(8, 8)?; + } + self.out.words.extend(&w); + Ok(()) + } +} + +/// Seven scalar registers no instruction of the program names: two pairs, five single ones. +fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> { + let mut used = [false; 128]; + for d in list { + let (r, w) = rdna2::sgpr_uses(d); ~~~~ --- **Medium**: `spare_sgprs` gets its 'used' set from `rdna2::sgpr_uses`, which skips SRC0 for non-Plain variants (rdna2.rs:557) and never sees an SDWA S1 SGPR source or an SDWA VOPC SDST, so an SGPR the program uses only through SDWA can be chosen as E, a temp, the swap register or the far-jump pair. If the program uses s104/s105 only as an SDWA operand (e.g. `v_cmp_eq_u32_sdwa s[104:105], v0, v1` with SD=1), `spare_sgprs` treats them as free and makes them E, so the console's mask overwrites EXEC or the moves into E overwrite the program's value, and lanes run with the wrong EXEC or read corrupted data. Including SDWA operands in the used set would fix it.
bmjask commented 2026-12-02 21:10:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T21:10:44Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 898

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))
+    }
+
+    fn push(&mut self, t: Twin) {
+        if !self.joins(&t) {
+            self.flush();
+        }
+        let last = t.exec || t.store || t.upper_first;
+        self.run.push(t);
+        if last {
+            self.flush();
+        }
+    }
+
+    /// Writes the run: lanes 0..31, then 32..63.
+    fn flush(&mut self) {
+        let run = std::mem::take(&mut self.run);
+        if run.is_empty() {
+            return;
+        }
+        let exec = run.iter().any(|t| t.exec);
+        let vcc = run.iter().any(|t| t.vcc);
+        if run.iter().any(|t| t.upper_first) {
+            self.upper_copies(&run, exec, vcc);
+            self.lower_copies(&run, exec);
+        } else {
+            self.lower_copies(&run, exec);
+            self.upper_copies(&run, exec, vcc);
+        }
+    }
+
+    fn lower_copies(&mut self, run: &[Twin], exec: bool) {
+        let e = self.x.e;
+        self.out.mov(EXEC_LO, e);
+        for t in run {
+            self.out.words.extend(&t.a.words);
+        }
+        if exec {
+            self.out.mov(e, EXEC_LO);
+        }
+    }
+
+    fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) {
+        let e = self.x.e;
+        if vcc {
+            self.swap_vcc();
+        }
+        self.out.mov(EXEC_LO, e + 1);
+        for t in run {
+            self.out.words.extend(&t.b.words);
+        }
+        if exec {
+            self.out.mov(e + 1, EXEC_LO);
+        }
+        if vcc {
+            self.swap_vcc();
+        }
+    }
+
+    /// Lane reads and writes: each half's lane is in its own twin.
+    fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> {
+        let x = self.x;
+        let (n, e) = (x.n, x.e);
+        let [t0, t1, t2] = x.t;
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        let src = |code: u32| -> Result<Src, Why> {
+            match code {
+                0..=127 => Ok(sgpr(scalar(code as u8, &x))),
+                255 => Ok(Src::Lit(d.literal.unwrap_or(0))),
+                128..=208 | 240..=248 => Ok(Src::Code(code as u16)),
+                _ => Err("an operand a lane instruction cannot have"),
+            }
+        };
+        // the lane's half (1: the twins) and number there, for a constant lane
+        let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32));
+        let (s0, lane) = (f("SRC0"), f("SRC1"));
+        match d.inst.name {
+            "V_WRITELANE_B32" => {
+                let reg = f("VDST");
+                twin(reg, Half::B, &x)?;
+                let s = src(s0)?;
+                if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s);
+                    self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1));
+                    self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2));
+                    self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2));
+                    self.restore(live);
+                } else {
+                    return Err("a lane write to a lane given otherwise");
+                }
+            }
+            name => {
+                let dst = scalar(f("VDST") as u8, &x);
+                if s0 < 256 {
+                    self.out.sop1("S_MOV_B32", dst, src(s0)?);
+                    return Ok(());
+                }
+                let reg = s0 - 256;
+                twin(reg, Half::B, &x)?;
+                if name == "V_READFIRSTLANE_B32" {
+                    self.out.mov(EXEC_LO, e);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg));
+                    self.out.mov(EXEC_LO, e + 1);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n));
+                    self.save(live);
+                    // the upper half's only where no lane of the lower half is active
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0));
+                    self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1));
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else {
+                    return Err("a lane read of a lane given otherwise");
+                }
+            }
+        }
+        Ok(())
+    }
+
+    /// A scalar instruction (the console's EXEC renamed to E).
+    fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> {
+        let name = d.inst.name;
+        let x = self.x;
+        let e = x.e;
+        let [t0, t1, t2] = x.t;
+        let next = d.pc + d.len as u64;
+        match (d.enc.name, flow) {
+            ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live),
+            ("ENC_SOPP", Flow::Branch(t)) => {
+                let (lo, hi) = match name {
+                    "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live),
+                    "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1),
+                    "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI),
+                    _ => return Err("a debug branch"),
+                };
+                let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ");
+                let on_zero = if name.ends_with("NZ") { nzb } else { zb };
+                if !live {
+                    self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi));
+                    return self.jump(on_zero, t, d.pc, live);
+                }
+                // SCC stays the console's: one dword at a time
+                self.out.mov(EXEC_LO, lo);
+                if on_zero == zb {
+                    self.out.branch(nzb, next, d.pc);
+                } else {
+                    self.jump(nzb, t, d.pc, live)?;
+                }
+                self.out.mov(EXEC_LO, hi);
+                return self.jump(on_zero, t, d.pc, live);
+            }
+            ("ENC_SOPP", _) => {
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SMEM", _) => {
+                let (r, w) = rdna2::sgpr_uses(d);
+                if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) {
+                    return Err("EXEC as a scalar memory operand");
+                }
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {}

Medium: SOPK branches such as S_SUBVECTOR_LOOP_BEGIN/END (F_BRANCH, so flow returns Flow::Branch) fall into the generic SOPK path and are copied verbatim. Their SIMM16 still holds the console offset, which is wrong in the longer folded code, and their implicit EXEC use isn't renamed to E. A program using them folds without a refusal, the host branch jumps into the middle of the expanded code, and the loop tests EXEC_LO instead of E. Refusing them, or relocating their offsets like the other branches, would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776103131 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776103131). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T21:10:44Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 898 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) + } + + fn push(&mut self, t: Twin) { + if !self.joins(&t) { + self.flush(); + } + let last = t.exec || t.store || t.upper_first; + self.run.push(t); + if last { + self.flush(); + } + } + + /// Writes the run: lanes 0..31, then 32..63. + fn flush(&mut self) { + let run = std::mem::take(&mut self.run); + if run.is_empty() { + return; + } + let exec = run.iter().any(|t| t.exec); + let vcc = run.iter().any(|t| t.vcc); + if run.iter().any(|t| t.upper_first) { + self.upper_copies(&run, exec, vcc); + self.lower_copies(&run, exec); + } else { + self.lower_copies(&run, exec); + self.upper_copies(&run, exec, vcc); + } + } + + fn lower_copies(&mut self, run: &[Twin], exec: bool) { + let e = self.x.e; + self.out.mov(EXEC_LO, e); + for t in run { + self.out.words.extend(&t.a.words); + } + if exec { + self.out.mov(e, EXEC_LO); + } + } + + fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) { + let e = self.x.e; + if vcc { + self.swap_vcc(); + } + self.out.mov(EXEC_LO, e + 1); + for t in run { + self.out.words.extend(&t.b.words); + } + if exec { + self.out.mov(e + 1, EXEC_LO); + } + if vcc { + self.swap_vcc(); + } + } + + /// Lane reads and writes: each half's lane is in its own twin. + fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> { + let x = self.x; + let (n, e) = (x.n, x.e); + let [t0, t1, t2] = x.t; + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + let src = |code: u32| -> Result<Src, Why> { + match code { + 0..=127 => Ok(sgpr(scalar(code as u8, &x))), + 255 => Ok(Src::Lit(d.literal.unwrap_or(0))), + 128..=208 | 240..=248 => Ok(Src::Code(code as u16)), + _ => Err("an operand a lane instruction cannot have"), + } + }; + // the lane's half (1: the twins) and number there, for a constant lane + let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32)); + let (s0, lane) = (f("SRC0"), f("SRC1")); + match d.inst.name { + "V_WRITELANE_B32" => { + let reg = f("VDST"); + twin(reg, Half::B, &x)?; + let s = src(s0)?; + if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s); + self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1)); + self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2)); + self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2)); + self.restore(live); + } else { + return Err("a lane write to a lane given otherwise"); + } + } + name => { + let dst = scalar(f("VDST") as u8, &x); + if s0 < 256 { + self.out.sop1("S_MOV_B32", dst, src(s0)?); + return Ok(()); + } + let reg = s0 - 256; + twin(reg, Half::B, &x)?; + if name == "V_READFIRSTLANE_B32" { + self.out.mov(EXEC_LO, e); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg)); + self.out.mov(EXEC_LO, e + 1); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n)); + self.save(live); + // the upper half's only where no lane of the lower half is active + self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0)); + self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1)); + self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else { + return Err("a lane read of a lane given otherwise"); + } + } + } + Ok(()) + } + + /// A scalar instruction (the console's EXEC renamed to E). + fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> { + let name = d.inst.name; + let x = self.x; + let e = x.e; + let [t0, t1, t2] = x.t; + let next = d.pc + d.len as u64; + match (d.enc.name, flow) { + ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live), + ("ENC_SOPP", Flow::Branch(t)) => { + let (lo, hi) = match name { + "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live), + "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1), + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI), + _ => return Err("a debug branch"), + }; + let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ"); + let on_zero = if name.ends_with("NZ") { nzb } else { zb }; + if !live { + self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi)); + return self.jump(on_zero, t, d.pc, live); + } + // SCC stays the console's: one dword at a time + self.out.mov(EXEC_LO, lo); + if on_zero == zb { + self.out.branch(nzb, next, d.pc); + } else { + self.jump(nzb, t, d.pc, live)?; + } + self.out.mov(EXEC_LO, hi); + return self.jump(on_zero, t, d.pc, live); + } + ("ENC_SOPP", _) => { + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SMEM", _) => { + let (r, w) = rdna2::sgpr_uses(d); + if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) { + return Err("EXEC as a scalar memory operand"); + } + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {} ~~~~ --- **Medium**: SOPK branches such as S_SUBVECTOR_LOOP_BEGIN/END (F_BRANCH, so `flow` returns Flow::Branch) fall into the generic SOPK path and are copied verbatim. Their SIMM16 still holds the console offset, which is wrong in the longer folded code, and their implicit EXEC use isn't renamed to E. A program using them folds without a refusal, the host branch jumps into the middle of the expanded code, and the loop tests EXEC_LO instead of E. Refusing them, or relocating their offsets like the other branches, would fix it.
bmjask commented 2026-12-02 21:10:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T21:10:44Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 1027

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))
+    }
+
+    fn push(&mut self, t: Twin) {
+        if !self.joins(&t) {
+            self.flush();
+        }
+        let last = t.exec || t.store || t.upper_first;
+        self.run.push(t);
+        if last {
+            self.flush();
+        }
+    }
+
+    /// Writes the run: lanes 0..31, then 32..63.
+    fn flush(&mut self) {
+        let run = std::mem::take(&mut self.run);
+        if run.is_empty() {
+            return;
+        }
+        let exec = run.iter().any(|t| t.exec);
+        let vcc = run.iter().any(|t| t.vcc);
+        if run.iter().any(|t| t.upper_first) {
+            self.upper_copies(&run, exec, vcc);
+            self.lower_copies(&run, exec);
+        } else {
+            self.lower_copies(&run, exec);
+            self.upper_copies(&run, exec, vcc);
+        }
+    }
+
+    fn lower_copies(&mut self, run: &[Twin], exec: bool) {
+        let e = self.x.e;
+        self.out.mov(EXEC_LO, e);
+        for t in run {
+            self.out.words.extend(&t.a.words);
+        }
+        if exec {
+            self.out.mov(e, EXEC_LO);
+        }
+    }
+
+    fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) {
+        let e = self.x.e;
+        if vcc {
+            self.swap_vcc();
+        }
+        self.out.mov(EXEC_LO, e + 1);
+        for t in run {
+            self.out.words.extend(&t.b.words);
+        }
+        if exec {
+            self.out.mov(e + 1, EXEC_LO);
+        }
+        if vcc {
+            self.swap_vcc();
+        }
+    }
+
+    /// Lane reads and writes: each half's lane is in its own twin.
+    fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> {
+        let x = self.x;
+        let (n, e) = (x.n, x.e);
+        let [t0, t1, t2] = x.t;
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        let src = |code: u32| -> Result<Src, Why> {
+            match code {
+                0..=127 => Ok(sgpr(scalar(code as u8, &x))),
+                255 => Ok(Src::Lit(d.literal.unwrap_or(0))),
+                128..=208 | 240..=248 => Ok(Src::Code(code as u16)),
+                _ => Err("an operand a lane instruction cannot have"),
+            }
+        };
+        // the lane's half (1: the twins) and number there, for a constant lane
+        let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32));
+        let (s0, lane) = (f("SRC0"), f("SRC1"));
+        match d.inst.name {
+            "V_WRITELANE_B32" => {
+                let reg = f("VDST");
+                twin(reg, Half::B, &x)?;
+                let s = src(s0)?;
+                if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s);
+                    self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1));
+                    self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2));
+                    self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2));
+                    self.restore(live);
+                } else {
+                    return Err("a lane write to a lane given otherwise");
+                }
+            }
+            name => {
+                let dst = scalar(f("VDST") as u8, &x);
+                if s0 < 256 {
+                    self.out.sop1("S_MOV_B32", dst, src(s0)?);
+                    return Ok(());
+                }
+                let reg = s0 - 256;
+                twin(reg, Half::B, &x)?;
+                if name == "V_READFIRSTLANE_B32" {
+                    self.out.mov(EXEC_LO, e);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg));
+                    self.out.mov(EXEC_LO, e + 1);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n));
+                    self.save(live);
+                    // the upper half's only where no lane of the lower half is active
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0));
+                    self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1));
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else {
+                    return Err("a lane read of a lane given otherwise");
+                }
+            }
+        }
+        Ok(())
+    }
+
+    /// A scalar instruction (the console's EXEC renamed to E).
+    fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> {
+        let name = d.inst.name;
+        let x = self.x;
+        let e = x.e;
+        let [t0, t1, t2] = x.t;
+        let next = d.pc + d.len as u64;
+        match (d.enc.name, flow) {
+            ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live),
+            ("ENC_SOPP", Flow::Branch(t)) => {
+                let (lo, hi) = match name {
+                    "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live),
+                    "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1),
+                    "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI),
+                    _ => return Err("a debug branch"),
+                };
+                let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ");
+                let on_zero = if name.ends_with("NZ") { nzb } else { zb };
+                if !live {
+                    self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi));
+                    return self.jump(on_zero, t, d.pc, live);
+                }
+                // SCC stays the console's: one dword at a time
+                self.out.mov(EXEC_LO, lo);
+                if on_zero == zb {
+                    self.out.branch(nzb, next, d.pc);
+                } else {
+                    self.jump(nzb, t, d.pc, live)?;
+                }
+                self.out.mov(EXEC_LO, hi);
+                return self.jump(on_zero, t, d.pc, live);
+            }
+            ("ENC_SOPP", _) => {
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SMEM", _) => {
+                let (r, w) = rdna2::sgpr_uses(d);
+                if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) {
+                    return Err("EXEC as a scalar memory operand");
+                }
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {}
+            _ => return Err("an unexpected scalar encoding"),
+        }
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        if name == "S_GETPC_B64" {
+            // the console's address, which its constant data is found from
+            let dst = scalar(f("SDST") as u8, &x);
+            let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1);
+            self.out.sop1("S_GETPC_B64", dst, int(0));
+            self.save(live);
+            self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32));
+            self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 }));
+            self.restore(live);
+            return Ok(());
+        }
+        if let Flow::Jump(t) = flow {
+            return self.jump("S_BRANCH", t, d.pc, live);
+        }
+        if name.starts_with("S_MOVREL") {
+            return Err("a relative register move");
+        }
+        if name.ends_with("EXEC_B32") {
+            return Err("a wave32 EXEC operation in a wave64 program");
+        }
+        if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) {
+            let (lo, hi) = match f("SSRC0") {
+                c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)),
+                c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)),
+                c @ 128..=192 => (Src::Code(c as u16), int(0)),
+                c @ 193..=208 => (Src::Code(c as u16), int(-1)),
+                255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)),
+                _ => return Err("a float or special constant as a 64-bit scalar operand"),
+            };
+            // (operation, whether EXEC is its first operand)
+            let (op, exec_first) = match stem {
+                "S_AND" => ("S_AND_B32", false),
+                "S_OR" => ("S_OR_B32", false),
+                "S_XOR" => ("S_XOR_B32", false),
+                "S_ANDN2" => ("S_ANDN2_B32", false),
+                "S_ORN2" => ("S_ORN2_B32", false),
+                "S_NAND" => ("S_NAND_B32", false),
+                "S_NOR" => ("S_NOR_B32", false),
+                "S_XNOR" => ("S_XNOR_B32", false),
+                "S_ANDN1" => ("S_ANDN2_B32", true),
+                "S_ORN1" => ("S_ORN2_B32", true),
+                _ => return Err("an EXEC operation the rewrite does not know"),
+            };
+            for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() {
+                let ek = sgpr(e + k as u8);
+                if exec_first {
+                    self.out.sop2(op, t, ek, s);
+                } else {
+                    self.out.sop2(op, t, s, ek);
+                }
+            }
+            let dst = f("SDST") as u8;
+            let old = name.contains("SAVEEXEC");
+            if old && dst != NULL {
+                self.out.mov(scalar(dst, &x), e);
+                self.out.mov(scalar(dst, &x) + 1, e + 1);
+            }
+            self.out.mov(e, t0);
+            self.out.mov(e + 1, t1);
+            if !old && dst != NULL {
+                self.out.mov(scalar(dst, &x), t0);
+                self.out.mov(scalar(dst, &x) + 1, t1);
+            }
+            if live {
+                self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1));
+            }
+            return Ok(());
+        }
+        let mut w = d.words.clone();
+        let mut rename = |shift: u32, bits: u32| -> Result<(), Why> {
+            let m = (1 << bits) - 1;
+            let c = w[0] >> shift & m;
+            let c = match c {
+                251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"),
+                0..=127 => u32::from(scalar(c as u8, &x)),
+                _ => c,
+            };
+            w[0] = w[0] & !(m << shift) | c << shift;
+            Ok(())
+        };
+        if d.enc.name != "ENC_SOPC" {
+            rename(16, 7)?;
+        }
+        if d.enc.name != "ENC_SOPK" {
+            rename(0, 8)?;
+        }
+        if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") {
+            rename(8, 8)?;
+        }
+        self.out.words.extend(&w);
+        Ok(())
+    }
+}
+
+/// Seven scalar registers no instruction of the program names: two pairs, five single ones.
+fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> {
+    let mut used = [false; 128];
+    for d in list {
+        let (r, w) = rdna2::sgpr_uses(d);
+        for c in r.into_iter().chain(w) {
+            used[c as usize] = true;
+        }
+    }
+    let mut free = (0..=105u8).rev().filter(|&c| !used[usize::from(c)]);
+    let mut pairs = [0u8; 2];
+    let mut rest = Vec::new();
+    let mut k = 0;
+    while k < 2 || rest.len() < 5 {
+        let c = free.next().ok_or("no spare scalar registers")?;
+        if k < 2 && c % 2 == 1 && c > 0 && !used[usize::from(c - 1)] {
+            free.next();
+            pairs[k] = c - 1;
+            k += 1;
+        } else {
+            rest.push(c);
+        }
+    }
+    Ok((pairs, [rest[0], rest[1], rest[2], rest[3], rest[4]]))
+}
+
+/// The program's VGPR count: one past the highest it names.
+fn vgprs(list: &[Decoded]) -> u32 {
+    list.iter()
+        .flat_map(|d| {
+            let (r, w) = rdna2::vgpr_uses(d);
+            let tfe = u64::from(field_value(d.enc, &d.words, "TFE") == Some(1));

Medium: vgprs() adds the extra write dword for TFE but not for MIMG LWE, and mimg_vgpr_uses counts neither, so N can be one too small and the status dword lands on a twin register. An image load with LWE=1, TFE=0 that writes the program's highest VGPRs puts its status dword in v(N), the twin of v0, so the lower copy overwrites console lane t+32's v0 (its thread id or other data). Counting LWE like TFE would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776103137 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776103137). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T21:10:44Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 1027 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) + } + + fn push(&mut self, t: Twin) { + if !self.joins(&t) { + self.flush(); + } + let last = t.exec || t.store || t.upper_first; + self.run.push(t); + if last { + self.flush(); + } + } + + /// Writes the run: lanes 0..31, then 32..63. + fn flush(&mut self) { + let run = std::mem::take(&mut self.run); + if run.is_empty() { + return; + } + let exec = run.iter().any(|t| t.exec); + let vcc = run.iter().any(|t| t.vcc); + if run.iter().any(|t| t.upper_first) { + self.upper_copies(&run, exec, vcc); + self.lower_copies(&run, exec); + } else { + self.lower_copies(&run, exec); + self.upper_copies(&run, exec, vcc); + } + } + + fn lower_copies(&mut self, run: &[Twin], exec: bool) { + let e = self.x.e; + self.out.mov(EXEC_LO, e); + for t in run { + self.out.words.extend(&t.a.words); + } + if exec { + self.out.mov(e, EXEC_LO); + } + } + + fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) { + let e = self.x.e; + if vcc { + self.swap_vcc(); + } + self.out.mov(EXEC_LO, e + 1); + for t in run { + self.out.words.extend(&t.b.words); + } + if exec { + self.out.mov(e + 1, EXEC_LO); + } + if vcc { + self.swap_vcc(); + } + } + + /// Lane reads and writes: each half's lane is in its own twin. + fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> { + let x = self.x; + let (n, e) = (x.n, x.e); + let [t0, t1, t2] = x.t; + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + let src = |code: u32| -> Result<Src, Why> { + match code { + 0..=127 => Ok(sgpr(scalar(code as u8, &x))), + 255 => Ok(Src::Lit(d.literal.unwrap_or(0))), + 128..=208 | 240..=248 => Ok(Src::Code(code as u16)), + _ => Err("an operand a lane instruction cannot have"), + } + }; + // the lane's half (1: the twins) and number there, for a constant lane + let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32)); + let (s0, lane) = (f("SRC0"), f("SRC1")); + match d.inst.name { + "V_WRITELANE_B32" => { + let reg = f("VDST"); + twin(reg, Half::B, &x)?; + let s = src(s0)?; + if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s); + self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1)); + self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2)); + self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2)); + self.restore(live); + } else { + return Err("a lane write to a lane given otherwise"); + } + } + name => { + let dst = scalar(f("VDST") as u8, &x); + if s0 < 256 { + self.out.sop1("S_MOV_B32", dst, src(s0)?); + return Ok(()); + } + let reg = s0 - 256; + twin(reg, Half::B, &x)?; + if name == "V_READFIRSTLANE_B32" { + self.out.mov(EXEC_LO, e); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg)); + self.out.mov(EXEC_LO, e + 1); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n)); + self.save(live); + // the upper half's only where no lane of the lower half is active + self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0)); + self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1)); + self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else { + return Err("a lane read of a lane given otherwise"); + } + } + } + Ok(()) + } + + /// A scalar instruction (the console's EXEC renamed to E). + fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> { + let name = d.inst.name; + let x = self.x; + let e = x.e; + let [t0, t1, t2] = x.t; + let next = d.pc + d.len as u64; + match (d.enc.name, flow) { + ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live), + ("ENC_SOPP", Flow::Branch(t)) => { + let (lo, hi) = match name { + "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live), + "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1), + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI), + _ => return Err("a debug branch"), + }; + let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ"); + let on_zero = if name.ends_with("NZ") { nzb } else { zb }; + if !live { + self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi)); + return self.jump(on_zero, t, d.pc, live); + } + // SCC stays the console's: one dword at a time + self.out.mov(EXEC_LO, lo); + if on_zero == zb { + self.out.branch(nzb, next, d.pc); + } else { + self.jump(nzb, t, d.pc, live)?; + } + self.out.mov(EXEC_LO, hi); + return self.jump(on_zero, t, d.pc, live); + } + ("ENC_SOPP", _) => { + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SMEM", _) => { + let (r, w) = rdna2::sgpr_uses(d); + if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) { + return Err("EXEC as a scalar memory operand"); + } + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {} + _ => return Err("an unexpected scalar encoding"), + } + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + if name == "S_GETPC_B64" { + // the console's address, which its constant data is found from + let dst = scalar(f("SDST") as u8, &x); + let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1); + self.out.sop1("S_GETPC_B64", dst, int(0)); + self.save(live); + self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32)); + self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 })); + self.restore(live); + return Ok(()); + } + if let Flow::Jump(t) = flow { + return self.jump("S_BRANCH", t, d.pc, live); + } + if name.starts_with("S_MOVREL") { + return Err("a relative register move"); + } + if name.ends_with("EXEC_B32") { + return Err("a wave32 EXEC operation in a wave64 program"); + } + if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) { + let (lo, hi) = match f("SSRC0") { + c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)), + c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)), + c @ 128..=192 => (Src::Code(c as u16), int(0)), + c @ 193..=208 => (Src::Code(c as u16), int(-1)), + 255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)), + _ => return Err("a float or special constant as a 64-bit scalar operand"), + }; + // (operation, whether EXEC is its first operand) + let (op, exec_first) = match stem { + "S_AND" => ("S_AND_B32", false), + "S_OR" => ("S_OR_B32", false), + "S_XOR" => ("S_XOR_B32", false), + "S_ANDN2" => ("S_ANDN2_B32", false), + "S_ORN2" => ("S_ORN2_B32", false), + "S_NAND" => ("S_NAND_B32", false), + "S_NOR" => ("S_NOR_B32", false), + "S_XNOR" => ("S_XNOR_B32", false), + "S_ANDN1" => ("S_ANDN2_B32", true), + "S_ORN1" => ("S_ORN2_B32", true), + _ => return Err("an EXEC operation the rewrite does not know"), + }; + for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() { + let ek = sgpr(e + k as u8); + if exec_first { + self.out.sop2(op, t, ek, s); + } else { + self.out.sop2(op, t, s, ek); + } + } + let dst = f("SDST") as u8; + let old = name.contains("SAVEEXEC"); + if old && dst != NULL { + self.out.mov(scalar(dst, &x), e); + self.out.mov(scalar(dst, &x) + 1, e + 1); + } + self.out.mov(e, t0); + self.out.mov(e + 1, t1); + if !old && dst != NULL { + self.out.mov(scalar(dst, &x), t0); + self.out.mov(scalar(dst, &x) + 1, t1); + } + if live { + self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1)); + } + return Ok(()); + } + let mut w = d.words.clone(); + let mut rename = |shift: u32, bits: u32| -> Result<(), Why> { + let m = (1 << bits) - 1; + let c = w[0] >> shift & m; + let c = match c { + 251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"), + 0..=127 => u32::from(scalar(c as u8, &x)), + _ => c, + }; + w[0] = w[0] & !(m << shift) | c << shift; + Ok(()) + }; + if d.enc.name != "ENC_SOPC" { + rename(16, 7)?; + } + if d.enc.name != "ENC_SOPK" { + rename(0, 8)?; + } + if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") { + rename(8, 8)?; + } + self.out.words.extend(&w); + Ok(()) + } +} + +/// Seven scalar registers no instruction of the program names: two pairs, five single ones. +fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> { + let mut used = [false; 128]; + for d in list { + let (r, w) = rdna2::sgpr_uses(d); + for c in r.into_iter().chain(w) { + used[c as usize] = true; + } + } + let mut free = (0..=105u8).rev().filter(|&c| !used[usize::from(c)]); + let mut pairs = [0u8; 2]; + let mut rest = Vec::new(); + let mut k = 0; + while k < 2 || rest.len() < 5 { + let c = free.next().ok_or("no spare scalar registers")?; + if k < 2 && c % 2 == 1 && c > 0 && !used[usize::from(c - 1)] { + free.next(); + pairs[k] = c - 1; + k += 1; + } else { + rest.push(c); + } + } + Ok((pairs, [rest[0], rest[1], rest[2], rest[3], rest[4]])) +} + +/// The program's VGPR count: one past the highest it names. +fn vgprs(list: &[Decoded]) -> u32 { + list.iter() + .flat_map(|d| { + let (r, w) = rdna2::vgpr_uses(d); + let tfe = u64::from(field_value(d.enc, &d.words, "TFE") == Some(1)); ~~~~ --- **Medium**: `vgprs()` adds the extra write dword for TFE but not for MIMG LWE, and `mimg_vgpr_uses` counts neither, so N can be one too small and the status dword lands on a twin register. An image load with LWE=1, TFE=0 that writes the program's highest VGPRs puts its status dword in v(N), the twin of v0, so the lower copy overwrites console lane t+32's v0 (its thread id or other data). Counting LWE like TFE would fix it.
Foniass commented 2026-12-02 21:35:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T21:35:25Z.


Follow-up review of f1988c2e, since ee2c186e (code reading only, not a merge-check; PR description red) · 1 high, 1 nit

In short: This push fixes four more cases in the fold and answers the interpreter-only point:

  • buffer accesses that count the lane (ADD_TID) now count console lane t + 32 in the upper copy;
  • SDWA scalar operands are kept out of the spare SGPRs;
  • LWE is treated like TFE;
  • s_subvector_loop is refused.

The GPU test now also compares each program with the split form on the same GPU. The fixes read right. The size is still open, and the smoke blocks name 8f236eca (PR description is red).

High

  1. Please split it (still open). 2,168 changed lines (fold.rs and fold_tests.rs most of them), none generated. The stack suggested earlier still applies:
    • the preparation;
    • the rewrite of scalar code and vector runs;
    • the lane instructions;
    • turning it on behind XCL_WAVE64_FOLD=1;
    • the census.

Nit

  1. Compact-limit refusal (still open). kernel.rs ~492 refuses folding whenever the folded wanted_plan does not fit, even when the split form's tables do not fit either.
Checked and fine
  • Earlier finding fixed: the GPU tests compared only with the PR's own interpreter. gpu_folded_wave64_matches_the_console_wave now also runs translate_compute (the split form) and asserts the folded output equals it.
  • ADD_TID: emit records where each upper copy of a MUBUF / MTBUF access without IDXEN, or of an *ADDTID instruction, starts. upper_tid passes those as byte offsets to lane_plus_32, and tid_lane adds 32 to the lane there (binary_search on a list built in increasing order). gpu_folded_wave64_counts_the_console_lane_in_add_tid_accesses checks 128 lanes through global_store_dword_addtid and a V# with ADD_TID.
  • SDWA: spare_sgprs marks SRC0 (S0, bit 23), SRC1 (S1, bit 31) and a VOPC SDST (SD, bit 15) as used. c < 127 keeps c..c + 2 inside the 128-entry array. Covered by an_sgpr_named_only_by_an_sdwa_operand_is_not_spare.
  • LWE now counts like TFE for the extra returned VGPR, and s_subvector_loop is refused, with a test.
  • Commits 2, 3, 4 and 6 are unchanged.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7359495749 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7359495749). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T21:35:25Z. --- **Follow-up review** of `f1988c2e`, since `ee2c186e` (code reading only, not a merge-check; `PR description` red) · 1 high, 1 nit **In short:** This push fixes four more cases in the fold and answers the interpreter-only point: - buffer accesses that count the lane (ADD_TID) now count console lane t + 32 in the upper copy; - SDWA scalar operands are kept out of the spare SGPRs; - `LWE` is treated like `TFE`; - `s_subvector_loop` is refused. The GPU test now also compares each program with the split form on the same GPU. The fixes read right. The size is still open, and the smoke blocks name `8f236eca` (`PR description` is red). #### High 1. **Please split it (still open).** 2,168 changed lines (`fold.rs` and `fold_tests.rs` most of them), none generated. The stack suggested earlier still applies: - the preparation; - the rewrite of scalar code and vector runs; - the lane instructions; - turning it on behind `XCL_WAVE64_FOLD=1`; - the census. #### Nit 2. **Compact-limit refusal (still open).** `kernel.rs` ~492 refuses folding whenever the folded `wanted_plan` does not fit, even when the split form's tables do not fit either. <details><summary>Checked and fine</summary> - Earlier finding fixed: the GPU tests compared only with the PR's own interpreter. `gpu_folded_wave64_matches_the_console_wave` now also runs `translate_compute` (the split form) and asserts the folded output equals it. - ADD_TID: `emit` records where each upper copy of a MUBUF / MTBUF access without `IDXEN`, or of an `*ADDTID` instruction, starts. `upper_tid` passes those as byte offsets to `lane_plus_32`, and `tid_lane` adds 32 to the lane there (`binary_search` on a list built in increasing order). `gpu_folded_wave64_counts_the_console_lane_in_add_tid_accesses` checks 128 lanes through `global_store_dword_addtid` and a V# with ADD_TID. - SDWA: `spare_sgprs` marks SRC0 (`S0`, bit 23), SRC1 (`S1`, bit 31) and a VOPC SDST (`SD`, bit 15) as used. `c < 127` keeps `c..c + 2` inside the 128-entry array. Covered by `an_sgpr_named_only_by_an_sdwa_operand_is_not_spare`. - `LWE` now counts like `TFE` for the extra returned VGPR, and `s_subvector_loop` is refused, with a test. - Commits 2, 3, 4 and 6 are unchanged. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
Royalflamejlh commented 2026-12-02 21:55:18 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T21:55:18Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 712

@@ -0,0 +1,1158 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))

Right for reads of EXEC as data. fold_tests showed it: with your v_mbcnt_lo/hi + v_cmpx_gt_u32 16, v0 run, console lane 32 counted 16 instead of 32. Fixed in f1988c2e8: a copy that writes EXEC now lists EXEC's dword in its writes (end of valu_copy), so joins ends the run before it. v_mov_b32 v6, exec_lo before a v_cmpx had the same fault: its upper copy reads EXEC_LO through E.

v_cndmask_b32 ..., exec was right before the fix: as a mask, its upper copy reads the upper dword from the hardware EXEC, and the v_cmpx's upper copy only changes that after it. The new test program exec_read_then_cmpx has all three.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776635482 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776635482). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T21:55:18Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 712 ~~~~diff @@ -0,0 +1,1158 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) ~~~~ --- Right for reads of EXEC as data. `fold_tests` showed it: with your `v_mbcnt_lo/hi` + `v_cmpx_gt_u32 16, v0` run, console lane 32 counted 16 instead of 32. Fixed in `f1988c2e8`: a copy that writes EXEC now lists EXEC's dword in its `writes` (end of `valu_copy`), so `joins` ends the run before it. `v_mov_b32 v6, exec_lo` before a `v_cmpx` had the same fault: its upper copy reads EXEC_LO through E. `v_cndmask_b32 ..., exec` was right before the fix: as a mask, its upper copy reads the upper dword from the hardware EXEC, and the `v_cmpx`'s upper copy only changes that after it. The new test program `exec_read_then_cmpx` has all three.
Royalflamejlh commented 2026-12-02 21:55:20 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T21:55:20Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 368

@@ -0,0 +1,1158 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 => Ok(code),

Right. mask9 now gives the upper copy -1 (193) for any inline -1..-16, as the SAVEEXEC path does (f1988c2e8). Test program inline_masks (v_cndmask_b32 with -2, v_add_co_ci_u32 with -3): before the fix console lane 32 took 1 where the console takes 2.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776635780 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776635780). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T21:55:20Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 368 ~~~~diff @@ -0,0 +1,1158 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 => Ok(code), ~~~~ --- Right. `mask9` now gives the upper copy -1 (193) for any inline -1..-16, as the SAVEEXEC path does (`f1988c2e8`). Test program `inline_masks` (`v_cndmask_b32` with -2, `v_add_co_ci_u32` with -3): before the fix console lane 32 took 1 where the console takes 2.
Royalflamejlh commented 2026-12-02 21:55:22 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T21:55:22Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 1151

@@ -0,0 +1,1158 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))
+    }
+
+    fn push(&mut self, t: Twin) {
+        if !self.joins(&t) {
+            self.flush();
+        }
+        let last = t.exec || t.store || t.upper_first;
+        self.run.push(t);
+        if last {
+            self.flush();
+        }
+    }
+
+    /// Writes the run: lanes 0..31, then 32..63.
+    fn flush(&mut self) {
+        let run = std::mem::take(&mut self.run);
+        if run.is_empty() {
+            return;
+        }
+        let exec = run.iter().any(|t| t.exec);
+        let vcc = run.iter().any(|t| t.vcc);
+        if run.iter().any(|t| t.upper_first) {
+            self.upper_copies(&run, exec, vcc);
+            self.lower_copies(&run, exec);
+        } else {
+            self.lower_copies(&run, exec);
+            self.upper_copies(&run, exec, vcc);
+        }
+    }
+
+    fn lower_copies(&mut self, run: &[Twin], exec: bool) {
+        let e = self.x.e;
+        self.out.mov(EXEC_LO, e);
+        for t in run {
+            self.out.words.extend(&t.a.words);
+        }
+        if exec {
+            self.out.mov(e, EXEC_LO);
+        }
+    }
+
+    fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) {
+        let e = self.x.e;
+        if vcc {
+            self.swap_vcc();
+        }
+        self.out.mov(EXEC_LO, e + 1);
+        for t in run {
+            self.out.words.extend(&t.b.words);
+        }
+        if exec {
+            self.out.mov(e + 1, EXEC_LO);
+        }
+        if vcc {
+            self.swap_vcc();
+        }
+    }
+
+    /// Lane reads and writes: each half's lane is in its own twin.
+    fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> {
+        let x = self.x;
+        let (n, e) = (x.n, x.e);
+        let [t0, t1, t2] = x.t;
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        let src = |code: u32| -> Result<Src, Why> {
+            match code {
+                0..=127 => Ok(sgpr(scalar(code as u8, &x))),
+                255 => Ok(Src::Lit(d.literal.unwrap_or(0))),
+                128..=208 | 240..=248 => Ok(Src::Code(code as u16)),
+                _ => Err("an operand a lane instruction cannot have"),
+            }
+        };
+        // the lane's half (1: the twins) and number there, for a constant lane
+        let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32));
+        let (s0, lane) = (f("SRC0"), f("SRC1"));
+        match d.inst.name {
+            "V_WRITELANE_B32" => {
+                let reg = f("VDST");
+                twin(reg, Half::B, &x)?;
+                let s = src(s0)?;
+                if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s);
+                    self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1));
+                    self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2));
+                    self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2));
+                    self.restore(live);
+                } else {
+                    return Err("a lane write to a lane given otherwise");
+                }
+            }
+            name => {
+                let dst = scalar(f("VDST") as u8, &x);
+                if s0 < 256 {
+                    self.out.sop1("S_MOV_B32", dst, src(s0)?);
+                    return Ok(());
+                }
+                let reg = s0 - 256;
+                twin(reg, Half::B, &x)?;
+                if name == "V_READFIRSTLANE_B32" {
+                    self.out.mov(EXEC_LO, e);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg));
+                    self.out.mov(EXEC_LO, e + 1);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n));
+                    self.save(live);
+                    // the upper half's only where no lane of the lower half is active
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0));
+                    self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1));
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else {
+                    return Err("a lane read of a lane given otherwise");
+                }
+            }
+        }
+        Ok(())
+    }
+
+    /// A scalar instruction (the console's EXEC renamed to E).
+    fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> {
+        let name = d.inst.name;
+        let x = self.x;
+        let e = x.e;
+        let [t0, t1, t2] = x.t;
+        let next = d.pc + d.len as u64;
+        match (d.enc.name, flow) {
+            ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live),
+            ("ENC_SOPP", Flow::Branch(t)) => {
+                let (lo, hi) = match name {
+                    "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live),
+                    "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1),
+                    "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI),
+                    _ => return Err("a debug branch"),
+                };
+                let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ");
+                let on_zero = if name.ends_with("NZ") { nzb } else { zb };
+                if !live {
+                    self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi));
+                    return self.jump(on_zero, t, d.pc, live);
+                }
+                // SCC stays the console's: one dword at a time
+                self.out.mov(EXEC_LO, lo);
+                if on_zero == zb {
+                    self.out.branch(nzb, next, d.pc);
+                } else {
+                    self.jump(nzb, t, d.pc, live)?;
+                }
+                self.out.mov(EXEC_LO, hi);
+                return self.jump(on_zero, t, d.pc, live);
+            }
+            ("ENC_SOPP", _) => {
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SMEM", _) => {
+                let (r, w) = rdna2::sgpr_uses(d);
+                if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) {
+                    return Err("EXEC as a scalar memory operand");
+                }
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {}
+            _ => return Err("an unexpected scalar encoding"),
+        }
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        if name == "S_GETPC_B64" {
+            // the console's address, which its constant data is found from
+            let dst = scalar(f("SDST") as u8, &x);
+            let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1);
+            self.out.sop1("S_GETPC_B64", dst, int(0));
+            self.save(live);
+            self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32));
+            self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 }));
+            self.restore(live);
+            return Ok(());
+        }
+        if let Flow::Jump(t) = flow {
+            return self.jump("S_BRANCH", t, d.pc, live);
+        }
+        if name.starts_with("S_MOVREL") {
+            return Err("a relative register move");
+        }
+        if name.ends_with("EXEC_B32") {
+            return Err("a wave32 EXEC operation in a wave64 program");
+        }
+        if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) {
+            let (lo, hi) = match f("SSRC0") {
+                c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)),
+                c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)),
+                c @ 128..=192 => (Src::Code(c as u16), int(0)),
+                c @ 193..=208 => (Src::Code(c as u16), int(-1)),
+                255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)),
+                _ => return Err("a float or special constant as a 64-bit scalar operand"),
+            };
+            // (operation, whether EXEC is its first operand)
+            let (op, exec_first) = match stem {
+                "S_AND" => ("S_AND_B32", false),
+                "S_OR" => ("S_OR_B32", false),
+                "S_XOR" => ("S_XOR_B32", false),
+                "S_ANDN2" => ("S_ANDN2_B32", false),
+                "S_ORN2" => ("S_ORN2_B32", false),
+                "S_NAND" => ("S_NAND_B32", false),
+                "S_NOR" => ("S_NOR_B32", false),
+                "S_XNOR" => ("S_XNOR_B32", false),
+                "S_ANDN1" => ("S_ANDN2_B32", true),
+                "S_ORN1" => ("S_ORN2_B32", true),
+                _ => return Err("an EXEC operation the rewrite does not know"),
+            };
+            for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() {
+                let ek = sgpr(e + k as u8);
+                if exec_first {
+                    self.out.sop2(op, t, ek, s);
+                } else {
+                    self.out.sop2(op, t, s, ek);
+                }
+            }
+            let dst = f("SDST") as u8;
+            let old = name.contains("SAVEEXEC");
+            if old && dst != NULL {
+                self.out.mov(scalar(dst, &x), e);
+                self.out.mov(scalar(dst, &x) + 1, e + 1);
+            }
+            self.out.mov(e, t0);
+            self.out.mov(e + 1, t1);
+            if !old && dst != NULL {
+                self.out.mov(scalar(dst, &x), t0);
+                self.out.mov(scalar(dst, &x) + 1, t1);
+            }
+            if live {
+                self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1));
+            }
+            return Ok(());
+        }
+        let mut w = d.words.clone();
+        let mut rename = |shift: u32, bits: u32| -> Result<(), Why> {
+            let m = (1 << bits) - 1;
+            let c = w[0] >> shift & m;
+            let c = match c {
+                251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"),
+                0..=127 => u32::from(scalar(c as u8, &x)),
+                _ => c,
+            };
+            w[0] = w[0] & !(m << shift) | c << shift;
+            Ok(())
+        };
+        if d.enc.name != "ENC_SOPC" {
+            rename(16, 7)?;
+        }
+        if d.enc.name != "ENC_SOPK" {
+            rename(0, 8)?;
+        }
+        if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") {
+            rename(8, 8)?;
+        }
+        self.out.words.extend(&w);
+        Ok(())
+    }
+}
+
+/// Seven scalar registers no instruction of the program names: two pairs, five single ones.
+fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> {
+    let mut used = [false; 128];
+    for d in list {
+        let (r, w) = rdna2::sgpr_uses(d);
+        for c in r.into_iter().chain(w) {
+            used[c as usize] = true;
+        }
+    }
+    let mut free = (0..=105u8).rev().filter(|&c| !used[usize::from(c)]);
+    let mut pairs = [0u8; 2];
+    let mut rest = Vec::new();
+    let mut k = 0;
+    while k < 2 || rest.len() < 5 {
+        let c = free.next().ok_or("no spare scalar registers")?;
+        if k < 2 && c % 2 == 1 && c > 0 && !used[usize::from(c - 1)] {
+            free.next();
+            pairs[k] = c - 1;
+            k += 1;
+        } else {
+            rest.push(c);
+        }
+    }
+    Ok((pairs, [rest[0], rest[1], rest[2], rest[3], rest[4]]))
+}
+
+/// The program's VGPR count: one past the highest it names.
+fn vgprs(list: &[Decoded]) -> u32 {
+    list.iter()
+        .flat_map(|d| {
+            let (r, w) = rdna2::vgpr_uses(d);
+            let tfe = u64::from(field_value(d.enc, &d.words, "TFE") == Some(1));
+            r.into_iter().chain(w.into_iter().map(move |v| v + tfe))
+        })
+        .max()
+        .map_or(0, |v| v as u32 + 1)
+}
+
+fn emit(list: &[Decoded], flows: &[Flow], leaders: &HashSet<u64>, live: &[bool], x: Spare, far: &HashSet<u64>) -> Result<(Vec<u32>, Vec<u64>), Why> {
+    let mut f = Fold { x, out: Asm::default(), run: Vec::new(), far };
+    f.out.mov(x.e, EXEC_LO);
+    f.out.mov(x.e + 1, EXEC_HI);
+    let mut at: HashMap<u64, usize> = HashMap::new();
+    for (i, d) in list.iter().enumerate() {
+        if leaders.contains(&d.pc) {
+            f.flush();
+        }
+        at.insert(d.pc, f.out.words.len());
+        let name = d.inst.name;
+        if matches!(name, "S_NOP" | "S_INST_PREFETCH" | "S_CLAUSE" | "V_NOP" | "V_PIPEFLUSH" | "V_CLREXCP") || name.starts_with("S_WAITCNT") {
+            continue;
+        }
+        match d.enc.name {
+            "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" | "ENC_VOP3" | "ENC_VOP3P" | "VOP3_SDST_ENC" => match name {
+                "V_READLANE_B32" | "V_WRITELANE_B32" | "V_READFIRSTLANE_B32" => {
+                    f.flush();
+                    f.lanes(d, live[i])?;
+                }
+                "V_MBCNT_LO_U32_B32" | "V_MBCNT_HI_U32_B32" => f.push(mbcnt(d, &x)?),
+                _ if name.starts_with("V_INTERP") || name.starts_with("V_MOVREL") || name == "V_SWAPREL_B32" => {
+                    return Err("an interpolation or a relative register move");
+                }
+                _ => {
+                    let mut t = Twin::default();
+                    t.a = valu_copy(d, Half::A, &x, &mut t)?;
+                    t.b = match valu_copy(d, Half::B, &x, &mut t) {
+                        Err(NEEDS_SWAP) => {
+                            t.vcc = true;
+                            t.store = true;
+                            valu_copy(d, Half::BSwap, &x, &mut t)?
+                        }
+                        b => b?,
+                    };
+                    f.push(t.ordered()?);
+                }
+            },
+            "ENC_DS" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => {
+                let t = Twin { a: memory_copy(d, Half::A, &x)?, b: memory_copy(d, Half::B, &x)?, store: writes_memory(d), ..Twin::default() };
+                f.push(t);
+            }
+            "ENC_VINTRP" | "ENC_EXP" => return Err("an interpolation or export"),
+            _ => {
+                f.flush();
+                f.scalar_inst(d, live[i], flows[i])?;
+            }
+        }
+    }
+    f.flush();
+    // branches; the console instructions whose branches do not reach
+    let mut words = f.out.words;
+    let mut short = Vec::new();
+    for &(w, to, origin) in &f.out.branches {
+        let to = *at.get(&to).ok_or("a branch into an instruction")?;
+        match i16::try_from(to as i64 - (w as i64 + 1)) {
+            Ok(delta) => words[w] = words[w] & 0xFFFF_0000 | u32::from(delta as u16),
+            Err(_) => short.push(origin),
+        }
+    }
+    for &(w, to) in &f.out.far {
+        let to = *at.get(&to).ok_or("a branch into an instruction")?;
+        // from the address `s_getpc_b64` gives, the next instruction's
+        let delta = 4 * (to as i64 - (w as i64 + 1));
+        words[w + 2] = delta as u32;
+        words[w + 3] = words[w + 3] & !0xFF00 | if delta < 0 { 193 } else { 128 } << 8;
+    }
+    Ok((words, short))
+}
+
+/// `code` (a console wave64 compute program of interface `cs`) as a wave32 program of the
+/// same effects (see the module), or what the rewrite does not cover.
+pub fn fold(code: &[u8], cs: &CsInterface) -> Result<Folded, Why> {
+    let mut list = Vec::new();
+    let mut off = 0;
+    while off + 4 <= code.len() {
+        let d = rdna2::decode(&code[off..], off as u64).map_err(|_| "code that does not decode")?;
+        off += d.len;
+        list.push(d);
+    }
+    rdna2::resolve_far_jumps(&mut list);
+    let n = vgprs(&list).max(cs.tid_components);
+    if 2 * n > HOST_REGISTERS {
+        return Err("too many VGPRs for two lanes per host lane");
+    }
+    let index: HashMap<u64, usize> = list.iter().enumerate().map(|(i, d)| (d.pc, i)).collect();
+    let mut flows = Vec::with_capacity(list.len());
+    let mut succs = Vec::with_capacity(list.len());
+    let mut leaders = HashSet::new();
+    for (i, d) in list.iter().enumerate() {
+        let fl = flow(d)?;
+        let next = (i + 1 < list.len()).then_some(i + 1);
+        let to = |t: u64| index.get(&t).copied().ok_or("a branch into an instruction");
+        succs.push(match fl {
+            Flow::Next => next.into_iter().collect(),
+            Flow::Stop => vec![],
+            Flow::Jump(t) => vec![to(t)?],
+            Flow::Branch(t) => std::iter::once(to(t)?).chain(next).collect(),
+        });
+        if let Flow::Jump(t) | Flow::Branch(t) = fl {
+            leaders.insert(t);
+        }
+        if fl != Flow::Next {
+            leaders.insert(d.pc + d.len as u64);
+        }
+        flows.push(fl);
+    }
+    let live = scc_live(&list, &succs);
+    let ([e, jp], rest) = spare_sgprs(&list)?;
+    let x = Spare { n, e, save: rest[0], swap: rest[1], t: [rest[2], rest[3], rest[4]], jp };
+    let mut far = HashSet::new();
+    let words = loop {
+        let (words, short) = emit(&list, &flows, &leaders, &live, x, &far)?;
+        if short.is_empty() {
+            break words;
+        }
+        far.extend(short);
+    };
+    let total: u32 = cs.threads.iter().product();
+    Ok(Folded {
+        code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
+        cs: CsInterface { threads: [total.div_ceil(64) * 32, 1, 1], tid_components: 1, ..cs.clone() },

Right. For a folded program loop_passes now divides by the console group's threads, not the host group's (translate_on_this_thread, f1988c2e8), so its cap is the split form's. Test: a_folded_loop_has_the_passes_of_the_console_threads (a group of 96: the folded form divided by 64 before the fix).

<!-- greyfinch-sync:ivall/xcl:review-comment:4776636159 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776636159). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T21:55:22Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 1151 ~~~~diff @@ -0,0 +1,1158 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) + } + + fn push(&mut self, t: Twin) { + if !self.joins(&t) { + self.flush(); + } + let last = t.exec || t.store || t.upper_first; + self.run.push(t); + if last { + self.flush(); + } + } + + /// Writes the run: lanes 0..31, then 32..63. + fn flush(&mut self) { + let run = std::mem::take(&mut self.run); + if run.is_empty() { + return; + } + let exec = run.iter().any(|t| t.exec); + let vcc = run.iter().any(|t| t.vcc); + if run.iter().any(|t| t.upper_first) { + self.upper_copies(&run, exec, vcc); + self.lower_copies(&run, exec); + } else { + self.lower_copies(&run, exec); + self.upper_copies(&run, exec, vcc); + } + } + + fn lower_copies(&mut self, run: &[Twin], exec: bool) { + let e = self.x.e; + self.out.mov(EXEC_LO, e); + for t in run { + self.out.words.extend(&t.a.words); + } + if exec { + self.out.mov(e, EXEC_LO); + } + } + + fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) { + let e = self.x.e; + if vcc { + self.swap_vcc(); + } + self.out.mov(EXEC_LO, e + 1); + for t in run { + self.out.words.extend(&t.b.words); + } + if exec { + self.out.mov(e + 1, EXEC_LO); + } + if vcc { + self.swap_vcc(); + } + } + + /// Lane reads and writes: each half's lane is in its own twin. + fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> { + let x = self.x; + let (n, e) = (x.n, x.e); + let [t0, t1, t2] = x.t; + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + let src = |code: u32| -> Result<Src, Why> { + match code { + 0..=127 => Ok(sgpr(scalar(code as u8, &x))), + 255 => Ok(Src::Lit(d.literal.unwrap_or(0))), + 128..=208 | 240..=248 => Ok(Src::Code(code as u16)), + _ => Err("an operand a lane instruction cannot have"), + } + }; + // the lane's half (1: the twins) and number there, for a constant lane + let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32)); + let (s0, lane) = (f("SRC0"), f("SRC1")); + match d.inst.name { + "V_WRITELANE_B32" => { + let reg = f("VDST"); + twin(reg, Half::B, &x)?; + let s = src(s0)?; + if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s); + self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1)); + self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2)); + self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2)); + self.restore(live); + } else { + return Err("a lane write to a lane given otherwise"); + } + } + name => { + let dst = scalar(f("VDST") as u8, &x); + if s0 < 256 { + self.out.sop1("S_MOV_B32", dst, src(s0)?); + return Ok(()); + } + let reg = s0 - 256; + twin(reg, Half::B, &x)?; + if name == "V_READFIRSTLANE_B32" { + self.out.mov(EXEC_LO, e); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg)); + self.out.mov(EXEC_LO, e + 1); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n)); + self.save(live); + // the upper half's only where no lane of the lower half is active + self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0)); + self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1)); + self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else { + return Err("a lane read of a lane given otherwise"); + } + } + } + Ok(()) + } + + /// A scalar instruction (the console's EXEC renamed to E). + fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> { + let name = d.inst.name; + let x = self.x; + let e = x.e; + let [t0, t1, t2] = x.t; + let next = d.pc + d.len as u64; + match (d.enc.name, flow) { + ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live), + ("ENC_SOPP", Flow::Branch(t)) => { + let (lo, hi) = match name { + "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live), + "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1), + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI), + _ => return Err("a debug branch"), + }; + let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ"); + let on_zero = if name.ends_with("NZ") { nzb } else { zb }; + if !live { + self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi)); + return self.jump(on_zero, t, d.pc, live); + } + // SCC stays the console's: one dword at a time + self.out.mov(EXEC_LO, lo); + if on_zero == zb { + self.out.branch(nzb, next, d.pc); + } else { + self.jump(nzb, t, d.pc, live)?; + } + self.out.mov(EXEC_LO, hi); + return self.jump(on_zero, t, d.pc, live); + } + ("ENC_SOPP", _) => { + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SMEM", _) => { + let (r, w) = rdna2::sgpr_uses(d); + if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) { + return Err("EXEC as a scalar memory operand"); + } + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {} + _ => return Err("an unexpected scalar encoding"), + } + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + if name == "S_GETPC_B64" { + // the console's address, which its constant data is found from + let dst = scalar(f("SDST") as u8, &x); + let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1); + self.out.sop1("S_GETPC_B64", dst, int(0)); + self.save(live); + self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32)); + self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 })); + self.restore(live); + return Ok(()); + } + if let Flow::Jump(t) = flow { + return self.jump("S_BRANCH", t, d.pc, live); + } + if name.starts_with("S_MOVREL") { + return Err("a relative register move"); + } + if name.ends_with("EXEC_B32") { + return Err("a wave32 EXEC operation in a wave64 program"); + } + if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) { + let (lo, hi) = match f("SSRC0") { + c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)), + c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)), + c @ 128..=192 => (Src::Code(c as u16), int(0)), + c @ 193..=208 => (Src::Code(c as u16), int(-1)), + 255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)), + _ => return Err("a float or special constant as a 64-bit scalar operand"), + }; + // (operation, whether EXEC is its first operand) + let (op, exec_first) = match stem { + "S_AND" => ("S_AND_B32", false), + "S_OR" => ("S_OR_B32", false), + "S_XOR" => ("S_XOR_B32", false), + "S_ANDN2" => ("S_ANDN2_B32", false), + "S_ORN2" => ("S_ORN2_B32", false), + "S_NAND" => ("S_NAND_B32", false), + "S_NOR" => ("S_NOR_B32", false), + "S_XNOR" => ("S_XNOR_B32", false), + "S_ANDN1" => ("S_ANDN2_B32", true), + "S_ORN1" => ("S_ORN2_B32", true), + _ => return Err("an EXEC operation the rewrite does not know"), + }; + for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() { + let ek = sgpr(e + k as u8); + if exec_first { + self.out.sop2(op, t, ek, s); + } else { + self.out.sop2(op, t, s, ek); + } + } + let dst = f("SDST") as u8; + let old = name.contains("SAVEEXEC"); + if old && dst != NULL { + self.out.mov(scalar(dst, &x), e); + self.out.mov(scalar(dst, &x) + 1, e + 1); + } + self.out.mov(e, t0); + self.out.mov(e + 1, t1); + if !old && dst != NULL { + self.out.mov(scalar(dst, &x), t0); + self.out.mov(scalar(dst, &x) + 1, t1); + } + if live { + self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1)); + } + return Ok(()); + } + let mut w = d.words.clone(); + let mut rename = |shift: u32, bits: u32| -> Result<(), Why> { + let m = (1 << bits) - 1; + let c = w[0] >> shift & m; + let c = match c { + 251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"), + 0..=127 => u32::from(scalar(c as u8, &x)), + _ => c, + }; + w[0] = w[0] & !(m << shift) | c << shift; + Ok(()) + }; + if d.enc.name != "ENC_SOPC" { + rename(16, 7)?; + } + if d.enc.name != "ENC_SOPK" { + rename(0, 8)?; + } + if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") { + rename(8, 8)?; + } + self.out.words.extend(&w); + Ok(()) + } +} + +/// Seven scalar registers no instruction of the program names: two pairs, five single ones. +fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> { + let mut used = [false; 128]; + for d in list { + let (r, w) = rdna2::sgpr_uses(d); + for c in r.into_iter().chain(w) { + used[c as usize] = true; + } + } + let mut free = (0..=105u8).rev().filter(|&c| !used[usize::from(c)]); + let mut pairs = [0u8; 2]; + let mut rest = Vec::new(); + let mut k = 0; + while k < 2 || rest.len() < 5 { + let c = free.next().ok_or("no spare scalar registers")?; + if k < 2 && c % 2 == 1 && c > 0 && !used[usize::from(c - 1)] { + free.next(); + pairs[k] = c - 1; + k += 1; + } else { + rest.push(c); + } + } + Ok((pairs, [rest[0], rest[1], rest[2], rest[3], rest[4]])) +} + +/// The program's VGPR count: one past the highest it names. +fn vgprs(list: &[Decoded]) -> u32 { + list.iter() + .flat_map(|d| { + let (r, w) = rdna2::vgpr_uses(d); + let tfe = u64::from(field_value(d.enc, &d.words, "TFE") == Some(1)); + r.into_iter().chain(w.into_iter().map(move |v| v + tfe)) + }) + .max() + .map_or(0, |v| v as u32 + 1) +} + +fn emit(list: &[Decoded], flows: &[Flow], leaders: &HashSet<u64>, live: &[bool], x: Spare, far: &HashSet<u64>) -> Result<(Vec<u32>, Vec<u64>), Why> { + let mut f = Fold { x, out: Asm::default(), run: Vec::new(), far }; + f.out.mov(x.e, EXEC_LO); + f.out.mov(x.e + 1, EXEC_HI); + let mut at: HashMap<u64, usize> = HashMap::new(); + for (i, d) in list.iter().enumerate() { + if leaders.contains(&d.pc) { + f.flush(); + } + at.insert(d.pc, f.out.words.len()); + let name = d.inst.name; + if matches!(name, "S_NOP" | "S_INST_PREFETCH" | "S_CLAUSE" | "V_NOP" | "V_PIPEFLUSH" | "V_CLREXCP") || name.starts_with("S_WAITCNT") { + continue; + } + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" | "ENC_VOP3" | "ENC_VOP3P" | "VOP3_SDST_ENC" => match name { + "V_READLANE_B32" | "V_WRITELANE_B32" | "V_READFIRSTLANE_B32" => { + f.flush(); + f.lanes(d, live[i])?; + } + "V_MBCNT_LO_U32_B32" | "V_MBCNT_HI_U32_B32" => f.push(mbcnt(d, &x)?), + _ if name.starts_with("V_INTERP") || name.starts_with("V_MOVREL") || name == "V_SWAPREL_B32" => { + return Err("an interpolation or a relative register move"); + } + _ => { + let mut t = Twin::default(); + t.a = valu_copy(d, Half::A, &x, &mut t)?; + t.b = match valu_copy(d, Half::B, &x, &mut t) { + Err(NEEDS_SWAP) => { + t.vcc = true; + t.store = true; + valu_copy(d, Half::BSwap, &x, &mut t)? + } + b => b?, + }; + f.push(t.ordered()?); + } + }, + "ENC_DS" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => { + let t = Twin { a: memory_copy(d, Half::A, &x)?, b: memory_copy(d, Half::B, &x)?, store: writes_memory(d), ..Twin::default() }; + f.push(t); + } + "ENC_VINTRP" | "ENC_EXP" => return Err("an interpolation or export"), + _ => { + f.flush(); + f.scalar_inst(d, live[i], flows[i])?; + } + } + } + f.flush(); + // branches; the console instructions whose branches do not reach + let mut words = f.out.words; + let mut short = Vec::new(); + for &(w, to, origin) in &f.out.branches { + let to = *at.get(&to).ok_or("a branch into an instruction")?; + match i16::try_from(to as i64 - (w as i64 + 1)) { + Ok(delta) => words[w] = words[w] & 0xFFFF_0000 | u32::from(delta as u16), + Err(_) => short.push(origin), + } + } + for &(w, to) in &f.out.far { + let to = *at.get(&to).ok_or("a branch into an instruction")?; + // from the address `s_getpc_b64` gives, the next instruction's + let delta = 4 * (to as i64 - (w as i64 + 1)); + words[w + 2] = delta as u32; + words[w + 3] = words[w + 3] & !0xFF00 | if delta < 0 { 193 } else { 128 } << 8; + } + Ok((words, short)) +} + +/// `code` (a console wave64 compute program of interface `cs`) as a wave32 program of the +/// same effects (see the module), or what the rewrite does not cover. +pub fn fold(code: &[u8], cs: &CsInterface) -> Result<Folded, Why> { + let mut list = Vec::new(); + let mut off = 0; + while off + 4 <= code.len() { + let d = rdna2::decode(&code[off..], off as u64).map_err(|_| "code that does not decode")?; + off += d.len; + list.push(d); + } + rdna2::resolve_far_jumps(&mut list); + let n = vgprs(&list).max(cs.tid_components); + if 2 * n > HOST_REGISTERS { + return Err("too many VGPRs for two lanes per host lane"); + } + let index: HashMap<u64, usize> = list.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let mut flows = Vec::with_capacity(list.len()); + let mut succs = Vec::with_capacity(list.len()); + let mut leaders = HashSet::new(); + for (i, d) in list.iter().enumerate() { + let fl = flow(d)?; + let next = (i + 1 < list.len()).then_some(i + 1); + let to = |t: u64| index.get(&t).copied().ok_or("a branch into an instruction"); + succs.push(match fl { + Flow::Next => next.into_iter().collect(), + Flow::Stop => vec![], + Flow::Jump(t) => vec![to(t)?], + Flow::Branch(t) => std::iter::once(to(t)?).chain(next).collect(), + }); + if let Flow::Jump(t) | Flow::Branch(t) = fl { + leaders.insert(t); + } + if fl != Flow::Next { + leaders.insert(d.pc + d.len as u64); + } + flows.push(fl); + } + let live = scc_live(&list, &succs); + let ([e, jp], rest) = spare_sgprs(&list)?; + let x = Spare { n, e, save: rest[0], swap: rest[1], t: [rest[2], rest[3], rest[4]], jp }; + let mut far = HashSet::new(); + let words = loop { + let (words, short) = emit(&list, &flows, &leaders, &live, x, &far)?; + if short.is_empty() { + break words; + } + far.extend(short); + }; + let total: u32 = cs.threads.iter().product(); + Ok(Folded { + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + cs: CsInterface { threads: [total.div_ceil(64) * 32, 1, 1], tid_components: 1, ..cs.clone() }, ~~~~ --- Right. For a folded program `loop_passes` now divides by the console group's threads, not the host group's (`translate_on_this_thread`, `f1988c2e8`), so its cap is the split form's. Test: `a_folded_loop_has_the_passes_of_the_console_threads` (a group of 96: the folded form divided by 64 before the fix).
Royalflamejlh commented 2026-12-02 21:55:24 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T21:55:24Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 593

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {

Right. ADD_TID is a bit of the V#, known only when the program runs, so the fold cannot refuse on it. Fixed in f1988c2e8: fold lists where the upper copies of buffer accesses without IDXEN and of global_*_addtid start (Twins::upper_tid), and the translation counts lane + 32 there (Lw::tid_lane, lower_mem.rs ~2476, used by the MUBUF, MTBUF and addtid paths). Test: gpu_folded_wave64_counts_the_console_lane_in_add_tid_accesses (a global_store_dword_addtid and a buffer_store_dword through an ADD_TID V#, one console wave of 64). It runs only on a GPU with wave32; its results will be in the description.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776636592 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776636592). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T21:55:24Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 593 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { ~~~~ --- Right. ADD_TID is a bit of the V#, known only when the program runs, so the fold cannot refuse on it. Fixed in `f1988c2e8`: `fold` lists where the upper copies of buffer accesses without IDXEN and of `global_*_addtid` start (`Twins::upper_tid`), and the translation counts lane + 32 there (`Lw::tid_lane`, `lower_mem.rs` ~2476, used by the MUBUF, MTBUF and addtid paths). Test: `gpu_folded_wave64_counts_the_console_lane_in_add_tid_accesses` (a `global_store_dword_addtid` and a `buffer_store_dword` through an ADD_TID V#, one console wave of 64). It runs only on a GPU with wave32; its results will be in the description.
Royalflamejlh commented 2026-12-02 21:55:26 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T21:55:26Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 563

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {

Right; the same change as the buffer one above covers it, by counting the console lane instead of refusing: the upper copy of a global_*_addtid is listed in Twins::upper_tid, and Lw::tid_lane gives it lane + 32 (f1988c2e8). The GPU test stores with global_store_dword_addtid across both halves.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776636991 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776636991). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T21:55:26Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 563 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { ~~~~ --- Right; the same change as the buffer one above covers it, by counting the console lane instead of refusing: the upper copy of a `global_*_addtid` is listed in `Twins::upper_tid`, and `Lw::tid_lane` gives it lane + 32 (`f1988c2e8`). The GPU test stores with `global_store_dword_addtid` across both halves.
Royalflamejlh commented 2026-12-02 21:55:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T21:55:28Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 1000

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))
+    }
+
+    fn push(&mut self, t: Twin) {
+        if !self.joins(&t) {
+            self.flush();
+        }
+        let last = t.exec || t.store || t.upper_first;
+        self.run.push(t);
+        if last {
+            self.flush();
+        }
+    }
+
+    /// Writes the run: lanes 0..31, then 32..63.
+    fn flush(&mut self) {
+        let run = std::mem::take(&mut self.run);
+        if run.is_empty() {
+            return;
+        }
+        let exec = run.iter().any(|t| t.exec);
+        let vcc = run.iter().any(|t| t.vcc);
+        if run.iter().any(|t| t.upper_first) {
+            self.upper_copies(&run, exec, vcc);
+            self.lower_copies(&run, exec);
+        } else {
+            self.lower_copies(&run, exec);
+            self.upper_copies(&run, exec, vcc);
+        }
+    }
+
+    fn lower_copies(&mut self, run: &[Twin], exec: bool) {
+        let e = self.x.e;
+        self.out.mov(EXEC_LO, e);
+        for t in run {
+            self.out.words.extend(&t.a.words);
+        }
+        if exec {
+            self.out.mov(e, EXEC_LO);
+        }
+    }
+
+    fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) {
+        let e = self.x.e;
+        if vcc {
+            self.swap_vcc();
+        }
+        self.out.mov(EXEC_LO, e + 1);
+        for t in run {
+            self.out.words.extend(&t.b.words);
+        }
+        if exec {
+            self.out.mov(e + 1, EXEC_LO);
+        }
+        if vcc {
+            self.swap_vcc();
+        }
+    }
+
+    /// Lane reads and writes: each half's lane is in its own twin.
+    fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> {
+        let x = self.x;
+        let (n, e) = (x.n, x.e);
+        let [t0, t1, t2] = x.t;
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        let src = |code: u32| -> Result<Src, Why> {
+            match code {
+                0..=127 => Ok(sgpr(scalar(code as u8, &x))),
+                255 => Ok(Src::Lit(d.literal.unwrap_or(0))),
+                128..=208 | 240..=248 => Ok(Src::Code(code as u16)),
+                _ => Err("an operand a lane instruction cannot have"),
+            }
+        };
+        // the lane's half (1: the twins) and number there, for a constant lane
+        let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32));
+        let (s0, lane) = (f("SRC0"), f("SRC1"));
+        match d.inst.name {
+            "V_WRITELANE_B32" => {
+                let reg = f("VDST");
+                twin(reg, Half::B, &x)?;
+                let s = src(s0)?;
+                if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s);
+                    self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1));
+                    self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2));
+                    self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2));
+                    self.restore(live);
+                } else {
+                    return Err("a lane write to a lane given otherwise");
+                }
+            }
+            name => {
+                let dst = scalar(f("VDST") as u8, &x);
+                if s0 < 256 {
+                    self.out.sop1("S_MOV_B32", dst, src(s0)?);
+                    return Ok(());
+                }
+                let reg = s0 - 256;
+                twin(reg, Half::B, &x)?;
+                if name == "V_READFIRSTLANE_B32" {
+                    self.out.mov(EXEC_LO, e);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg));
+                    self.out.mov(EXEC_LO, e + 1);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n));
+                    self.save(live);
+                    // the upper half's only where no lane of the lower half is active
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0));
+                    self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1));
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else {
+                    return Err("a lane read of a lane given otherwise");
+                }
+            }
+        }
+        Ok(())
+    }
+
+    /// A scalar instruction (the console's EXEC renamed to E).
+    fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> {
+        let name = d.inst.name;
+        let x = self.x;
+        let e = x.e;
+        let [t0, t1, t2] = x.t;
+        let next = d.pc + d.len as u64;
+        match (d.enc.name, flow) {
+            ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live),
+            ("ENC_SOPP", Flow::Branch(t)) => {
+                let (lo, hi) = match name {
+                    "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live),
+                    "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1),
+                    "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI),
+                    _ => return Err("a debug branch"),
+                };
+                let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ");
+                let on_zero = if name.ends_with("NZ") { nzb } else { zb };
+                if !live {
+                    self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi));
+                    return self.jump(on_zero, t, d.pc, live);
+                }
+                // SCC stays the console's: one dword at a time
+                self.out.mov(EXEC_LO, lo);
+                if on_zero == zb {
+                    self.out.branch(nzb, next, d.pc);
+                } else {
+                    self.jump(nzb, t, d.pc, live)?;
+                }
+                self.out.mov(EXEC_LO, hi);
+                return self.jump(on_zero, t, d.pc, live);
+            }
+            ("ENC_SOPP", _) => {
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SMEM", _) => {
+                let (r, w) = rdna2::sgpr_uses(d);
+                if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) {
+                    return Err("EXEC as a scalar memory operand");
+                }
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {}
+            _ => return Err("an unexpected scalar encoding"),
+        }
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        if name == "S_GETPC_B64" {
+            // the console's address, which its constant data is found from
+            let dst = scalar(f("SDST") as u8, &x);
+            let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1);
+            self.out.sop1("S_GETPC_B64", dst, int(0));
+            self.save(live);
+            self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32));
+            self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 }));
+            self.restore(live);
+            return Ok(());
+        }
+        if let Flow::Jump(t) = flow {
+            return self.jump("S_BRANCH", t, d.pc, live);
+        }
+        if name.starts_with("S_MOVREL") {
+            return Err("a relative register move");
+        }
+        if name.ends_with("EXEC_B32") {
+            return Err("a wave32 EXEC operation in a wave64 program");
+        }
+        if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) {
+            let (lo, hi) = match f("SSRC0") {
+                c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)),
+                c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)),
+                c @ 128..=192 => (Src::Code(c as u16), int(0)),
+                c @ 193..=208 => (Src::Code(c as u16), int(-1)),
+                255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)),
+                _ => return Err("a float or special constant as a 64-bit scalar operand"),
+            };
+            // (operation, whether EXEC is its first operand)
+            let (op, exec_first) = match stem {
+                "S_AND" => ("S_AND_B32", false),
+                "S_OR" => ("S_OR_B32", false),
+                "S_XOR" => ("S_XOR_B32", false),
+                "S_ANDN2" => ("S_ANDN2_B32", false),
+                "S_ORN2" => ("S_ORN2_B32", false),
+                "S_NAND" => ("S_NAND_B32", false),
+                "S_NOR" => ("S_NOR_B32", false),
+                "S_XNOR" => ("S_XNOR_B32", false),
+                "S_ANDN1" => ("S_ANDN2_B32", true),
+                "S_ORN1" => ("S_ORN2_B32", true),
+                _ => return Err("an EXEC operation the rewrite does not know"),
+            };
+            for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() {
+                let ek = sgpr(e + k as u8);
+                if exec_first {
+                    self.out.sop2(op, t, ek, s);
+                } else {
+                    self.out.sop2(op, t, s, ek);
+                }
+            }
+            let dst = f("SDST") as u8;
+            let old = name.contains("SAVEEXEC");
+            if old && dst != NULL {
+                self.out.mov(scalar(dst, &x), e);
+                self.out.mov(scalar(dst, &x) + 1, e + 1);
+            }
+            self.out.mov(e, t0);
+            self.out.mov(e + 1, t1);
+            if !old && dst != NULL {
+                self.out.mov(scalar(dst, &x), t0);
+                self.out.mov(scalar(dst, &x) + 1, t1);
+            }
+            if live {
+                self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1));
+            }
+            return Ok(());
+        }
+        let mut w = d.words.clone();
+        let mut rename = |shift: u32, bits: u32| -> Result<(), Why> {
+            let m = (1 << bits) - 1;
+            let c = w[0] >> shift & m;
+            let c = match c {
+                251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"),
+                0..=127 => u32::from(scalar(c as u8, &x)),
+                _ => c,
+            };
+            w[0] = w[0] & !(m << shift) | c << shift;
+            Ok(())
+        };
+        if d.enc.name != "ENC_SOPC" {
+            rename(16, 7)?;
+        }
+        if d.enc.name != "ENC_SOPK" {
+            rename(0, 8)?;
+        }
+        if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") {
+            rename(8, 8)?;
+        }
+        self.out.words.extend(&w);
+        Ok(())
+    }
+}
+
+/// Seven scalar registers no instruction of the program names: two pairs, five single ones.
+fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> {
+    let mut used = [false; 128];
+    for d in list {
+        let (r, w) = rdna2::sgpr_uses(d);

Right. spare_sgprs now marks an SDWA instruction's scalar operands too (S0, S1 and a VOPC SDST with SD, each as a pair), in f1988c2e8. Test: an_sgpr_named_only_by_an_sdwa_operand_is_not_spare (v_cmp_eq_u32_sdwa s[104:105], v0, v1; before the fix s[104:105] became E).

<!-- greyfinch-sync:ivall/xcl:review-comment:4776637355 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776637355). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T21:55:28Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 1000 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) + } + + fn push(&mut self, t: Twin) { + if !self.joins(&t) { + self.flush(); + } + let last = t.exec || t.store || t.upper_first; + self.run.push(t); + if last { + self.flush(); + } + } + + /// Writes the run: lanes 0..31, then 32..63. + fn flush(&mut self) { + let run = std::mem::take(&mut self.run); + if run.is_empty() { + return; + } + let exec = run.iter().any(|t| t.exec); + let vcc = run.iter().any(|t| t.vcc); + if run.iter().any(|t| t.upper_first) { + self.upper_copies(&run, exec, vcc); + self.lower_copies(&run, exec); + } else { + self.lower_copies(&run, exec); + self.upper_copies(&run, exec, vcc); + } + } + + fn lower_copies(&mut self, run: &[Twin], exec: bool) { + let e = self.x.e; + self.out.mov(EXEC_LO, e); + for t in run { + self.out.words.extend(&t.a.words); + } + if exec { + self.out.mov(e, EXEC_LO); + } + } + + fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) { + let e = self.x.e; + if vcc { + self.swap_vcc(); + } + self.out.mov(EXEC_LO, e + 1); + for t in run { + self.out.words.extend(&t.b.words); + } + if exec { + self.out.mov(e + 1, EXEC_LO); + } + if vcc { + self.swap_vcc(); + } + } + + /// Lane reads and writes: each half's lane is in its own twin. + fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> { + let x = self.x; + let (n, e) = (x.n, x.e); + let [t0, t1, t2] = x.t; + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + let src = |code: u32| -> Result<Src, Why> { + match code { + 0..=127 => Ok(sgpr(scalar(code as u8, &x))), + 255 => Ok(Src::Lit(d.literal.unwrap_or(0))), + 128..=208 | 240..=248 => Ok(Src::Code(code as u16)), + _ => Err("an operand a lane instruction cannot have"), + } + }; + // the lane's half (1: the twins) and number there, for a constant lane + let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32)); + let (s0, lane) = (f("SRC0"), f("SRC1")); + match d.inst.name { + "V_WRITELANE_B32" => { + let reg = f("VDST"); + twin(reg, Half::B, &x)?; + let s = src(s0)?; + if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s); + self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1)); + self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2)); + self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2)); + self.restore(live); + } else { + return Err("a lane write to a lane given otherwise"); + } + } + name => { + let dst = scalar(f("VDST") as u8, &x); + if s0 < 256 { + self.out.sop1("S_MOV_B32", dst, src(s0)?); + return Ok(()); + } + let reg = s0 - 256; + twin(reg, Half::B, &x)?; + if name == "V_READFIRSTLANE_B32" { + self.out.mov(EXEC_LO, e); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg)); + self.out.mov(EXEC_LO, e + 1); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n)); + self.save(live); + // the upper half's only where no lane of the lower half is active + self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0)); + self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1)); + self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else { + return Err("a lane read of a lane given otherwise"); + } + } + } + Ok(()) + } + + /// A scalar instruction (the console's EXEC renamed to E). + fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> { + let name = d.inst.name; + let x = self.x; + let e = x.e; + let [t0, t1, t2] = x.t; + let next = d.pc + d.len as u64; + match (d.enc.name, flow) { + ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live), + ("ENC_SOPP", Flow::Branch(t)) => { + let (lo, hi) = match name { + "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live), + "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1), + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI), + _ => return Err("a debug branch"), + }; + let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ"); + let on_zero = if name.ends_with("NZ") { nzb } else { zb }; + if !live { + self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi)); + return self.jump(on_zero, t, d.pc, live); + } + // SCC stays the console's: one dword at a time + self.out.mov(EXEC_LO, lo); + if on_zero == zb { + self.out.branch(nzb, next, d.pc); + } else { + self.jump(nzb, t, d.pc, live)?; + } + self.out.mov(EXEC_LO, hi); + return self.jump(on_zero, t, d.pc, live); + } + ("ENC_SOPP", _) => { + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SMEM", _) => { + let (r, w) = rdna2::sgpr_uses(d); + if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) { + return Err("EXEC as a scalar memory operand"); + } + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {} + _ => return Err("an unexpected scalar encoding"), + } + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + if name == "S_GETPC_B64" { + // the console's address, which its constant data is found from + let dst = scalar(f("SDST") as u8, &x); + let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1); + self.out.sop1("S_GETPC_B64", dst, int(0)); + self.save(live); + self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32)); + self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 })); + self.restore(live); + return Ok(()); + } + if let Flow::Jump(t) = flow { + return self.jump("S_BRANCH", t, d.pc, live); + } + if name.starts_with("S_MOVREL") { + return Err("a relative register move"); + } + if name.ends_with("EXEC_B32") { + return Err("a wave32 EXEC operation in a wave64 program"); + } + if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) { + let (lo, hi) = match f("SSRC0") { + c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)), + c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)), + c @ 128..=192 => (Src::Code(c as u16), int(0)), + c @ 193..=208 => (Src::Code(c as u16), int(-1)), + 255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)), + _ => return Err("a float or special constant as a 64-bit scalar operand"), + }; + // (operation, whether EXEC is its first operand) + let (op, exec_first) = match stem { + "S_AND" => ("S_AND_B32", false), + "S_OR" => ("S_OR_B32", false), + "S_XOR" => ("S_XOR_B32", false), + "S_ANDN2" => ("S_ANDN2_B32", false), + "S_ORN2" => ("S_ORN2_B32", false), + "S_NAND" => ("S_NAND_B32", false), + "S_NOR" => ("S_NOR_B32", false), + "S_XNOR" => ("S_XNOR_B32", false), + "S_ANDN1" => ("S_ANDN2_B32", true), + "S_ORN1" => ("S_ORN2_B32", true), + _ => return Err("an EXEC operation the rewrite does not know"), + }; + for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() { + let ek = sgpr(e + k as u8); + if exec_first { + self.out.sop2(op, t, ek, s); + } else { + self.out.sop2(op, t, s, ek); + } + } + let dst = f("SDST") as u8; + let old = name.contains("SAVEEXEC"); + if old && dst != NULL { + self.out.mov(scalar(dst, &x), e); + self.out.mov(scalar(dst, &x) + 1, e + 1); + } + self.out.mov(e, t0); + self.out.mov(e + 1, t1); + if !old && dst != NULL { + self.out.mov(scalar(dst, &x), t0); + self.out.mov(scalar(dst, &x) + 1, t1); + } + if live { + self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1)); + } + return Ok(()); + } + let mut w = d.words.clone(); + let mut rename = |shift: u32, bits: u32| -> Result<(), Why> { + let m = (1 << bits) - 1; + let c = w[0] >> shift & m; + let c = match c { + 251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"), + 0..=127 => u32::from(scalar(c as u8, &x)), + _ => c, + }; + w[0] = w[0] & !(m << shift) | c << shift; + Ok(()) + }; + if d.enc.name != "ENC_SOPC" { + rename(16, 7)?; + } + if d.enc.name != "ENC_SOPK" { + rename(0, 8)?; + } + if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") { + rename(8, 8)?; + } + self.out.words.extend(&w); + Ok(()) + } +} + +/// Seven scalar registers no instruction of the program names: two pairs, five single ones. +fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> { + let mut used = [false; 128]; + for d in list { + let (r, w) = rdna2::sgpr_uses(d); ~~~~ --- Right. `spare_sgprs` now marks an SDWA instruction's scalar operands too (S0, S1 and a VOPC SDST with SD, each as a pair), in `f1988c2e8`. Test: `an_sgpr_named_only_by_an_sdwa_operand_is_not_spare` (`v_cmp_eq_u32_sdwa s[104:105], v0, v1`; before the fix s[104:105] became E).
Royalflamejlh commented 2026-12-02 21:55:31 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T21:55:31Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 898

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))
+    }
+
+    fn push(&mut self, t: Twin) {
+        if !self.joins(&t) {
+            self.flush();
+        }
+        let last = t.exec || t.store || t.upper_first;
+        self.run.push(t);
+        if last {
+            self.flush();
+        }
+    }
+
+    /// Writes the run: lanes 0..31, then 32..63.
+    fn flush(&mut self) {
+        let run = std::mem::take(&mut self.run);
+        if run.is_empty() {
+            return;
+        }
+        let exec = run.iter().any(|t| t.exec);
+        let vcc = run.iter().any(|t| t.vcc);
+        if run.iter().any(|t| t.upper_first) {
+            self.upper_copies(&run, exec, vcc);
+            self.lower_copies(&run, exec);
+        } else {
+            self.lower_copies(&run, exec);
+            self.upper_copies(&run, exec, vcc);
+        }
+    }
+
+    fn lower_copies(&mut self, run: &[Twin], exec: bool) {
+        let e = self.x.e;
+        self.out.mov(EXEC_LO, e);
+        for t in run {
+            self.out.words.extend(&t.a.words);
+        }
+        if exec {
+            self.out.mov(e, EXEC_LO);
+        }
+    }
+
+    fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) {
+        let e = self.x.e;
+        if vcc {
+            self.swap_vcc();
+        }
+        self.out.mov(EXEC_LO, e + 1);
+        for t in run {
+            self.out.words.extend(&t.b.words);
+        }
+        if exec {
+            self.out.mov(e + 1, EXEC_LO);
+        }
+        if vcc {
+            self.swap_vcc();
+        }
+    }
+
+    /// Lane reads and writes: each half's lane is in its own twin.
+    fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> {
+        let x = self.x;
+        let (n, e) = (x.n, x.e);
+        let [t0, t1, t2] = x.t;
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        let src = |code: u32| -> Result<Src, Why> {
+            match code {
+                0..=127 => Ok(sgpr(scalar(code as u8, &x))),
+                255 => Ok(Src::Lit(d.literal.unwrap_or(0))),
+                128..=208 | 240..=248 => Ok(Src::Code(code as u16)),
+                _ => Err("an operand a lane instruction cannot have"),
+            }
+        };
+        // the lane's half (1: the twins) and number there, for a constant lane
+        let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32));
+        let (s0, lane) = (f("SRC0"), f("SRC1"));
+        match d.inst.name {
+            "V_WRITELANE_B32" => {
+                let reg = f("VDST");
+                twin(reg, Half::B, &x)?;
+                let s = src(s0)?;
+                if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s);
+                    self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1));
+                    self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2));
+                    self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2));
+                    self.restore(live);
+                } else {
+                    return Err("a lane write to a lane given otherwise");
+                }
+            }
+            name => {
+                let dst = scalar(f("VDST") as u8, &x);
+                if s0 < 256 {
+                    self.out.sop1("S_MOV_B32", dst, src(s0)?);
+                    return Ok(());
+                }
+                let reg = s0 - 256;
+                twin(reg, Half::B, &x)?;
+                if name == "V_READFIRSTLANE_B32" {
+                    self.out.mov(EXEC_LO, e);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg));
+                    self.out.mov(EXEC_LO, e + 1);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n));
+                    self.save(live);
+                    // the upper half's only where no lane of the lower half is active
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0));
+                    self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1));
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else {
+                    return Err("a lane read of a lane given otherwise");
+                }
+            }
+        }
+        Ok(())
+    }
+
+    /// A scalar instruction (the console's EXEC renamed to E).
+    fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> {
+        let name = d.inst.name;
+        let x = self.x;
+        let e = x.e;
+        let [t0, t1, t2] = x.t;
+        let next = d.pc + d.len as u64;
+        match (d.enc.name, flow) {
+            ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live),
+            ("ENC_SOPP", Flow::Branch(t)) => {
+                let (lo, hi) = match name {
+                    "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live),
+                    "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1),
+                    "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI),
+                    _ => return Err("a debug branch"),
+                };
+                let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ");
+                let on_zero = if name.ends_with("NZ") { nzb } else { zb };
+                if !live {
+                    self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi));
+                    return self.jump(on_zero, t, d.pc, live);
+                }
+                // SCC stays the console's: one dword at a time
+                self.out.mov(EXEC_LO, lo);
+                if on_zero == zb {
+                    self.out.branch(nzb, next, d.pc);
+                } else {
+                    self.jump(nzb, t, d.pc, live)?;
+                }
+                self.out.mov(EXEC_LO, hi);
+                return self.jump(on_zero, t, d.pc, live);
+            }
+            ("ENC_SOPP", _) => {
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SMEM", _) => {
+                let (r, w) = rdna2::sgpr_uses(d);
+                if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) {
+                    return Err("EXEC as a scalar memory operand");
+                }
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {}

Right. flow now refuses s_subvector_loop_begin/end (fold.rs ~628, f1988c2e8), so such a program keeps the split form. Test: what_the_rewrite_does_not_cover_is_refused_with_its_reason.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776637797 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776637797). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T21:55:31Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 898 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) + } + + fn push(&mut self, t: Twin) { + if !self.joins(&t) { + self.flush(); + } + let last = t.exec || t.store || t.upper_first; + self.run.push(t); + if last { + self.flush(); + } + } + + /// Writes the run: lanes 0..31, then 32..63. + fn flush(&mut self) { + let run = std::mem::take(&mut self.run); + if run.is_empty() { + return; + } + let exec = run.iter().any(|t| t.exec); + let vcc = run.iter().any(|t| t.vcc); + if run.iter().any(|t| t.upper_first) { + self.upper_copies(&run, exec, vcc); + self.lower_copies(&run, exec); + } else { + self.lower_copies(&run, exec); + self.upper_copies(&run, exec, vcc); + } + } + + fn lower_copies(&mut self, run: &[Twin], exec: bool) { + let e = self.x.e; + self.out.mov(EXEC_LO, e); + for t in run { + self.out.words.extend(&t.a.words); + } + if exec { + self.out.mov(e, EXEC_LO); + } + } + + fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) { + let e = self.x.e; + if vcc { + self.swap_vcc(); + } + self.out.mov(EXEC_LO, e + 1); + for t in run { + self.out.words.extend(&t.b.words); + } + if exec { + self.out.mov(e + 1, EXEC_LO); + } + if vcc { + self.swap_vcc(); + } + } + + /// Lane reads and writes: each half's lane is in its own twin. + fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> { + let x = self.x; + let (n, e) = (x.n, x.e); + let [t0, t1, t2] = x.t; + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + let src = |code: u32| -> Result<Src, Why> { + match code { + 0..=127 => Ok(sgpr(scalar(code as u8, &x))), + 255 => Ok(Src::Lit(d.literal.unwrap_or(0))), + 128..=208 | 240..=248 => Ok(Src::Code(code as u16)), + _ => Err("an operand a lane instruction cannot have"), + } + }; + // the lane's half (1: the twins) and number there, for a constant lane + let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32)); + let (s0, lane) = (f("SRC0"), f("SRC1")); + match d.inst.name { + "V_WRITELANE_B32" => { + let reg = f("VDST"); + twin(reg, Half::B, &x)?; + let s = src(s0)?; + if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s); + self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1)); + self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2)); + self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2)); + self.restore(live); + } else { + return Err("a lane write to a lane given otherwise"); + } + } + name => { + let dst = scalar(f("VDST") as u8, &x); + if s0 < 256 { + self.out.sop1("S_MOV_B32", dst, src(s0)?); + return Ok(()); + } + let reg = s0 - 256; + twin(reg, Half::B, &x)?; + if name == "V_READFIRSTLANE_B32" { + self.out.mov(EXEC_LO, e); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg)); + self.out.mov(EXEC_LO, e + 1); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n)); + self.save(live); + // the upper half's only where no lane of the lower half is active + self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0)); + self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1)); + self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else { + return Err("a lane read of a lane given otherwise"); + } + } + } + Ok(()) + } + + /// A scalar instruction (the console's EXEC renamed to E). + fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> { + let name = d.inst.name; + let x = self.x; + let e = x.e; + let [t0, t1, t2] = x.t; + let next = d.pc + d.len as u64; + match (d.enc.name, flow) { + ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live), + ("ENC_SOPP", Flow::Branch(t)) => { + let (lo, hi) = match name { + "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live), + "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1), + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI), + _ => return Err("a debug branch"), + }; + let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ"); + let on_zero = if name.ends_with("NZ") { nzb } else { zb }; + if !live { + self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi)); + return self.jump(on_zero, t, d.pc, live); + } + // SCC stays the console's: one dword at a time + self.out.mov(EXEC_LO, lo); + if on_zero == zb { + self.out.branch(nzb, next, d.pc); + } else { + self.jump(nzb, t, d.pc, live)?; + } + self.out.mov(EXEC_LO, hi); + return self.jump(on_zero, t, d.pc, live); + } + ("ENC_SOPP", _) => { + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SMEM", _) => { + let (r, w) = rdna2::sgpr_uses(d); + if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) { + return Err("EXEC as a scalar memory operand"); + } + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {} ~~~~ --- Right. `flow` now refuses `s_subvector_loop_begin/end` (`fold.rs` ~628, `f1988c2e8`), so such a program keeps the split form. Test: `what_the_rewrite_does_not_cover_is_refused_with_its_reason`.
Royalflamejlh commented 2026-12-02 21:55:32 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T21:55:32Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 1027

@@ -0,0 +1,1162 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,
+                _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?,
+            }
+            if d.enc.name != "ENC_VOP1" {
+                let c1 = w[0] >> 9 & 0xFF;
+                let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? };
+                w[0] = w[0] & !(0xFF << 9) | c1 << 9;
+            }
+            if !vopc {
+                w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17;
+            } else if src0 != 0xF9 {
+                if cmpx {
+                    t.exec = true;
+                } else {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+            if d.enc.name == "ENC_VOP2" && carry_in {
+                side.reads.push(mask_console(VCC_LO, half));
+                if co_ci {
+                    side.writes.push(mask_console(VCC_LO, half));
+                }
+            }
+        }
+        _ => {
+            let vop3 = d.enc.name != "ENC_VOP3P";
+            let dst = w[0] & 0xFF;
+            if vop3 && name.starts_with("V_CMP") {
+                let dst = dst as u8;
+                if cmpx && dst != EXEC_LO {
+                    return Err("a VOP3 v_cmpx with another destination");
+                }
+                if dst == EXEC_LO {
+                    t.exec = true;
+                } else if dst != NULL {
+                    side.writes.push(mask_console(dst, half));
+                }
+                w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x));
+            } else {
+                w[0] = w[0] & !0xFF | twin(dst, half, x)?;
+            }
+            if d.enc.name == "VOP3_SDST_ENC" {
+                let s = (w[0] >> 8 & 0x7F) as u8;
+                if s == EXEC_LO {
+                    return Err("a carry into EXEC");
+                }
+                if s != NULL {
+                    side.writes.push(mask_console(s, half));
+                }
+                w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8;
+            }
+            let mut w1 = w[1];
+            for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) {
+                let f = w1 >> (9 * i) & 0x1FF;
+                let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? };
+                w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i);
+            }
+            w[1] = w1;
+            // a literal mask operand became an inline 0: the literal goes with it
+            if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) {
+                w.truncate(2);
+            }
+        }
+    }
+    if name.starts_with("V_DIV_FMAS") {
+        if half == Half::B {
+            return Err(NEEDS_SWAP);
+        }
+        side.reads.push(mask_console(VCC_LO, half));
+    }
+    // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword
+    let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in };
+    if half == Half::B && implicit {
+        let src0 = w[0] & 0x1FF;
+        if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) {
+            return Err(NEEDS_SWAP);
+        }
+        let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF));
+        let hi = u64::from(VCC_HI);
+        let lit = (src0 == 255).then(|| w[1]);
+        let b = if vopc {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit)
+        } else if co_ci {
+            rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        } else {
+            rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit)
+        };
+        w = words(&b.map_err(|_| "an opcode without a VOP3 form")?);
+    }
+    if t.exec {
+        side.writes.push(mask_console(EXEC_LO, half));
+    }
+    side.words = w;
+    Ok(side)
+}
+
+/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes
+/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword
+/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it).
+fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> {
+    let mut t = Twin::default();
+    let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) };
+    let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF);
+    let hi = d.inst.name == "V_MBCNT_HI_U32_B32";
+    for half in [Half::A, Half::B] {
+        let mut side = Side::default();
+        let s0 = src(source9(f0, 1, half, x, &mut side)?);
+        let s1 = src(source9(f1, 1, half, x, &mut side)?);
+        let vd = twin(d.words[0] & 0xFF, half, x)?;
+        let mut a = Asm::default();
+        match (half, hi) {
+            (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+            (Half::A, true) => a.vop1("V_MOV_B32", vd, s1),
+            (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1),
+            (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1),
+        }
+        side.words = a.words;
+        match half {
+            Half::A => t.a = side,
+            _ => t.b = side,
+        }
+    }
+    Ok(t)
+}
+
+fn writes_memory(d: &Decoded) -> bool {
+    let name = d.inst.name;
+    match d.enc.name {
+        "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")),
+        "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)),
+        _ => !name.contains("_LOAD_"),
+    }
+}
+
+/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for
+/// the upper half.
+fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1);
+    let refused = match d.enc.name {
+        "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => {
+            Some("an LDS operation on the wave's lanes or the GDS")
+        }
+        "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"),
+        "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"),
+        "ENC_FLAT_SCRATCH" => Some("scratch"),
+        _ => None,
+    };
+    if let Some(why) = refused {
+        return Err(why);
+    }
+    let (reads, _) = rdna2::sgpr_uses(d);
+    if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) {
+        return Err("EXEC or VCC as a memory instruction's operand");
+    }
+    let mut w = d.words.clone();
+    let mut byte = |i: usize, shift: u32| -> Result<(), Why> {
+        w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift;
+        Ok(())
+    };
+    match d.enc.name {
+        "ENC_MIMG" => {
+            byte(1, 0)?;
+            byte(1, 8)?;
+            for i in 2..d.words.len() {
+                for shift in [0, 8, 16, 24] {
+                    byte(i, shift)?;
+                }
+            }
+        }
+        "ENC_MUBUF" | "ENC_MTBUF" => {
+            if f("OFFEN") || f("IDXEN") {
+                byte(1, 0)?;
+            }
+            byte(1, 8)?;
+        }
+        _ => {
+            for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] {
+                if has(d, field) {
+                    byte(1, shift)?;
+                }
+            }
+        }
+    }
+    Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Flow {
+    Next,
+    Stop,
+    Jump(u64),
+    Branch(u64),
+}
+
+fn flow(d: &Decoded) -> Result<Flow, Why> {
+    let name = d.inst.name;
+    if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() {
+        return Err("a call or an indirect jump");
+    }
+    Ok(match rdna2::branch_target(d) {
+        Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t),
+        Some(t) => Flow::Branch(t),
+        None if name.starts_with("S_ENDPGM") => Flow::Stop,
+        None => Flow::Next,
+    })
+}
+
+fn scc_use(d: &Decoded) -> (bool, bool) {
+    let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output });
+    let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253))
+        || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253;
+    (op(true) || named, op(false))
+}
+
+/// Whether SCC is live after each instruction of `list`.
+fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> {
+    let n = list.len();
+    let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect();
+    let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]);
+    let mut changed = true;
+    while changed {
+        changed = false;
+        for i in (0..n).rev() {
+            let out = succs[i].iter().any(|&s| live_in[s]);
+            let inn = uses[i].0 || out && !uses[i].1;
+            if out != live_out[i] || inn != live_in[i] {
+                live_out[i] = out;
+                live_in[i] = inn;
+                changed = true;
+            }
+        }
+    }
+    live_out
+}
+
+/// The rewrite's state: the code so far and the run of vector instructions not yet written.
+struct Fold<'a> {
+    x: Spare,
+    out: Asm,
+    run: Vec<Twin>,
+    /// console instructions whose branches are far jumps
+    far: &'a HashSet<u64>,
+}
+
+impl Fold<'_> {
+    /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is
+    /// in `far` (SCC must then be free after it).
+    fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> {
+        if !self.far.contains(&origin) {
+            self.out.branch(name, to, origin);
+            return Ok(());
+        }
+        if scc_live {
+            return Err("a far branch where SCC is live");
+        }
+        if name != "S_BRANCH" {
+            let not = match name {
+                "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1",
+                "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0",
+                "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ",
+                _ => "S_CBRANCH_EXECZ",
+            };
+            self.out.sopp(not, 5);
+        }
+        self.out.far_jump(self.x.jp, to);
+        Ok(())
+    }
+
+    fn save(&mut self, live: bool) {
+        if live {
+            self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0));
+        }
+    }
+
+    fn restore(&mut self, live: bool) {
+        if live {
+            self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0));
+        }
+    }
+
+    fn swap_vcc(&mut self) {
+        let s = self.x.swap;
+        self.out.mov(s, VCC_LO);
+        self.out.mov(VCC_LO, VCC_HI);
+        self.out.mov(VCC_HI, s);
+    }
+
+    /// Whether `t` can join the run without reordering what the console orders.
+    fn joins(&self, t: &Twin) -> bool {
+        if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) {
+            return self.run.is_empty();
+        }
+        self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads))
+    }
+
+    fn push(&mut self, t: Twin) {
+        if !self.joins(&t) {
+            self.flush();
+        }
+        let last = t.exec || t.store || t.upper_first;
+        self.run.push(t);
+        if last {
+            self.flush();
+        }
+    }
+
+    /// Writes the run: lanes 0..31, then 32..63.
+    fn flush(&mut self) {
+        let run = std::mem::take(&mut self.run);
+        if run.is_empty() {
+            return;
+        }
+        let exec = run.iter().any(|t| t.exec);
+        let vcc = run.iter().any(|t| t.vcc);
+        if run.iter().any(|t| t.upper_first) {
+            self.upper_copies(&run, exec, vcc);
+            self.lower_copies(&run, exec);
+        } else {
+            self.lower_copies(&run, exec);
+            self.upper_copies(&run, exec, vcc);
+        }
+    }
+
+    fn lower_copies(&mut self, run: &[Twin], exec: bool) {
+        let e = self.x.e;
+        self.out.mov(EXEC_LO, e);
+        for t in run {
+            self.out.words.extend(&t.a.words);
+        }
+        if exec {
+            self.out.mov(e, EXEC_LO);
+        }
+    }
+
+    fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) {
+        let e = self.x.e;
+        if vcc {
+            self.swap_vcc();
+        }
+        self.out.mov(EXEC_LO, e + 1);
+        for t in run {
+            self.out.words.extend(&t.b.words);
+        }
+        if exec {
+            self.out.mov(e + 1, EXEC_LO);
+        }
+        if vcc {
+            self.swap_vcc();
+        }
+    }
+
+    /// Lane reads and writes: each half's lane is in its own twin.
+    fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> {
+        let x = self.x;
+        let (n, e) = (x.n, x.e);
+        let [t0, t1, t2] = x.t;
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        let src = |code: u32| -> Result<Src, Why> {
+            match code {
+                0..=127 => Ok(sgpr(scalar(code as u8, &x))),
+                255 => Ok(Src::Lit(d.literal.unwrap_or(0))),
+                128..=208 | 240..=248 => Ok(Src::Code(code as u16)),
+                _ => Err("an operand a lane instruction cannot have"),
+            }
+        };
+        // the lane's half (1: the twins) and number there, for a constant lane
+        let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32));
+        let (s0, lane) = (f("SRC0"), f("SRC1"));
+        match d.inst.name {
+            "V_WRITELANE_B32" => {
+                let reg = f("VDST");
+                twin(reg, Half::B, &x)?;
+                let s = src(s0)?;
+                if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s);
+                    self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1));
+                    self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2));
+                    self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2));
+                    self.restore(live);
+                } else {
+                    return Err("a lane write to a lane given otherwise");
+                }
+            }
+            name => {
+                let dst = scalar(f("VDST") as u8, &x);
+                if s0 < 256 {
+                    self.out.sop1("S_MOV_B32", dst, src(s0)?);
+                    return Ok(());
+                }
+                let reg = s0 - 256;
+                twin(reg, Half::B, &x)?;
+                if name == "V_READFIRSTLANE_B32" {
+                    self.out.mov(EXEC_LO, e);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg));
+                    self.out.mov(EXEC_LO, e + 1);
+                    self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n));
+                    self.save(live);
+                    // the upper half's only where no lane of the lower half is active
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0));
+                    self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1));
+                    self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else if let Some((half, k)) = fixed(lane) {
+                    self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k));
+                } else if lane < 128 {
+                    let l = scalar(lane as u8, &x);
+                    self.save(live);
+                    self.out.sop2("S_AND_B32", t2, sgpr(l), int(31));
+                    self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2));
+                    self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2));
+                    self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5));
+                    self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0));
+                    self.restore(live);
+                } else {
+                    return Err("a lane read of a lane given otherwise");
+                }
+            }
+        }
+        Ok(())
+    }
+
+    /// A scalar instruction (the console's EXEC renamed to E).
+    fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> {
+        let name = d.inst.name;
+        let x = self.x;
+        let e = x.e;
+        let [t0, t1, t2] = x.t;
+        let next = d.pc + d.len as u64;
+        match (d.enc.name, flow) {
+            ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live),
+            ("ENC_SOPP", Flow::Branch(t)) => {
+                let (lo, hi) = match name {
+                    "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live),
+                    "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1),
+                    "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI),
+                    _ => return Err("a debug branch"),
+                };
+                let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ");
+                let on_zero = if name.ends_with("NZ") { nzb } else { zb };
+                if !live {
+                    self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi));
+                    return self.jump(on_zero, t, d.pc, live);
+                }
+                // SCC stays the console's: one dword at a time
+                self.out.mov(EXEC_LO, lo);
+                if on_zero == zb {
+                    self.out.branch(nzb, next, d.pc);
+                } else {
+                    self.jump(nzb, t, d.pc, live)?;
+                }
+                self.out.mov(EXEC_LO, hi);
+                return self.jump(on_zero, t, d.pc, live);
+            }
+            ("ENC_SOPP", _) => {
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SMEM", _) => {
+                let (r, w) = rdna2::sgpr_uses(d);
+                if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) {
+                    return Err("EXEC as a scalar memory operand");
+                }
+                self.out.words.extend(&d.words);
+                return Ok(());
+            }
+            ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {}
+            _ => return Err("an unexpected scalar encoding"),
+        }
+        let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32;
+        if name == "S_GETPC_B64" {
+            // the console's address, which its constant data is found from
+            let dst = scalar(f("SDST") as u8, &x);
+            let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1);
+            self.out.sop1("S_GETPC_B64", dst, int(0));
+            self.save(live);
+            self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32));
+            self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 }));
+            self.restore(live);
+            return Ok(());
+        }
+        if let Flow::Jump(t) = flow {
+            return self.jump("S_BRANCH", t, d.pc, live);
+        }
+        if name.starts_with("S_MOVREL") {
+            return Err("a relative register move");
+        }
+        if name.ends_with("EXEC_B32") {
+            return Err("a wave32 EXEC operation in a wave64 program");
+        }
+        if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) {
+            let (lo, hi) = match f("SSRC0") {
+                c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)),
+                c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)),
+                c @ 128..=192 => (Src::Code(c as u16), int(0)),
+                c @ 193..=208 => (Src::Code(c as u16), int(-1)),
+                255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)),
+                _ => return Err("a float or special constant as a 64-bit scalar operand"),
+            };
+            // (operation, whether EXEC is its first operand)
+            let (op, exec_first) = match stem {
+                "S_AND" => ("S_AND_B32", false),
+                "S_OR" => ("S_OR_B32", false),
+                "S_XOR" => ("S_XOR_B32", false),
+                "S_ANDN2" => ("S_ANDN2_B32", false),
+                "S_ORN2" => ("S_ORN2_B32", false),
+                "S_NAND" => ("S_NAND_B32", false),
+                "S_NOR" => ("S_NOR_B32", false),
+                "S_XNOR" => ("S_XNOR_B32", false),
+                "S_ANDN1" => ("S_ANDN2_B32", true),
+                "S_ORN1" => ("S_ORN2_B32", true),
+                _ => return Err("an EXEC operation the rewrite does not know"),
+            };
+            for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() {
+                let ek = sgpr(e + k as u8);
+                if exec_first {
+                    self.out.sop2(op, t, ek, s);
+                } else {
+                    self.out.sop2(op, t, s, ek);
+                }
+            }
+            let dst = f("SDST") as u8;
+            let old = name.contains("SAVEEXEC");
+            if old && dst != NULL {
+                self.out.mov(scalar(dst, &x), e);
+                self.out.mov(scalar(dst, &x) + 1, e + 1);
+            }
+            self.out.mov(e, t0);
+            self.out.mov(e + 1, t1);
+            if !old && dst != NULL {
+                self.out.mov(scalar(dst, &x), t0);
+                self.out.mov(scalar(dst, &x) + 1, t1);
+            }
+            if live {
+                self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1));
+            }
+            return Ok(());
+        }
+        let mut w = d.words.clone();
+        let mut rename = |shift: u32, bits: u32| -> Result<(), Why> {
+            let m = (1 << bits) - 1;
+            let c = w[0] >> shift & m;
+            let c = match c {
+                251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"),
+                0..=127 => u32::from(scalar(c as u8, &x)),
+                _ => c,
+            };
+            w[0] = w[0] & !(m << shift) | c << shift;
+            Ok(())
+        };
+        if d.enc.name != "ENC_SOPC" {
+            rename(16, 7)?;
+        }
+        if d.enc.name != "ENC_SOPK" {
+            rename(0, 8)?;
+        }
+        if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") {
+            rename(8, 8)?;
+        }
+        self.out.words.extend(&w);
+        Ok(())
+    }
+}
+
+/// Seven scalar registers no instruction of the program names: two pairs, five single ones.
+fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> {
+    let mut used = [false; 128];
+    for d in list {
+        let (r, w) = rdna2::sgpr_uses(d);
+        for c in r.into_iter().chain(w) {
+            used[c as usize] = true;
+        }
+    }
+    let mut free = (0..=105u8).rev().filter(|&c| !used[usize::from(c)]);
+    let mut pairs = [0u8; 2];
+    let mut rest = Vec::new();
+    let mut k = 0;
+    while k < 2 || rest.len() < 5 {
+        let c = free.next().ok_or("no spare scalar registers")?;
+        if k < 2 && c % 2 == 1 && c > 0 && !used[usize::from(c - 1)] {
+            free.next();
+            pairs[k] = c - 1;
+            k += 1;
+        } else {
+            rest.push(c);
+        }
+    }
+    Ok((pairs, [rest[0], rest[1], rest[2], rest[3], rest[4]]))
+}
+
+/// The program's VGPR count: one past the highest it names.
+fn vgprs(list: &[Decoded]) -> u32 {
+    list.iter()
+        .flat_map(|d| {
+            let (r, w) = rdna2::vgpr_uses(d);
+            let tfe = u64::from(field_value(d.enc, &d.words, "TFE") == Some(1));

Right. vgprs now adds the status dword for LWE as for TFE (fold.rs ~1050, f1988c2e8). Test: an_image_load_with_lwe_counts_its_status_dword (an image_load into v10 with LWE: N is 12; 11 before the fix).

<!-- greyfinch-sync:ivall/xcl:review-comment:4776638147 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776638147). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T21:55:32Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 1027 ~~~~diff @@ -0,0 +1,1162 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, + _ => w[0] = w[0] & !0x1FF | source9(src0, dwords(d, "SRC0"), half, x, &mut side)?, + } + if d.enc.name != "ENC_VOP1" { + let c1 = w[0] >> 9 & 0xFF; + let c1 = if vsrc1_sgpr { source9(c1, dwords(d, "VSRC1"), half, x, &mut side)? & 0xFF } else { twin(c1, half, x)? }; + w[0] = w[0] & !(0xFF << 9) | c1 << 9; + } + if !vopc { + w[0] = w[0] & !(0xFF << 17) | twin(w[0] >> 17 & 0xFF, half, x)? << 17; + } else if src0 != 0xF9 { + if cmpx { + t.exec = true; + } else { + side.writes.push(mask_console(VCC_LO, half)); + } + } + if d.enc.name == "ENC_VOP2" && carry_in { + side.reads.push(mask_console(VCC_LO, half)); + if co_ci { + side.writes.push(mask_console(VCC_LO, half)); + } + } + } + _ => { + let vop3 = d.enc.name != "ENC_VOP3P"; + let dst = w[0] & 0xFF; + if vop3 && name.starts_with("V_CMP") { + let dst = dst as u8; + if cmpx && dst != EXEC_LO { + return Err("a VOP3 v_cmpx with another destination"); + } + if dst == EXEC_LO { + t.exec = true; + } else if dst != NULL { + side.writes.push(mask_console(dst, half)); + } + w[0] = w[0] & !0xFF | u32::from(mask(dst, half, x)); + } else { + w[0] = w[0] & !0xFF | twin(dst, half, x)?; + } + if d.enc.name == "VOP3_SDST_ENC" { + let s = (w[0] >> 8 & 0x7F) as u8; + if s == EXEC_LO { + return Err("a carry into EXEC"); + } + if s != NULL { + side.writes.push(mask_console(s, half)); + } + w[0] = w[0] & !(0x7F << 8) | u32::from(mask(s, half, x)) << 8; + } + let mut w1 = w[1]; + for (i, field) in ["SRC0", "SRC1", "SRC2"].into_iter().enumerate().filter(|(_, f)| has(d, f)) { + let f = w1 >> (9 * i) & 0x1FF; + let g = if vop3 && i == 2 && carry_in { mask9(f, half, x, &mut side)? } else { source9(f, dwords(d, field), half, x, &mut side)? }; + w1 = w1 & !(0x1FF << (9 * i)) | g << (9 * i); + } + w[1] = w1; + // a literal mask operand became an inline 0: the literal goes with it + if w.len() == 3 && !(0..3).any(|i| w1 >> (9 * i) & 0x1FF == 255) { + w.truncate(2); + } + } + } + if name.starts_with("V_DIV_FMAS") { + if half == Half::B { + return Err(NEEDS_SWAP); + } + side.reads.push(mask_console(VCC_LO, half)); + } + // the upper half of an implicit VCC: the VOP3 form, which names VCC's upper dword + let implicit = if vopc { !cmpx && w[0] & 0x1FF != 0xF9 } else { d.enc.name == "ENC_VOP2" && carry_in }; + if half == Half::B && implicit { + let src0 = w[0] & 0x1FF; + if matches!(src0, 0xF9 | 0xFA | 0xE9 | 0xEA) { + return Err(NEEDS_SWAP); + } + let (src0, src1, dst) = (u64::from(src0), u64::from(256 + (w[0] >> 9 & 0xFF)), u64::from(w[0] >> 17 & 0xFF)); + let hi = u64::from(VCC_HI); + let lit = (src0 == 255).then(|| w[1]); + let b = if vopc { + rdna2::encode(name, "ENC_VOP3", &[("VDST", hi), ("SRC0", src0), ("SRC1", src1)], lit) + } else if co_ci { + rdna2::encode(name, "VOP3_SDST_ENC", &[("VDST", dst), ("SDST", hi), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + } else { + rdna2::encode(name, "ENC_VOP3", &[("VDST", dst), ("SRC0", src0), ("SRC1", src1), ("SRC2", hi)], lit) + }; + w = words(&b.map_err(|_| "an opcode without a VOP3 form")?); + } + if t.exec { + side.writes.push(mask_console(EXEC_LO, half)); + } + side.words = w; + Ok(side) +} + +/// `v_mbcnt_lo/hi_u32_b32 d, mask, add`: lane t's count of the mask's bits below it. Lanes +/// 0..31 count the low dword's and nothing of the high; lanes 32..63 all of the low dword +/// (`v_bcnt_u32_b32`) and the high dword's below t (a low count of it). +fn mbcnt(d: &Decoded, x: &Spare) -> Result<Twin, Why> { + let mut t = Twin::default(); + let src = |code: u32| if code == 255 { Src::Lit(d.literal.unwrap_or(0)) } else { Src::Code(code as u16) }; + let (f0, f1) = (d.words[1] & 0x1FF, d.words[1] >> 9 & 0x1FF); + let hi = d.inst.name == "V_MBCNT_HI_U32_B32"; + for half in [Half::A, Half::B] { + let mut side = Side::default(); + let s0 = src(source9(f0, 1, half, x, &mut side)?); + let s1 = src(source9(f1, 1, half, x, &mut side)?); + let vd = twin(d.words[0] & 0xFF, half, x)?; + let mut a = Asm::default(); + match (half, hi) { + (Half::A, false) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + (Half::A, true) => a.vop1("V_MOV_B32", vd, s1), + (_, false) => a.vop3("V_BCNT_U32_B32", vd, s0, s1), + (_, true) => a.vop3("V_MBCNT_LO_U32_B32", vd, s0, s1), + } + side.words = a.words; + match half { + Half::A => t.a = side, + _ => t.b = side, + } + } + Ok(t) +} + +fn writes_memory(d: &Decoded) -> bool { + let name = d.inst.name; + match d.enc.name { + "ENC_DS" => !(name.starts_with("DS_READ") || name.starts_with("DS_SWIZZLE")), + "ENC_MIMG" => !["IMAGE_LOAD", "IMAGE_SAMPLE", "IMAGE_GATHER", "IMAGE_GET_", "IMAGE_BVH"].iter().any(|p| name.starts_with(p)), + _ => !name.contains("_LOAD_"), + } +} + +/// The copy of vector memory instruction `d` for `half`: its VGPRs moved to the twins for +/// the upper half. +fn memory_copy(d: &Decoded, half: Half, x: &Spare) -> Result<Side, Why> { + let name = d.inst.name; + let f = |n: &str| field_value(d.enc, &d.words, n) == Some(1); + let refused = match d.enc.name { + "ENC_DS" if f("GDS") || name.contains("ADDTID") || name.starts_with("DS_GWS") || matches!(name, "DS_APPEND" | "DS_CONSUME" | "DS_ORDERED_COUNT") => { + Some("an LDS operation on the wave's lanes or the GDS") + } + "ENC_DS" if name.contains("PERMUTE") => Some("ds_(b)permute"), + "ENC_MUBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" if f("LDS") => Some("a load into LDS"), + "ENC_FLAT_SCRATCH" => Some("scratch"), + _ => None, + }; + if let Some(why) = refused { + return Err(why); + } + let (reads, _) = rdna2::sgpr_uses(d); + if reads.iter().any(|&r| matches!(r as u8, VCC_LO | VCC_HI | EXEC_LO | EXEC_HI)) { + return Err("EXEC or VCC as a memory instruction's operand"); + } + let mut w = d.words.clone(); + let mut byte = |i: usize, shift: u32| -> Result<(), Why> { + w[i] = w[i] & !(0xFF << shift) | twin(w[i] >> shift & 0xFF, half, x)? << shift; + Ok(()) + }; + match d.enc.name { + "ENC_MIMG" => { + byte(1, 0)?; + byte(1, 8)?; + for i in 2..d.words.len() { + for shift in [0, 8, 16, 24] { + byte(i, shift)?; + } + } + } + "ENC_MUBUF" | "ENC_MTBUF" => { + if f("OFFEN") || f("IDXEN") { + byte(1, 0)?; + } + byte(1, 8)?; + } + _ => { + for (field, shift) in [("ADDR", 0), ("DATA0", 8), ("DATA", 8), ("DATA1", 16), ("VDST", 24)] { + if has(d, field) { + byte(1, shift)?; + } + } + } + } + Ok(Side { words: w, reads: reads.into_iter().map(|r| r as u8).collect(), writes: Vec::new() }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Flow { + Next, + Stop, + Jump(u64), + Branch(u64), +} + +fn flow(d: &Decoded) -> Result<Flow, Why> { + let name = d.inst.name; + if matches!(name, "S_CALL_B64" | "S_SWAPPC_B64" | "S_RFE_B64") || name == "S_SETPC_B64" && d.far_target.is_none() { + return Err("a call or an indirect jump"); + } + Ok(match rdna2::branch_target(d) { + Some(t) if name == "S_BRANCH" || d.far_target.is_some() => Flow::Jump(t), + Some(t) => Flow::Branch(t), + None if name.starts_with("S_ENDPGM") => Flow::Stop, + None => Flow::Next, + }) +} + +fn scc_use(d: &Decoded) -> (bool, bool) { + let op = |input: bool| d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && if input { o.input } else { o.output }); + let named = ["SRC0", "SRC1", "SRC2", "SSRC0", "SSRC1"].iter().any(|f| has(d, f) && field_value(d.enc, &d.words, f) == Some(253)) + || d.variant == Variant::Sdwa && d.words[1] & 0xFF == 253; + (op(true) || named, op(false)) +} + +/// Whether SCC is live after each instruction of `list`. +fn scc_live(list: &[Decoded], succs: &[Vec<usize>]) -> Vec<bool> { + let n = list.len(); + let uses: Vec<(bool, bool)> = list.iter().map(scc_use).collect(); + let (mut live_in, mut live_out) = (vec![false; n], vec![false; n]); + let mut changed = true; + while changed { + changed = false; + for i in (0..n).rev() { + let out = succs[i].iter().any(|&s| live_in[s]); + let inn = uses[i].0 || out && !uses[i].1; + if out != live_out[i] || inn != live_in[i] { + live_out[i] = out; + live_in[i] = inn; + changed = true; + } + } + } + live_out +} + +/// The rewrite's state: the code so far and the run of vector instructions not yet written. +struct Fold<'a> { + x: Spare, + out: Asm, + run: Vec<Twin>, + /// console instructions whose branches are far jumps + far: &'a HashSet<u64>, +} + +impl Fold<'_> { + /// A branch of the console instruction at `origin` to `to`; a far jump where `origin` is + /// in `far` (SCC must then be free after it). + fn jump(&mut self, name: &str, to: u64, origin: u64, scc_live: bool) -> Result<(), Why> { + if !self.far.contains(&origin) { + self.out.branch(name, to, origin); + return Ok(()); + } + if scc_live { + return Err("a far branch where SCC is live"); + } + if name != "S_BRANCH" { + let not = match name { + "S_CBRANCH_SCC0" => "S_CBRANCH_SCC1", + "S_CBRANCH_SCC1" => "S_CBRANCH_SCC0", + "S_CBRANCH_EXECZ" => "S_CBRANCH_EXECNZ", + _ => "S_CBRANCH_EXECZ", + }; + self.out.sopp(not, 5); + } + self.out.far_jump(self.x.jp, to); + Ok(()) + } + + fn save(&mut self, live: bool) { + if live { + self.out.sop2("S_CSELECT_B32", self.x.save, int(1), int(0)); + } + } + + fn restore(&mut self, live: bool) { + if live { + self.out.sopc("S_CMP_LG_U32", sgpr(self.x.save), int(0)); + } + } + + fn swap_vcc(&mut self) { + let s = self.x.swap; + self.out.mov(s, VCC_LO); + self.out.mov(VCC_LO, VCC_HI); + self.out.mov(VCC_HI, s); + } + + /// Whether `t` can join the run without reordering what the console orders. + fn joins(&self, t: &Twin) -> bool { + if t.store || t.upper_first || self.run.iter().any(|j| j.store || j.exec || j.upper_first) { + return self.run.is_empty(); + } + self.run.iter().all(|j| !meets(&t.a.writes, &j.b.reads) && !meets(&t.a.writes, &j.b.writes) && !meets(&j.b.writes, &t.a.reads)) + } + + fn push(&mut self, t: Twin) { + if !self.joins(&t) { + self.flush(); + } + let last = t.exec || t.store || t.upper_first; + self.run.push(t); + if last { + self.flush(); + } + } + + /// Writes the run: lanes 0..31, then 32..63. + fn flush(&mut self) { + let run = std::mem::take(&mut self.run); + if run.is_empty() { + return; + } + let exec = run.iter().any(|t| t.exec); + let vcc = run.iter().any(|t| t.vcc); + if run.iter().any(|t| t.upper_first) { + self.upper_copies(&run, exec, vcc); + self.lower_copies(&run, exec); + } else { + self.lower_copies(&run, exec); + self.upper_copies(&run, exec, vcc); + } + } + + fn lower_copies(&mut self, run: &[Twin], exec: bool) { + let e = self.x.e; + self.out.mov(EXEC_LO, e); + for t in run { + self.out.words.extend(&t.a.words); + } + if exec { + self.out.mov(e, EXEC_LO); + } + } + + fn upper_copies(&mut self, run: &[Twin], exec: bool, vcc: bool) { + let e = self.x.e; + if vcc { + self.swap_vcc(); + } + self.out.mov(EXEC_LO, e + 1); + for t in run { + self.out.words.extend(&t.b.words); + } + if exec { + self.out.mov(e + 1, EXEC_LO); + } + if vcc { + self.swap_vcc(); + } + } + + /// Lane reads and writes: each half's lane is in its own twin. + fn lanes(&mut self, d: &Decoded, live: bool) -> Result<(), Why> { + let x = self.x; + let (n, e) = (x.n, x.e); + let [t0, t1, t2] = x.t; + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + let src = |code: u32| -> Result<Src, Why> { + match code { + 0..=127 => Ok(sgpr(scalar(code as u8, &x))), + 255 => Ok(Src::Lit(d.literal.unwrap_or(0))), + 128..=208 | 240..=248 => Ok(Src::Code(code as u16)), + _ => Err("an operand a lane instruction cannot have"), + } + }; + // the lane's half (1: the twins) and number there, for a constant lane + let fixed = |code: u32| (128..=192).contains(&code).then(|| ((code - 128) >> 5 & 1, (code - 128 & 31) as i32)); + let (s0, lane) = (f("SRC0"), f("SRC1")); + match d.inst.name { + "V_WRITELANE_B32" => { + let reg = f("VDST"); + twin(reg, Half::B, &x)?; + let s = src(s0)?; + if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_WRITELANE_B32", reg + half * n, s, int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", t0, sgpr(t0), s); + self.out.sop2("S_CSELECT_B32", t1, s, sgpr(t1)); + self.out.vop3("V_WRITELANE_B32", reg, sgpr(t0), sgpr(t2)); + self.out.vop3("V_WRITELANE_B32", reg + n, sgpr(t1), sgpr(t2)); + self.restore(live); + } else { + return Err("a lane write to a lane given otherwise"); + } + } + name => { + let dst = scalar(f("VDST") as u8, &x); + if s0 < 256 { + self.out.sop1("S_MOV_B32", dst, src(s0)?); + return Ok(()); + } + let reg = s0 - 256; + twin(reg, Half::B, &x)?; + if name == "V_READFIRSTLANE_B32" { + self.out.mov(EXEC_LO, e); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t0), vgpr(reg)); + self.out.mov(EXEC_LO, e + 1); + self.out.vop1("V_READFIRSTLANE_B32", u32::from(t1), vgpr(reg + n)); + self.save(live); + // the upper half's only where no lane of the lower half is active + self.out.sopc("S_CMP_LG_U32", sgpr(e), int(0)); + self.out.sop2("S_CSELECT_B32", t1, sgpr(t0), sgpr(t1)); + self.out.sopc("S_CMP_LG_U32", sgpr(e + 1), int(0)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else if let Some((half, k)) = fixed(lane) { + self.out.vop3("V_READLANE_B32", u32::from(dst), vgpr(reg + half * n), int(k)); + } else if lane < 128 { + let l = scalar(lane as u8, &x); + self.save(live); + self.out.sop2("S_AND_B32", t2, sgpr(l), int(31)); + self.out.vop3("V_READLANE_B32", u32::from(t0), vgpr(reg), sgpr(t2)); + self.out.vop3("V_READLANE_B32", u32::from(t1), vgpr(reg + n), sgpr(t2)); + self.out.sopc("S_BITCMP1_B32", sgpr(l), int(5)); + self.out.sop2("S_CSELECT_B32", dst, sgpr(t1), sgpr(t0)); + self.restore(live); + } else { + return Err("a lane read of a lane given otherwise"); + } + } + } + Ok(()) + } + + /// A scalar instruction (the console's EXEC renamed to E). + fn scalar_inst(&mut self, d: &Decoded, live: bool, flow: Flow) -> Result<(), Why> { + let name = d.inst.name; + let x = self.x; + let e = x.e; + let [t0, t1, t2] = x.t; + let next = d.pc + d.len as u64; + match (d.enc.name, flow) { + ("ENC_SOPP", Flow::Jump(t)) => return self.jump("S_BRANCH", t, d.pc, live), + ("ENC_SOPP", Flow::Branch(t)) => { + let (lo, hi) = match name { + "S_CBRANCH_SCC0" | "S_CBRANCH_SCC1" => return self.jump(name, t, d.pc, live), + "S_CBRANCH_EXECZ" | "S_CBRANCH_EXECNZ" => (e, e + 1), + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => (VCC_LO, VCC_HI), + _ => return Err("a debug branch"), + }; + let (zb, nzb) = ("S_CBRANCH_EXECZ", "S_CBRANCH_EXECNZ"); + let on_zero = if name.ends_with("NZ") { nzb } else { zb }; + if !live { + self.out.sop2("S_OR_B32", EXEC_LO, sgpr(lo), sgpr(hi)); + return self.jump(on_zero, t, d.pc, live); + } + // SCC stays the console's: one dword at a time + self.out.mov(EXEC_LO, lo); + if on_zero == zb { + self.out.branch(nzb, next, d.pc); + } else { + self.jump(nzb, t, d.pc, live)?; + } + self.out.mov(EXEC_LO, hi); + return self.jump(on_zero, t, d.pc, live); + } + ("ENC_SOPP", _) => { + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SMEM", _) => { + let (r, w) = rdna2::sgpr_uses(d); + if r.iter().chain(&w).any(|&c| matches!(c as u8, EXEC_LO | EXEC_HI)) { + return Err("EXEC as a scalar memory operand"); + } + self.out.words.extend(&d.words); + return Ok(()); + } + ("ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK", _) => {} + _ => return Err("an unexpected scalar encoding"), + } + let f = |name: &str| field_value(d.enc, &d.words, name).unwrap_or(0) as u32; + if name == "S_GETPC_B64" { + // the console's address, which its constant data is found from + let dst = scalar(f("SDST") as u8, &x); + let delta = next as i64 - 4 * (self.out.words.len() as i64 + 1); + self.out.sop1("S_GETPC_B64", dst, int(0)); + self.save(live); + self.out.sop2("S_ADD_U32", dst, sgpr(dst), Src::Lit(delta as u32)); + self.out.sop2("S_ADDC_U32", dst + 1, sgpr(dst + 1), int(if delta < 0 { -1 } else { 0 })); + self.restore(live); + return Ok(()); + } + if let Flow::Jump(t) = flow { + return self.jump("S_BRANCH", t, d.pc, live); + } + if name.starts_with("S_MOVREL") { + return Err("a relative register move"); + } + if name.ends_with("EXEC_B32") { + return Err("a wave32 EXEC operation in a wave64 program"); + } + if let Some(stem) = name.strip_suffix("_SAVEEXEC_B64").or_else(|| name.strip_suffix("_WREXEC_B64")) { + let (lo, hi) = match f("SSRC0") { + c @ 0..=127 if c as u8 == NULL => (sgpr(NULL), sgpr(NULL)), + c @ 0..=127 => (sgpr(scalar(c as u8, &x)), sgpr(scalar(c as u8, &x) + 1)), + c @ 128..=192 => (Src::Code(c as u16), int(0)), + c @ 193..=208 => (Src::Code(c as u16), int(-1)), + 255 => (Src::Lit(d.literal.unwrap_or(0)), int(0)), + _ => return Err("a float or special constant as a 64-bit scalar operand"), + }; + // (operation, whether EXEC is its first operand) + let (op, exec_first) = match stem { + "S_AND" => ("S_AND_B32", false), + "S_OR" => ("S_OR_B32", false), + "S_XOR" => ("S_XOR_B32", false), + "S_ANDN2" => ("S_ANDN2_B32", false), + "S_ORN2" => ("S_ORN2_B32", false), + "S_NAND" => ("S_NAND_B32", false), + "S_NOR" => ("S_NOR_B32", false), + "S_XNOR" => ("S_XNOR_B32", false), + "S_ANDN1" => ("S_ANDN2_B32", true), + "S_ORN1" => ("S_ORN2_B32", true), + _ => return Err("an EXEC operation the rewrite does not know"), + }; + for (k, (t, s)) in [(t0, lo), (t1, hi)].into_iter().enumerate() { + let ek = sgpr(e + k as u8); + if exec_first { + self.out.sop2(op, t, ek, s); + } else { + self.out.sop2(op, t, s, ek); + } + } + let dst = f("SDST") as u8; + let old = name.contains("SAVEEXEC"); + if old && dst != NULL { + self.out.mov(scalar(dst, &x), e); + self.out.mov(scalar(dst, &x) + 1, e + 1); + } + self.out.mov(e, t0); + self.out.mov(e + 1, t1); + if !old && dst != NULL { + self.out.mov(scalar(dst, &x), t0); + self.out.mov(scalar(dst, &x) + 1, t1); + } + if live { + self.out.sop2("S_OR_B32", t2, sgpr(t0), sgpr(t1)); + } + return Ok(()); + } + let mut w = d.words.clone(); + let mut rename = |shift: u32, bits: u32| -> Result<(), Why> { + let m = (1 << bits) - 1; + let c = w[0] >> shift & m; + let c = match c { + 251 | 252 | 254 if bits == 8 => return Err("vccz, execz or lds_direct as an operand"), + 0..=127 => u32::from(scalar(c as u8, &x)), + _ => c, + }; + w[0] = w[0] & !(m << shift) | c << shift; + Ok(()) + }; + if d.enc.name != "ENC_SOPC" { + rename(16, 7)?; + } + if d.enc.name != "ENC_SOPK" { + rename(0, 8)?; + } + if matches!(d.enc.name, "ENC_SOP2" | "ENC_SOPC") { + rename(8, 8)?; + } + self.out.words.extend(&w); + Ok(()) + } +} + +/// Seven scalar registers no instruction of the program names: two pairs, five single ones. +fn spare_sgprs(list: &[Decoded]) -> Result<([u8; 2], [u8; 5]), Why> { + let mut used = [false; 128]; + for d in list { + let (r, w) = rdna2::sgpr_uses(d); + for c in r.into_iter().chain(w) { + used[c as usize] = true; + } + } + let mut free = (0..=105u8).rev().filter(|&c| !used[usize::from(c)]); + let mut pairs = [0u8; 2]; + let mut rest = Vec::new(); + let mut k = 0; + while k < 2 || rest.len() < 5 { + let c = free.next().ok_or("no spare scalar registers")?; + if k < 2 && c % 2 == 1 && c > 0 && !used[usize::from(c - 1)] { + free.next(); + pairs[k] = c - 1; + k += 1; + } else { + rest.push(c); + } + } + Ok((pairs, [rest[0], rest[1], rest[2], rest[3], rest[4]])) +} + +/// The program's VGPR count: one past the highest it names. +fn vgprs(list: &[Decoded]) -> u32 { + list.iter() + .flat_map(|d| { + let (r, w) = rdna2::vgpr_uses(d); + let tfe = u64::from(field_value(d.enc, &d.words, "TFE") == Some(1)); ~~~~ --- Right. `vgprs` now adds the status dword for LWE as for TFE (`fold.rs` ~1050, `f1988c2e8`). Test: `an_image_load_with_lwe_counts_its_status_dword` (an `image_load` into v10 with LWE: N is 12; 11 before the fix).
Royalflamejlh commented 2026-12-02 21:55:39 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T21:55:39Z.


Thanks for both follow-ups (to 21:35). At f1988c2e8 (rebased on main 5ad98adbc), with bmjask's second round in it too:

  1. Split: we keep it one pull request for the reasons in its description; if the maintainer wants it split, we will split it along your outline.
  2. Taken. gpu_folded_wave64_matches_the_console_wave now also runs each program's split form on the same GPU and requires the folded output to equal it, besides the interpreter's values.
  3. Left as is: it costs a fold only with the switch on, and the split form there is what main runs.
  4. The first commit's message describes that commit, where the form was still on by default and the limit was 128 VGPRs; the opt-in and the 255-register limit come in the commits that make them, whose messages say so. Its message now also lists the review fixes. The description now says seven programs, and Not tested no longer lists Windows; the smoke runs are without XCL_WAVE64_FOLD, which it now says. The suite and smoke at f1988c2e8 on the RTX 2070 SUPER PC are running; their counts go into the description.

AI use: Claude Code (Claude Opus 5.5) wrote the fixes, the tests and the replies in this round.

<!-- greyfinch-sync:ivall/xcl:comment:7359980324 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7359980324). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T21:55:39Z. --- Thanks for both follow-ups (to 21:35). At `f1988c2e8` (rebased on `main` 5ad98adbc), with bmjask's second round in it too: 1. Split: we keep it one pull request for the reasons in its description; if the maintainer wants it split, we will split it along your outline. 2. Taken. `gpu_folded_wave64_matches_the_console_wave` now also runs each program's split form on the same GPU and requires the folded output to equal it, besides the interpreter's values. 3. Left as is: it costs a fold only with the switch on, and the split form there is what `main` runs. 4. The first commit's message describes that commit, where the form was still on by default and the limit was 128 VGPRs; the opt-in and the 255-register limit come in the commits that make them, whose messages say so. Its message now also lists the review fixes. The description now says seven programs, and **Not tested** no longer lists Windows; the smoke runs are without `XCL_WAVE64_FOLD`, which it now says. The suite and smoke at `f1988c2e8` on the RTX 2070 SUPER PC are running; their counts go into the description. **AI use**: Claude Code (Claude Opus 5.5) wrote the fixes, the tests and the replies in this round.
bmjask commented 2026-12-02 21:56:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T21:56:21Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 428

@@ -0,0 +1,1187 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+    /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets
+    pub upper_tid: Vec<u64>,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    lw.lane_plus_32 = t.upper_tid.clone();
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+    /// a buffer access whose address can count the lane (ADD_TID)
+    tid: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,

High: For DPP16, the upper-half copy renames only src0 to its twin and keeps the console's ROW_MASK (bits 28..31) unchanged, but the translator derives the row from the host lane (lane >> 4, rows 0..1), so the upper copy applies the mask bits meant for console rows 0..1 instead of rows 2..3 (row_mask >> 2). For a wave64 v_mov_b32_dpp v1, v0 row_shr:1 row_mask:0xc (update only lanes 32..63), the lower copy is correctly off, but the upper copy reads bits 0..1 of 0xc, which are 0, so lanes 32..63 never get the update. With row_mask 0x3 it goes the other way, and the upper copy writes rows that should stay unchanged. Any mask where (rm & 3) != (rm >> 2) gives silently wrong results. Shifting the mask for the upper copy (and the bank mask if needed) would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776647555 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776647555). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T21:56:21Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 428 ~~~~diff @@ -0,0 +1,1187 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, + /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets + pub upper_tid: Vec<u64>, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + lw.lane_plus_32 = t.upper_tid.clone(); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, + /// a buffer access whose address can count the lane (ADD_TID) + tid: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, ~~~~ --- **High**: For DPP16, the upper-half copy renames only src0 to its twin and keeps the console's ROW_MASK (bits 28..31) unchanged, but the translator derives the row from the host lane (lane >> 4, rows 0..1), so the upper copy applies the mask bits meant for console rows 0..1 instead of rows 2..3 (`row_mask >> 2`). For a wave64 `v_mov_b32_dpp v1, v0 row_shr:1 row_mask:0xc` (update only lanes 32..63), the lower copy is correctly off, but the upper copy reads bits 0..1 of 0xc, which are 0, so lanes 32..63 never get the update. With row_mask 0x3 it goes the other way, and the upper copy writes rows that should stay unchanged. Any mask where (rm & 3) != (rm >> 2) gives silently wrong results. Shifting the mask for the upper copy (and the bank mask if needed) would fix it.
bmjask commented 2026-12-02 21:56:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T21:56:21Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 413

@@ -0,0 +1,1187 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+    /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets
+    pub upper_tid: Vec<u64>,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    lw.lane_plus_32 = t.upper_tid.clone();
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+    /// a buffer access whose address can count the lane (ADD_TID)
+    tid: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {

High: An SDWA VOPC with an explicit SD destination of EXEC_LO doesn't set t.exec, unlike the VOP3 v_cmp path (line 460), so the compare writes the host EXEC_LO but the result is never copied back into E. For v_cmp_gt_u32_sdwa exec, v0, v1, both the A and B copies write the host EXEC_LO, no mov e, EXEC_LO / mov e+1, EXEC_LO follows, and the next run reloads EXEC_LO from the stale E. The EXEC update is lost and lanes the console turned off keep running. Treating an SDWA SD of EXEC like the VOP3 case would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4776647565 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776647565). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T21:56:21Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 413 ~~~~diff @@ -0,0 +1,1187 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, + /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets + pub upper_tid: Vec<u64>, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + lw.lane_plus_32 = t.upper_tid.clone(); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, + /// a buffer access whose address can count the lane (ADD_TID) + tid: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { ~~~~ --- **High**: An SDWA VOPC with an explicit SD destination of EXEC_LO doesn't set `t.exec`, unlike the VOP3 v_cmp path (line 460), so the compare writes the host EXEC_LO but the result is never copied back into E. For `v_cmp_gt_u32_sdwa exec, v0, v1`, both the A and B copies write the host EXEC_LO, no `mov e, EXEC_LO` / `mov e+1, EXEC_LO` follows, and the next run reloads EXEC_LO from the stale E. The EXEC update is lost and lanes the console turned off keep running. Treating an SDWA SD of EXEC like the VOP3 case would fix it.
bmjask commented 2026-12-02 21:56:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T21:56:21Z.

Review: COMMENTED


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

Re-review at f1988c2e. From the ee2c186e review, the SDWA spare-SGPR, S_SUBVECTOR_LOOP and MIMG LWE items weren't flagged again. ADD_TID addresses now use tid_lane(), but window selection still uses the host lane (third item). The first two items are new.

  1. High crates/xcl/src/gpu/dxil/fold.rs:428: For DPP16, the upper-half copy renames only src0 to its twin and keeps the console's ROW_MASK (bits 28..31) unchanged, but the translator derives the row from the host lane (lane >> 4, rows 0..1), so the upper copy applies the mask bits .... (inline)
  2. High crates/xcl/src/gpu/dxil/fold.rs:413: An SDWA VOPC with an explicit SD destination of EXEC_LO doesn't set t.exec, unlike the VOP3 v_cmp path (line 460), so the compare writes the host EXEC_LO but the result is never copied back into E. (inline)
  3. Medium crates/xcl/src/gpu/dxil/lower_window.rs:293: see below.

On lines outside the diff:

  1. Medium crates/xcl/src/gpu/dxil/lower_window.rs:293: addtid_window still picks the memory window of a global_*_addtid access from self.lane, while the address computed right after it (lower_mem.rs:2156) now uses tid_lane(), so a folded upper copy selects its window from lane t while it accesses lane t + 32. When the SADDR base sits within 128 bytes below a 4 GiB window boundary, the upper copy's address (base + 4*(t+32)) is in the next window but window_at was given base + 4*t, so lanes 32..63 go through the wrong window (wrong data or an out-of-window guard). Using tid_lane() here too would keep them consistent.

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.

<!-- greyfinch-sync:ivall/xcl:review:6159732178 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#pullrequestreview-6159732178). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T21:56:21Z. **Review:** COMMENTED --- Review of `f1988c2e`: 3 finding(s) (2 high, 1 medium), most severe first. Re-review at `f1988c2e`. From the `ee2c186e` review, the SDWA spare-SGPR, S_SUBVECTOR_LOOP and MIMG LWE items weren't flagged again. ADD_TID addresses now use `tid_lane()`, but window selection still uses the host lane (third item). The first two items are new. 1. **High** `crates/xcl/src/gpu/dxil/fold.rs:428`: For DPP16, the upper-half copy renames only src0 to its twin and keeps the console's ROW_MASK (bits 28..31) unchanged, but the translator derives the row from the host lane (lane >> 4, rows 0..1), so the upper copy applies the mask bits .... (inline) 2. **High** `crates/xcl/src/gpu/dxil/fold.rs:413`: An SDWA VOPC with an explicit SD destination of EXEC_LO doesn't set `t.exec`, unlike the VOP3 v_cmp path (line 460), so the compare writes the host EXEC_LO but the result is never copied back into E. (inline) 3. **Medium** `crates/xcl/src/gpu/dxil/lower_window.rs:293`: see below. **On lines outside the diff:** 3. **Medium** `crates/xcl/src/gpu/dxil/lower_window.rs:293`: `addtid_window` still picks the memory window of a `global_*_addtid` access from `self.lane`, while the address computed right after it (lower_mem.rs:2156) now uses `tid_lane()`, so a folded upper copy selects its window from lane t while it accesses lane t + 32. When the SADDR base sits within 128 bytes below a 4 GiB window boundary, the upper copy's address (base + 4*(t+32)) is in the next window but `window_at` was given base + 4*t, so lanes 32..63 go through the wrong window (wrong data or an out-of-window guard). Using `tid_lane()` here too would keep them consistent. --- _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._
Royalflamejlh commented 2026-12-02 22:17:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:17:05Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 428

@@ -0,0 +1,1187 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+    /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets
+    pub upper_tid: Vec<u64>,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    lw.lane_plus_32 = t.upper_tid.clone();
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+    /// a buffer access whose address can count the lane (ADD_TID)
+    tid: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {
+                            let sd = (ext >> 8 & 0x7F) as u8;
+                            if sd != NULL {
+                                side.writes.push(mask_console(sd, half));
+                            }
+                            ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8;
+                        } else {
+                            side.writes.push(mask_console(VCC_LO, half));
+                            if half == Half::B {
+                                ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8);
+                            }
+                        }
+                    }
+                    w[1] = ext;
+                }
+                0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?,

Right. In daf3c1be7 the upper copy of a DPP16 instruction takes the console's row mask bits 2..3 as its bits 0..1 (valu_copy); the bank mask is per row, so it stays. Test: a_dpp16_row_mask_names_the_console_rows_in_each_copy (v_mov_b32_dpp v1, v0 row_shr:1 row_mask:0xc: the copies get 0xc and 0x3; 0xc twice before the fix).

<!-- greyfinch-sync:ivall/xcl:review-comment:4776880858 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776880858). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:17:05Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 428 ~~~~diff @@ -0,0 +1,1187 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, + /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets + pub upper_tid: Vec<u64>, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + lw.lane_plus_32 = t.upper_tid.clone(); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, + /// a buffer access whose address can count the lane (ADD_TID) + tid: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { + let sd = (ext >> 8 & 0x7F) as u8; + if sd != NULL { + side.writes.push(mask_console(sd, half)); + } + ext = ext & !(0x7F << 8) | u32::from(mask(sd, half, x)) << 8; + } else { + side.writes.push(mask_console(VCC_LO, half)); + if half == Half::B { + ext = ext & !(0xFF << 8) | (1 << 15 | u32::from(VCC_HI) << 8); + } + } + } + w[1] = ext; + } + 0xFA | 0xE9 | 0xEA => w[1] = w[1] & !0xFF | twin(w[1] & 0xFF, half, x)?, ~~~~ --- Right. In `daf3c1be7` the upper copy of a DPP16 instruction takes the console's row mask bits 2..3 as its bits 0..1 (`valu_copy`); the bank mask is per row, so it stays. Test: `a_dpp16_row_mask_names_the_console_rows_in_each_copy` (`v_mov_b32_dpp v1, v0 row_shr:1 row_mask:0xc`: the copies get 0xc and 0x3; 0xc twice before the fix).
Royalflamejlh commented 2026-12-02 22:17:07 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:17:07Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 413

@@ -0,0 +1,1187 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+    /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets
+    pub upper_tid: Vec<u64>,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    lw.lane_plus_32 = t.upper_tid.clone();
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {
+        let mut lit = None;
+        let f: Vec<(&str, u64)> = fields
+            .iter()
+            .map(|&(n, s)| match s {
+                Src::Code(c) => (n, u64::from(c)),
+                Src::Lit(l) => {
+                    lit = Some(l);
+                    (n, 255)
+                }
+            })
+            .collect();
+        let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}"));
+        self.words.extend(words(&b));
+    }
+
+    fn sop1(&mut self, name: &str, d: u8, s: Src) {
+        self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]);
+    }
+
+    fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) {
+        self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopc(&mut self, name: &str, a: Src, b: Src) {
+        self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]);
+    }
+
+    fn sopp(&mut self, name: &str, imm: u16) {
+        self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]);
+    }
+
+    fn mov(&mut self, d: u8, s: u8) {
+        self.sop1("S_MOV_B32", d, sgpr(s));
+    }
+
+    fn branch(&mut self, name: &str, to: u64, origin: u64) {
+        self.branches.push((self.words.len(), to, origin));
+        self.sopp(name, 0);
+    }
+
+    /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`).
+    fn far_jump(&mut self, p: u8, to: u64) {
+        self.far.push((self.words.len(), to));
+        self.sop1("S_GETPC_B64", p, int(0));
+        self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0));
+        self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0));
+        self.sop1("S_SETPC_B64", 0, sgpr(p));
+    }
+
+    fn vop1(&mut self, name: &str, d: u32, s: Src) {
+        self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]);
+    }
+
+    fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) {
+        self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]);
+    }
+}
+
+/// What one copy of a vector instruction reads and writes of the console's scalar registers
+/// (by console register code), for ordering the copies.
+#[derive(Debug, Default, Clone)]
+struct Side {
+    words: Vec<u32>,
+    reads: Vec<u8>,
+    writes: Vec<u8>,
+}
+
+/// A vector instruction's two copies.
+#[derive(Debug, Default, Clone)]
+struct Twin {
+    a: Side,
+    b: Side,
+    /// writes EXEC: the last of its run
+    exec: bool,
+    /// its upper copy is [`Half::BSwap`]'s
+    vcc: bool,
+    /// a run of its own: it writes memory, or swaps VCC
+    store: bool,
+    /// a run of its own whose upper copy goes first: the lower copy writes a scalar the
+    /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`)
+    upper_first: bool,
+    /// a buffer access whose address can count the lane (ADD_TID)
+    tid: bool,
+}
+
+fn meets(a: &[u8], b: &[u8]) -> bool {
+    a.iter().any(|r| b.contains(r))
+}
+
+impl Twin {
+    fn ordered(mut self) -> Result<Self, Why> {
+        if meets(&self.a.writes, &self.b.reads) {
+            if meets(&self.b.writes, &self.a.reads) {
+                return Err("a vector instruction whose halves each write what the other reads");
+            }
+            self.upper_first = true;
+        }
+        Ok(self)
+    }
+}
+
+/// Spare registers of the rewrite.
+#[derive(Debug, Clone, Copy)]
+struct Spare {
+    /// VGPR offset of the twins
+    n: u32,
+    /// the console's EXEC (low dword; the high one follows)
+    e: u8,
+    /// SCC kept across a rewrite that changes it
+    save: u8,
+    /// VCC's dwords trading places
+    swap: u8,
+    t: [u8; 3],
+    /// a pair for far jumps
+    jp: u8,
+}
+
+/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`.
+fn data(c: u8, half: Half, x: &Spare) -> u8 {
+    match (half, c) {
+        (Half::A, EXEC_HI) => x.e + 1,
+        (Half::B | Half::BSwap, EXEC_LO) => x.e,
+        (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO,
+        (Half::BSwap, VCC_LO) => VCC_HI,
+        (Half::BSwap, VCC_HI) => VCC_LO,
+        _ => c,
+    }
+}
+
+/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes.
+fn mask(c: u8, half: Half, x: &Spare) -> u8 {
+    match half {
+        _ if c == NULL => NULL,
+        Half::A => data(c, half, x),
+        Half::B | Half::BSwap => data(c + 1, half, x),
+    }
+}
+
+/// The console code of the mask dword a copy for `half` uses (for ordering).
+fn mask_console(c: u8, half: Half) -> u8 {
+    match half {
+        Half::A => c,
+        Half::B | Half::BSwap => c + 1,
+    }
+}
+
+/// A scalar operand code between runs of vector instructions: the console's EXEC is E.
+fn scalar(c: u8, x: &Spare) -> u8 {
+    match c {
+        EXEC_LO => x.e,
+        EXEC_HI => x.e + 1,
+        _ => c,
+    }
+}
+
+fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> {
+    match half {
+        Half::A => Ok(v),
+        _ if v < x.n => Ok(v + x.n),
+        _ => Err("a VGPR past the program's count"),
+    }
+}
+
+/// A 9-bit source field of a vector instruction's copy; `dwords` of data.
+fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c == NULL {
+                return Ok(code);
+            }
+            if dwords == 1 {
+                side.reads.push(c);
+                return Ok(u32::from(data(c, half, x)));
+            }
+            side.reads.extend((0..dwords).map(|i| c + i));
+            match c {
+                EXEC_LO => Ok(u32::from(x.e)),
+                VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"),
+                _ => Ok(code),
+            }
+        }
+        251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"),
+        253 => {
+            side.reads.push(SCC);
+            Ok(code)
+        }
+        128..=255 => Ok(code),
+        _ => Ok(256 + twin(code - 256, half, x)?),
+    }
+}
+
+/// A mask source field (carry-in, `v_cndmask_b32`'s selector).
+fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> {
+    let upper = half != Half::A;
+    match code {
+        0..=127 => {
+            let c = code as u8;
+            if c != NULL {
+                side.reads.push(mask_console(c, half));
+            }
+            Ok(u32::from(mask(c, half, x)))
+        }
+        // an inline integer sign-extends to 64 bits, a literal zero-extends
+        128 => Ok(code),
+        129..=192 | 255 if upper => Ok(128),
+        129..=192 | 255 => Ok(code),
+        193..=208 if upper => Ok(193),
+        193..=208 => Ok(code),
+        _ => Err("a float or special constant as a lane mask"),
+    }
+}
+
+fn dwords(d: &Decoded, field: &str) -> u8 {
+    d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8)
+}
+
+fn has(d: &Decoded, field: &str) -> bool {
+    d.ienc.operands.iter().any(|o| o.field == Some(field))
+}
+
+/// The copy of VALU instruction `d` for `half`.
+fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> {
+    let name = d.inst.name;
+    let mut side = Side::default();
+    let mut w = d.words.clone();
+    let co_ci = name.ends_with("_CO_CI_U32");
+    let carry_in = co_ci || name == "V_CNDMASK_B32";
+    let cmpx = name.starts_with("V_CMPX");
+    let vopc = d.enc.name == "ENC_VOPC";
+    match d.enc.name {
+        "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => {
+            let src0 = w[0] & 0x1FF;
+            let mut vsrc1_sgpr = false;
+            match src0 {
+                0xF9 => {
+                    let mut ext = w[1];
+                    let c0 = ext & 0xFF;
+                    let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? };
+                    ext = ext & !0xFF | c0;
+                    vsrc1_sgpr = ext >> 31 & 1 == 1;
+                    if vopc && cmpx {
+                        if ext >> 15 & 1 == 1 {
+                            return Err("an SDWA v_cmpx with a scalar destination");
+                        }
+                        t.exec = true;
+                    } else if vopc {
+                        if ext >> 15 & 1 == 1 {

Right. An SDWA compare with SD = EXEC now sets t.exec as the VOP3 form does, so each copy's result goes back into E (daf3c1be7). Test: an_sdwa_compare_into_exec_keeps_the_console_exec (v_cmp_gt_u32_sdwa exec, v0, v1: s_mov_b32 E.hi, exec_lo after the upper copy; missing before the fix).

<!-- greyfinch-sync:ivall/xcl:review-comment:4776881225 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4776881225). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:17:07Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 413 ~~~~diff @@ -0,0 +1,1187 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, + /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets + pub upper_tid: Vec<u64>, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + lw.lane_plus_32 = t.upper_tid.clone(); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { + let mut lit = None; + let f: Vec<(&str, u64)> = fields + .iter() + .map(|&(n, s)| match s { + Src::Code(c) => (n, u64::from(c)), + Src::Lit(l) => { + lit = Some(l); + (n, 255) + } + }) + .collect(); + let b = rdna2::encode(name, enc, &f, lit).unwrap_or_else(|e| panic!("{name}: {e}")); + self.words.extend(words(&b)); + } + + fn sop1(&mut self, name: &str, d: u8, s: Src) { + self.put(name, "ENC_SOP1", &[("SDST", sgpr(d)), ("SSRC0", s)]); + } + + fn sop2(&mut self, name: &str, d: u8, a: Src, b: Src) { + self.put(name, "ENC_SOP2", &[("SDST", sgpr(d)), ("SSRC0", a), ("SSRC1", b)]); + } + + fn sopc(&mut self, name: &str, a: Src, b: Src) { + self.put(name, "ENC_SOPC", &[("SSRC0", a), ("SSRC1", b)]); + } + + fn sopp(&mut self, name: &str, imm: u16) { + self.put(name, "ENC_SOPP", &[("SIMM16", Src::Code(imm))]); + } + + fn mov(&mut self, d: u8, s: u8) { + self.sop1("S_MOV_B32", d, sgpr(s)); + } + + fn branch(&mut self, name: &str, to: u64, origin: u64) { + self.branches.push((self.words.len(), to, origin)); + self.sopp(name, 0); + } + + /// The compiler's far jump through `p`, `p + 1` (five words, `rdna2::resolve_far_jumps`). + fn far_jump(&mut self, p: u8, to: u64) { + self.far.push((self.words.len(), to)); + self.sop1("S_GETPC_B64", p, int(0)); + self.sop2("S_ADD_U32", p, sgpr(p), Src::Lit(0)); + self.sop2("S_ADDC_U32", p + 1, sgpr(p + 1), int(0)); + self.sop1("S_SETPC_B64", 0, sgpr(p)); + } + + fn vop1(&mut self, name: &str, d: u32, s: Src) { + self.put(name, "ENC_VOP1", &[("VDST", Src::Code(d as u16)), ("SRC0", s)]); + } + + fn vop3(&mut self, name: &str, d: u32, a: Src, b: Src) { + self.put(name, "ENC_VOP3", &[("VDST", Src::Code(d as u16)), ("SRC0", a), ("SRC1", b)]); + } +} + +/// What one copy of a vector instruction reads and writes of the console's scalar registers +/// (by console register code), for ordering the copies. +#[derive(Debug, Default, Clone)] +struct Side { + words: Vec<u32>, + reads: Vec<u8>, + writes: Vec<u8>, +} + +/// A vector instruction's two copies. +#[derive(Debug, Default, Clone)] +struct Twin { + a: Side, + b: Side, + /// writes EXEC: the last of its run + exec: bool, + /// its upper copy is [`Half::BSwap`]'s + vcc: bool, + /// a run of its own: it writes memory, or swaps VCC + store: bool, + /// a run of its own whose upper copy goes first: the lower copy writes a scalar the + /// upper one reads (`v_cmp_eq_i32 s[0:1], s0, v0`) + upper_first: bool, + /// a buffer access whose address can count the lane (ADD_TID) + tid: bool, +} + +fn meets(a: &[u8], b: &[u8]) -> bool { + a.iter().any(|r| b.contains(r)) +} + +impl Twin { + fn ordered(mut self) -> Result<Self, Why> { + if meets(&self.a.writes, &self.b.reads) { + if meets(&self.b.writes, &self.a.reads) { + return Err("a vector instruction whose halves each write what the other reads"); + } + self.upper_first = true; + } + Ok(self) + } +} + +/// Spare registers of the rewrite. +#[derive(Debug, Clone, Copy)] +struct Spare { + /// VGPR offset of the twins + n: u32, + /// the console's EXEC (low dword; the high one follows) + e: u8, + /// SCC kept across a rewrite that changes it + save: u8, + /// VCC's dwords trading places + swap: u8, + t: [u8; 3], + /// a pair for far jumps + jp: u8, +} + +/// The console's 1-dword scalar operand `c` in a vector instruction's copy for `half`. +fn data(c: u8, half: Half, x: &Spare) -> u8 { + match (half, c) { + (Half::A, EXEC_HI) => x.e + 1, + (Half::B | Half::BSwap, EXEC_LO) => x.e, + (Half::B | Half::BSwap, EXEC_HI) => EXEC_LO, + (Half::BSwap, VCC_LO) => VCC_HI, + (Half::BSwap, VCC_HI) => VCC_LO, + _ => c, + } +} + +/// The dword of the console's lane mask at `c` that the copy for `half` reads or writes. +fn mask(c: u8, half: Half, x: &Spare) -> u8 { + match half { + _ if c == NULL => NULL, + Half::A => data(c, half, x), + Half::B | Half::BSwap => data(c + 1, half, x), + } +} + +/// The console code of the mask dword a copy for `half` uses (for ordering). +fn mask_console(c: u8, half: Half) -> u8 { + match half { + Half::A => c, + Half::B | Half::BSwap => c + 1, + } +} + +/// A scalar operand code between runs of vector instructions: the console's EXEC is E. +fn scalar(c: u8, x: &Spare) -> u8 { + match c { + EXEC_LO => x.e, + EXEC_HI => x.e + 1, + _ => c, + } +} + +fn twin(v: u32, half: Half, x: &Spare) -> Result<u32, Why> { + match half { + Half::A => Ok(v), + _ if v < x.n => Ok(v + x.n), + _ => Err("a VGPR past the program's count"), + } +} + +/// A 9-bit source field of a vector instruction's copy; `dwords` of data. +fn source9(code: u32, dwords: u8, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + match code { + 0..=127 => { + let c = code as u8; + if c == NULL { + return Ok(code); + } + if dwords == 1 { + side.reads.push(c); + return Ok(u32::from(data(c, half, x))); + } + side.reads.extend((0..dwords).map(|i| c + i)); + match c { + EXEC_LO => Ok(u32::from(x.e)), + VCC_LO if half == Half::BSwap => Err("VCC as 64-bit data of a vector instruction"), + _ => Ok(code), + } + } + 251 | 252 | 254 => Err("vccz, execz or lds_direct as an operand"), + 253 => { + side.reads.push(SCC); + Ok(code) + } + 128..=255 => Ok(code), + _ => Ok(256 + twin(code - 256, half, x)?), + } +} + +/// A mask source field (carry-in, `v_cndmask_b32`'s selector). +fn mask9(code: u32, half: Half, x: &Spare, side: &mut Side) -> Result<u32, Why> { + let upper = half != Half::A; + match code { + 0..=127 => { + let c = code as u8; + if c != NULL { + side.reads.push(mask_console(c, half)); + } + Ok(u32::from(mask(c, half, x))) + } + // an inline integer sign-extends to 64 bits, a literal zero-extends + 128 => Ok(code), + 129..=192 | 255 if upper => Ok(128), + 129..=192 | 255 => Ok(code), + 193..=208 if upper => Ok(193), + 193..=208 => Ok(code), + _ => Err("a float or special constant as a lane mask"), + } +} + +fn dwords(d: &Decoded, field: &str) -> u8 { + d.ienc.operands.iter().find(|o| o.field == Some(field)).map_or(1, |o| o.size.div_ceil(32).max(1) as u8) +} + +fn has(d: &Decoded, field: &str) -> bool { + d.ienc.operands.iter().any(|o| o.field == Some(field)) +} + +/// The copy of VALU instruction `d` for `half`. +fn valu_copy(d: &Decoded, half: Half, x: &Spare, t: &mut Twin) -> Result<Side, Why> { + let name = d.inst.name; + let mut side = Side::default(); + let mut w = d.words.clone(); + let co_ci = name.ends_with("_CO_CI_U32"); + let carry_in = co_ci || name == "V_CNDMASK_B32"; + let cmpx = name.starts_with("V_CMPX"); + let vopc = d.enc.name == "ENC_VOPC"; + match d.enc.name { + "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC" => { + let src0 = w[0] & 0x1FF; + let mut vsrc1_sgpr = false; + match src0 { + 0xF9 => { + let mut ext = w[1]; + let c0 = ext & 0xFF; + let c0 = if ext >> 23 & 1 == 1 { source9(c0, dwords(d, "SRC0"), half, x, &mut side)? & 0xFF } else { twin(c0, half, x)? }; + ext = ext & !0xFF | c0; + vsrc1_sgpr = ext >> 31 & 1 == 1; + if vopc && cmpx { + if ext >> 15 & 1 == 1 { + return Err("an SDWA v_cmpx with a scalar destination"); + } + t.exec = true; + } else if vopc { + if ext >> 15 & 1 == 1 { ~~~~ --- Right. An SDWA compare with SD = EXEC now sets `t.exec` as the VOP3 form does, so each copy's result goes back into E (`daf3c1be7`). Test: `an_sdwa_compare_into_exec_keeps_the_console_exec` (`v_cmp_gt_u32_sdwa exec, v0, v1`: `s_mov_b32 E.hi, exec_lo` after the upper copy; missing before the fix).
Royalflamejlh commented 2026-12-02 22:17:09 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:17:09Z.


On bmjask's third point at f1988c2e (lower_window.rs ~293, outside the diff): right, addtid_window now picks the window from tid_lane() too, so a folded upper copy's window and address agree (daf3c1be7). No test of its own: it needs a SADDR base within 128 bytes below a 4 GiB window boundary, which the test runner's single window does not give; the GPU test gpu_folded_wave64_counts_the_console_lane_in_add_tid_accesses covers the address. The two inline points are answered in their threads.

AI use: Claude Code (Claude Opus 5.5) wrote the fixes, the tests and this reply.

<!-- greyfinch-sync:ivall/xcl:comment:7360482057 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7360482057). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:17:09Z. --- On bmjask's third point at `f1988c2e` (`lower_window.rs` ~293, outside the diff): right, `addtid_window` now picks the window from `tid_lane()` too, so a folded upper copy's window and address agree (`daf3c1be7`). No test of its own: it needs a SADDR base within 128 bytes below a 4 GiB window boundary, which the test runner's single window does not give; the GPU test `gpu_folded_wave64_counts_the_console_lane_in_add_tid_accesses` covers the address. The two inline points are answered in their threads. **AI use**: Claude Code (Claude Opus 5.5) wrote the fixes, the tests and this reply.
Foniass commented 2026-12-02 22:18:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T22:18:36Z.


Follow-up review of daf3c1be, since f1988c2e (code reading only, not a merge-check; PR description red) · 1 high, 1 nit

In short: This push fixes three more cases in the fold:

  • a DPP16 row mask in the upper copy now names console rows 2..3 as the 32-lane wave's rows 0..1;
  • an SDWA compare that writes EXEC is treated as an EXEC write, keeping the console's EXEC;
  • the global ADD_TID path in lower_mem.rs now uses tid_lane too.

Each has a test, and the code reads right. Commits 2, 3, 4 and 6 are unchanged. The size still blocks it.

High

  1. Please split it (still open). 2,198 changed lines, none generated. The stack suggested earlier still applies: the preparation, the rewrite of scalar code and vector runs, the lane instructions, turning it on behind XCL_WAVE64_FOLD=1, and the census.

Nit

  1. Compact-limit refusal (still open). kernel.rs ~492 refuses folding whenever the folded wanted_plan does not fit, even when the split form's tables do not fit either.
Checked and fine
  • DPP16 (src0 == 0xFA): the upper copy keeps bank mask and controls, clears row-mask bits 30..31 (rows a 32-lane wave does not have) and moves them to 28..29. a_dpp16_row_mask_names_the_console_rows_in_each_copy checks 0xC becomes 0xC / 0x3. DPP8 and the other encodings are unchanged.
  • SDWA VOPC with SD set and SDST EXEC_LO now sets t.exec, so the twin saves and restores EXEC like a VOP3 compare into EXEC. an_sdwa_compare_into_exec_keeps_the_console_exec checks the copies of exec_lo in the spare pair.
  • tid_lane is now pub(super) and used in lower_mem.rs, so a global ADD_TID access counts console lane t + 32 in the upper copy as well.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7360515140 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7360515140). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T22:18:36Z. --- **Follow-up review** of `daf3c1be`, since `f1988c2e` (code reading only, not a merge-check; `PR description` red) · 1 high, 1 nit **In short:** This push fixes three more cases in the fold: - a DPP16 row mask in the upper copy now names console rows 2..3 as the 32-lane wave's rows 0..1; - an SDWA compare that writes EXEC is treated as an EXEC write, keeping the console's EXEC; - the global ADD_TID path in `lower_mem.rs` now uses `tid_lane` too. Each has a test, and the code reads right. Commits 2, 3, 4 and 6 are unchanged. The size still blocks it. #### High 1. **Please split it (still open).** 2,198 changed lines, none generated. The stack suggested earlier still applies: the preparation, the rewrite of scalar code and vector runs, the lane instructions, turning it on behind `XCL_WAVE64_FOLD=1`, and the census. #### Nit 2. **Compact-limit refusal (still open).** `kernel.rs` ~492 refuses folding whenever the folded `wanted_plan` does not fit, even when the split form's tables do not fit either. <details><summary>Checked and fine</summary> - DPP16 (`src0 == 0xFA`): the upper copy keeps bank mask and controls, clears row-mask bits 30..31 (rows a 32-lane wave does not have) and moves them to 28..29. `a_dpp16_row_mask_names_the_console_rows_in_each_copy` checks `0xC` becomes `0xC` / `0x3`. DPP8 and the other encodings are unchanged. - SDWA VOPC with `SD` set and SDST `EXEC_LO` now sets `t.exec`, so the twin saves and restores EXEC like a VOP3 compare into EXEC. `an_sdwa_compare_into_exec_keeps_the_console_exec` checks the copies of `exec_lo` in the spare pair. - `tid_lane` is now `pub(super)` and used in `lower_mem.rs`, so a global ADD_TID access counts console lane t + 32 in the upper copy as well. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
Royalflamejlh commented 2026-12-02 22:26:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T22:26:36Z.


Thanks. The split and the compact-limit points stand as answered above: unchanged at daf3c1be7. Both PRs still merge cleanly with main 078358a05 and build there (cargo check --tests).

<!-- greyfinch-sync:ivall/xcl:comment:7360699297 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7360699297). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T22:26:36Z. --- Thanks. The split and the compact-limit points stand as answered above: unchanged at `daf3c1be7`. Both PRs still merge cleanly with `main` 078358a05 and build there (`cargo check --tests`).
bmjask commented 2026-12-02 22:47:54 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T22:47:54Z.

Review: COMMENTED


Review of daf3c1be: 2 finding(s) (2 medium), most severe first.

Re-review at daf3c1be. All three findings from the f1988c2e review look addressed: the DPP16 row mask, the SDWA compare writing EXEC, and the ADDTID window now using upper_tid. Two new items below, both behind XCL_WAVE64_FOLD=1.

  1. Medium crates/xcl/src/gpu/dxil/fold.rs:165: Asm::put panics on an encode error, and fold::fold runs on the caller's thread in translate_compute_rodata. (inline)
  2. Medium crates/xcl/src/gpu/dxil/kernel.rs:489: A folded program loses the compact form that branch-heavy split programs with a consumed atomic get, because automatic_plan is called with compute && split and split is false for the folded translation (the new guard at line 492 al.... (inline)

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.

<!-- greyfinch-sync:ivall/xcl:review:6160408660 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#pullrequestreview-6160408660). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T22:47:54Z. **Review:** COMMENTED --- Review of `daf3c1be`: 2 finding(s) (2 medium), most severe first. Re-review at `daf3c1be`. All three findings from the `f1988c2e` review look addressed: the DPP16 row mask, the SDWA compare writing EXEC, and the ADDTID window now using `upper_tid`. Two new items below, both behind XCL_WAVE64_FOLD=1. 1. **Medium** `crates/xcl/src/gpu/dxil/fold.rs:165`: `Asm::put` panics on an encode error, and `fold::fold` runs on the caller's thread in `translate_compute_rodata`. (inline) 2. **Medium** `crates/xcl/src/gpu/dxil/kernel.rs:489`: A folded program loses the compact form that branch-heavy split programs with a consumed atomic get, because `automatic_plan` is called with `compute && split` and `split` is false for the folded translation (the new guard at line 492 al.... (inline) --- _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._
bmjask commented 2026-12-02 22:47:55 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T22:47:55Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 165

@@ -0,0 +1,1195 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+    /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets
+    pub upper_tid: Vec<u64>,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    lw.lane_plus_32 = t.upper_tid.clone();
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {

Medium: Asm::put panics on an encode error, and fold::fold runs on the caller's thread in translate_compute_rodata. Only translate_entry_with turns translator panics into Err, so a panic in the rewrite skips the logged fallback to the split form. For any instruction/encoding pair rdna2::encode rejects ("X has no encoding Y") while rewriting a game shader, or an out-of-range index in the rewrite, the panic unwinds through pso::direct_compute into the PSO build instead of logging wave64 fold: ... the split form, so a shader the split form handles can take down the pipeline compile. Returning Result from Asm::put, or running fold() inside the translator thread's panic boundary, would keep the fallback.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777211845 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4777211845). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T22:47:55Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 165 ~~~~diff @@ -0,0 +1,1195 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, + /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets + pub upper_tid: Vec<u64>, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + lw.lane_plus_32 = t.upper_tid.clone(); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { ~~~~ --- **Medium**: `Asm::put` panics on an encode error, and `fold::fold` runs on the caller's thread in `translate_compute_rodata`. Only `translate_entry_with` turns translator panics into Err, so a panic in the rewrite skips the logged fallback to the split form. For any instruction/encoding pair `rdna2::encode` rejects ("X has no encoding Y") while rewriting a game shader, or an out-of-range index in the rewrite, the panic unwinds through `pso::direct_compute` into the PSO build instead of logging `wave64 fold: ... the split form`, so a shader the split form handles can take down the pipeline compile. Returning Result from `Asm::put`, or running `fold()` inside the translator thread's panic boundary, would keep the fallback.
bmjask commented 2026-12-02 22:47:55 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T22:47:55Z.

Code review location: crates/xcl/src/gpu/dxil/kernel.rs; line 489

@@ -468,6 +488,10 @@ fn translate_on_this_thread(
         Some(true) => super::compact::plan(&cfg, &lw),
         None => super::compact::automatic_plan(&cfg, &lw, compute && split),

Medium: A folded program loses the compact form that branch-heavy split programs with a consumed atomic get, because automatic_plan is called with compute && split and split is false for the folded translation (the new guard at line 492 also passes false, so it doesn't catch this). Take a wave64 compute program with 250 or more blocks, under 10 000 instructions, and a GLC BUFFER_ATOMIC_ADD whose result is used. Split, it gets a compact plan through atomic_candidate. Folded, the plan is None and split_compute won't cut it either (Op::AtomicRmw => return None), so it's emitted in full at twice the size, uncompacted: the huge-DXIL / driver-compile-hang case the compact path exists to avoid, with no fallback to the split form. Passing the original split-ness to automatic_plan (or refusing to fold when the split form would have had a plan) would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777211852 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4777211852). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T22:47:55Z. **Code review location:** `crates/xcl/src/gpu/dxil/kernel.rs`; line 489 ~~~~diff @@ -468,6 +488,10 @@ fn translate_on_this_thread( Some(true) => super::compact::plan(&cfg, &lw), None => super::compact::automatic_plan(&cfg, &lw, compute && split), ~~~~ --- **Medium**: A folded program loses the compact form that branch-heavy split programs with a consumed atomic get, because `automatic_plan` is called with `compute && split` and `split` is false for the folded translation (the new guard at line 492 also passes `false`, so it doesn't catch this). Take a wave64 compute program with 250 or more blocks, under 10 000 instructions, and a GLC BUFFER_ATOMIC_ADD whose result is used. Split, it gets a compact plan through `atomic_candidate`. Folded, the plan is None and `split_compute` won't cut it either (`Op::AtomicRmw => return None`), so it's emitted in full at twice the size, uncompacted: the huge-DXIL / driver-compile-hang case the compact path exists to avoid, with no fallback to the split form. Passing the original split-ness to `automatic_plan` (or refusing to fold when the split form would have had a plan) would fix it.
Royalflamejlh commented 2026-12-02 23:02:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:02:21Z.

Code review location: crates/xcl/src/gpu/dxil/fold.rs; line 165

@@ -0,0 +1,1195 @@
+//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane
+//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form").
+//!
+//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects,
+//! which the translator then takes as any other wave32 program:
+//!
+//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v
+//!   of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count).
+//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs
+//!   twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the
+//!   twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming
+//!   VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade
+//!   places around it.
+//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first
+//!   copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed.
+//! - Branches are the console's; a test of a 64-bit mask tests both dwords.
+//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane;
+//!   `v_mbcnt` counts the whole low dword for the upper half.
+//!
+//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the
+//! rewrite does not cover (the reasons `fold` returns) keeps the split form.
+//!
+//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit
+//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for
+//! XCL's decoder, register numbering and entry.
+
+use std::collections::{HashMap, HashSet};
+
+use super::kernel::{inside_limits, ComputeStart};
+use super::lower::Lw;
+use super::module::{BinOp, Pred, Value};
+use crate::gpu::rdna2::{self, field_value, Decoded, Variant};
+use crate::gpu::recomp::CsInterface;
+
+type Why = &'static str;
+
+const VCC_LO: u8 = 106;
+const VCC_HI: u8 = 107;
+const NULL: u8 = 125;
+const EXEC_LO: u8 = 126;
+const EXEC_HI: u8 = 127;
+/// SCC among the register codes of [`Side`] (no SGPR has this code).
+const SCC: u8 = 253;
+/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs.
+const HOST_REGISTERS: u32 = 255;
+
+/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves
+/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    return ON_IN_TEST.with(|c| c.get());
+    #[cfg(not(test))]
+    {
+        static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+        *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1"))
+    }
+}
+
+#[cfg(test)]
+thread_local! {
+    pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// A folded program's console side, for its entry.
+#[derive(Debug, Clone)]
+pub struct Twins {
+    /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t
+    pub base: u32,
+    pub cs: CsInterface,
+    /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets
+    pub upper_tid: Vec<u64>,
+}
+
+pub struct Folded {
+    pub code: Vec<u8>,
+    /// the host's group: one 32-lane wave for each console wave
+    pub cs: CsInterface,
+    pub twins: Twins,
+}
+
+/// The entry of a folded program, after `compute_init`: both console lanes' thread ids
+/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's
+/// first instructions move to E).
+pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) {
+    let [x, y, _] = t.cs.threads;
+    let total: u32 = t.cs.threads.iter().product();
+    let wave = lw.lshrc(tid, 5);
+    let base = lw.shlc(wave, 6);
+    lw.lane_plus_32 = t.upper_tid.clone();
+    let lane = lw.lane;
+    for half in 0..2u32 {
+        let l = lw.addc(lane, 32 * half);
+        let c = lw.add(base, l);
+        let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y));
+        let gx = lw.bin(BinOp::URem, c, kx);
+        let q = lw.bin(BinOp::UDiv, c, kx);
+        let gy = lw.bin(BinOp::URem, q, ky);
+        let gz = lw.bin(BinOp::UDiv, c, kxy);
+        let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]);
+        let there = lw.cmpc(Pred::ULt, c, total);
+        let on = lw.land(inside, there);
+        let word = lw.s.wave_ballot(on)[0];
+        let ci = lw.init.compute.as_mut().expect("the compute entry");
+        ci.sgpr.insert(u32::from(EXEC_LO) + half, word);
+        for (k, g) in [gx, gy, gz].into_iter().enumerate() {
+            if k == 0 || t.cs.tid_components as usize > k {
+                ci.vgpr.insert(half * t.base + k as u32, g);
+            }
+        }
+    }
+}
+
+/// Which console half a copy of a vector instruction runs for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Half {
+    /// lanes 0..31: the registers as they are
+    A,
+    /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC
+    B,
+    /// lanes 32..63 with VCC's dwords swapped around the copy
+    BSwap,
+}
+
+/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`].
+const NEEDS_SWAP: Why = "an implicit VCC only a swap names";
+
+/// A source operand to assemble: a 9-bit operand code or a literal.
+#[derive(Debug, Clone, Copy)]
+enum Src {
+    Code(u16),
+    Lit(u32),
+}
+
+fn sgpr(c: u8) -> Src {
+    Src::Code(u16::from(c))
+}
+
+fn vgpr(v: u32) -> Src {
+    Src::Code(256 + v as u16)
+}
+
+fn int(k: i32) -> Src {
+    match k {
+        0..=64 => Src::Code(128 + k as u16),
+        -16..=-1 => Src::Code((192 - k) as u16),
+        _ => Src::Lit(k as u32),
+    }
+}
+
+fn words(bytes: &[u8]) -> Vec<u32> {
+    bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
+}
+
+/// Machine code being written, with the branches still to resolve.
+#[derive(Default)]
+struct Asm {
+    words: Vec<u32>,
+    /// (word of a branch, the console pc it goes to, the console pc of its instruction)
+    branches: Vec<(usize, u64, u64)>,
+    /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to)
+    far: Vec<(usize, u64)>,
+}
+
+impl Asm {
+    fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) {

(Edited: at 2196dfd10 the SDST-255 compare below is refused by name in fold, and the panic test is replaced by that refusal in what_the_rewrite_does_not_cover_is_refused_with_its_reason. catch_unwind stays.)

Valid. In fbac76fdc translate_folded (kernel.rs:238) runs fold::fold inside catch_unwind, so a panic in the rewrite becomes the error "the rewrite panicked" and the logged fallback to the split form runs. Asm::put keeps its panic: the instruction names it encodes are XCL's own.

I could not make Asm::put fail from console code. Random instruction words did panic the rewrite elsewhere, though: a VOP3 compare whose SDST is 255 overflows c + 1 in mask_console (fold.rs:308) in a debug build. The new test a_panic_in_the_rewrite_is_an_error_the_split_form_takes_over_from uses that case. It fails without the change and passes with it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777359441 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4777359441). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:02:21Z. **Code review location:** `crates/xcl/src/gpu/dxil/fold.rs`; line 165 ~~~~diff @@ -0,0 +1,1195 @@ +//! Console wave64 compute programs on GPUs of 32-lane waves without halves: each host lane +//! runs two console lanes (`docs/wave64-on-wave32.md`, "The folded form"). +//! +//! [`fold`] rewrites a wave64 compute program into a wave32 program of the same effects, +//! which the translator then takes as any other wave32 program: +//! +//! - Host lane t of a host wave runs console lanes t and t + 32 of one console wave. VGPR v +//! of console lane t + 32 is VGPR v + N of host lane t (N: the program's VGPR count). +//! - The console's EXEC lives in a spare SGPR pair, E. Each run of vector instructions runs +//! twice: under EXEC = E.lo on the registers as they are, then under EXEC = E.hi on the +//! twins. The second copy of an instruction with an implicit VCC is its VOP3 form naming +//! VCC's upper dword; where there is none (DPP, SDWA, `v_div_fmas`) VCC's dwords trade +//! places around it. +//! - A lane mask stays a 64-bit value in its register pair: the low dword is the first +//! copy's ballot, the high dword the second's. Scalar code is the console's, EXEC renamed. +//! - Branches are the console's; a test of a 64-bit mask tests both dwords. +//! - `v_readlane`, `v_writelane` and `v_readfirstlane` go to the twin that holds the lane; +//! `v_mbcnt` counts the whole low dword for the upper half. +//! +//! The entry ([`init`]) gives both lanes their thread ids and E its two words. A program the +//! rewrite does not cover (the reasons `fold` returns) keeps the split form. +//! +//! Ported from VIctory-NVIDIA (https://github.com/trustno1-coder/VIctory-NVIDIA, commit +//! 5fabb46e, GPL-3.0-or-later), `crates/victory-shader/src/fold.rs`; changed 2026-11-30 for +//! XCL's decoder, register numbering and entry. + +use std::collections::{HashMap, HashSet}; + +use super::kernel::{inside_limits, ComputeStart}; +use super::lower::Lw; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::rdna2::{self, field_value, Decoded, Variant}; +use crate::gpu::recomp::CsInterface; + +type Why = &'static str; + +const VCC_LO: u8 = 106; +const VCC_HI: u8 = 107; +const NULL: u8 = 125; +const EXEC_LO: u8 = 126; +const EXEC_HI: u8 = 127; +/// SCC among the register codes of [`Side`] (no SGPR has this code). +const SCC: u8 = 253; +/// Registers a thread of an NVIDIA GPU has: a host lane holds both console lanes' VGPRs. +const HOST_REGISTERS: u32 = 255; + +/// Whether a wave64 compute program takes the folded form where the GPU has 32-lane waves +/// only: with `XCL_WAVE64_FOLD=1` (the translated cache keys on it). +pub fn enabled() -> bool { + #[cfg(test)] + return ON_IN_TEST.with(|c| c.get()); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_FOLD").is_ok_and(|v| v.trim() == "1")) + } +} + +#[cfg(test)] +thread_local! { + pub(super) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// A folded program's console side, for its entry. +#[derive(Debug, Clone)] +pub struct Twins { + /// VGPR v of console lane t + 32 is VGPR v + `base` of host lane t + pub base: u32, + pub cs: CsInterface, + /// the upper copies of buffer accesses whose lane counts (ADD_TID): byte offsets + pub upper_tid: Vec<u64>, +} + +pub struct Folded { + pub code: Vec<u8>, + /// the host's group: one 32-lane wave for each console wave + pub cs: CsInterface, + pub twins: Twins, +} + +/// The entry of a folded program, after `compute_init`: both console lanes' thread ids +/// (v0..v2 and their twins) and their EXEC words (in EXEC's two dwords, which the program's +/// first instructions move to E). +pub fn init(lw: &mut Lw, t: &Twins, st: &ComputeStart, tid: Value) { + let [x, y, _] = t.cs.threads; + let total: u32 = t.cs.threads.iter().product(); + let wave = lw.lshrc(tid, 5); + let base = lw.shlc(wave, 6); + lw.lane_plus_32 = t.upper_tid.clone(); + let lane = lw.lane; + for half in 0..2u32 { + let l = lw.addc(lane, 32 * half); + let c = lw.add(base, l); + let (kx, ky, kxy) = (lw.c(x), lw.c(y), lw.c(x * y)); + let gx = lw.bin(BinOp::URem, c, kx); + let q = lw.bin(BinOp::UDiv, c, kx); + let gy = lw.bin(BinOp::URem, q, ky); + let gz = lw.bin(BinOp::UDiv, c, kxy); + let inside = inside_limits(lw, t.cs.threads, st.groups, st.last, [gx, gy, gz]); + let there = lw.cmpc(Pred::ULt, c, total); + let on = lw.land(inside, there); + let word = lw.s.wave_ballot(on)[0]; + let ci = lw.init.compute.as_mut().expect("the compute entry"); + ci.sgpr.insert(u32::from(EXEC_LO) + half, word); + for (k, g) in [gx, gy, gz].into_iter().enumerate() { + if k == 0 || t.cs.tid_components as usize > k { + ci.vgpr.insert(half * t.base + k as u32, g); + } + } + } +} + +/// Which console half a copy of a vector instruction runs for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Half { + /// lanes 0..31: the registers as they are + A, + /// lanes 32..63: the twins, VCC's upper dword named where the console's instruction names VCC + B, + /// lanes 32..63 with VCC's dwords swapped around the copy + BSwap, +} + +/// What [`valu_copy`] stops with when the upper half needs [`Half::BSwap`]. +const NEEDS_SWAP: Why = "an implicit VCC only a swap names"; + +/// A source operand to assemble: a 9-bit operand code or a literal. +#[derive(Debug, Clone, Copy)] +enum Src { + Code(u16), + Lit(u32), +} + +fn sgpr(c: u8) -> Src { + Src::Code(u16::from(c)) +} + +fn vgpr(v: u32) -> Src { + Src::Code(256 + v as u16) +} + +fn int(k: i32) -> Src { + match k { + 0..=64 => Src::Code(128 + k as u16), + -16..=-1 => Src::Code((192 - k) as u16), + _ => Src::Lit(k as u32), + } +} + +fn words(bytes: &[u8]) -> Vec<u32> { + bytes.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect() +} + +/// Machine code being written, with the branches still to resolve. +#[derive(Default)] +struct Asm { + words: Vec<u32>, + /// (word of a branch, the console pc it goes to, the console pc of its instruction) + branches: Vec<(usize, u64, u64)>, + /// far jumps: (word of the `s_getpc_b64`, the console pc it goes to) + far: Vec<(usize, u64)>, +} + +impl Asm { + fn put(&mut self, name: &str, enc: &str, fields: &[(&str, Src)]) { ~~~~ --- (Edited: at `2196dfd10` the SDST-255 compare below is refused by name in `fold`, and the panic test is replaced by that refusal in `what_the_rewrite_does_not_cover_is_refused_with_its_reason`. `catch_unwind` stays.) Valid. In fbac76fdc `translate_folded` (kernel.rs:238) runs `fold::fold` inside `catch_unwind`, so a panic in the rewrite becomes the error "the rewrite panicked" and the logged fallback to the split form runs. `Asm::put` keeps its panic: the instruction names it encodes are XCL's own. I could not make `Asm::put` fail from console code. Random instruction words did panic the rewrite elsewhere, though: a VOP3 compare whose SDST is 255 overflows `c + 1` in `mask_console` (fold.rs:308) in a debug build. The new test `a_panic_in_the_rewrite_is_an_error_the_split_form_takes_over_from` uses that case. It fails without the change and passes with it.
Royalflamejlh commented 2026-12-02 23:02:23 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:02:23Z.

Code review location: crates/xcl/src/gpu/dxil/kernel.rs; line 489

@@ -468,6 +488,10 @@ fn translate_on_this_thread(
         Some(true) => super::compact::plan(&cfg, &lw),
         None => super::compact::automatic_plan(&cfg, &lw, compute && split),

Valid. In fbac76fdc the folded translation picks its compact plan as a split one does: automatic_plan(&cfg, &lw, compute && (split || fold.is_some())) (kernel.rs:489). The size guard below it now calls wanted_plan(.., true), so it measures the same plan.

New test: a_folded_program_with_a_returning_atomic_takes_the_compact_form (compact_tests.rs) folds a GLC BUFFER_ATOMIC_ADD followed by 100 and then 200 copies of the branchy block (about 300 blocks or more). Without the change, the 100 more copies cost 3,220 B of DXIL. With it they cost 252 B.

<!-- greyfinch-sync:ivall/xcl:review-comment:4777359784 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#discussion_r4777359784). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:02:23Z. **Code review location:** `crates/xcl/src/gpu/dxil/kernel.rs`; line 489 ~~~~diff @@ -468,6 +488,10 @@ fn translate_on_this_thread( Some(true) => super::compact::plan(&cfg, &lw), None => super::compact::automatic_plan(&cfg, &lw, compute && split), ~~~~ --- Valid. In fbac76fdc the folded translation picks its compact plan as a split one does: `automatic_plan(&cfg, &lw, compute && (split || fold.is_some()))` (kernel.rs:489). The size guard below it now calls `wanted_plan(.., true)`, so it measures the same plan. New test: `a_folded_program_with_a_returning_atomic_takes_the_compact_form` (compact_tests.rs) folds a GLC `BUFFER_ATOMIC_ADD` followed by 100 and then 200 copies of the branchy block (about 300 blocks or more). Without the change, the 100 more copies cost 3,220 B of DXIL. With it they cost 252 B.
Foniass commented 2026-12-02 23:03:53 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T23:03:53Z.


Follow-up review of fbac76fd, since daf3c1be (code reading only, not a merge-check) · 1 high, 1 nit

In short: This push makes two changes. A folded program is now chosen for the compact form the way a split one is: a branch-heavy program with a returning BUFFER_ATOMIC_ADD takes it in both forms. And a panic in the rewrite, which runs on the caller's thread, is now an error, so the split form takes over. Both have tests. Commits 1, 2, 3 and 5 are unchanged. The size still blocks it.

High

  1. Please split it (still open). 2,223 changed lines, none generated. The stack suggested earlier still applies: the preparation, the rewrite of scalar code and vector runs, the lane instructions, turning it on behind XCL_WAVE64_FOLD=1, and the census.

Nit

  1. The panic the new test catches is a rewrite bug, not a refusal. a_panic_in_the_rewrite_is_an_error_the_split_form_takes_over_from (fold_tests.rs) folds a VOP3 v_cmp_eq_u32 with VDST 255 and expects "the rewrite panicked". Catching the panic is a reasonable safety net, since catch_unwind works with the workspace's unwinding profile. But this known input should be refused by name in fold, and the test should expect that refusal. Otherwise the default panic hook still prints a backtrace for it, and a later bug that panics looks the same in the log.
Checked and fine
  • automatic_plan now gets compute && (split || fold.is_some()), and the refusal check uses wanted_plan(.., true), so a folded program is planned as a split one is. a_folded_program_with_a_returning_atomic_takes_the_compact_form checks that 100 more copies cost under a quarter of the DXIL of 100, and returns early when compact_mode is forced.
  • translate_folded wraps only fold::fold in catch_unwind, maps a panic to an error, and keeps fold's own refusals as they were (??). The closure borrows only code and cs, so no shared state is left half-written.
  • This also covers the earlier compact-limit nit: the refusal check now uses the plan the folded program would actually get.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7361517876 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7361517876). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T23:03:53Z. --- **Follow-up review** of `fbac76fd`, since `daf3c1be` (code reading only, not a merge-check) · 1 high, 1 nit **In short:** This push makes two changes. A folded program is now chosen for the compact form the way a split one is: a branch-heavy program with a returning `BUFFER_ATOMIC_ADD` takes it in both forms. And a panic in the rewrite, which runs on the caller's thread, is now an error, so the split form takes over. Both have tests. Commits 1, 2, 3 and 5 are unchanged. The size still blocks it. #### High 1. **Please split it (still open).** 2,223 changed lines, none generated. The stack suggested earlier still applies: the preparation, the rewrite of scalar code and vector runs, the lane instructions, turning it on behind `XCL_WAVE64_FOLD=1`, and the census. #### Nit 2. **The panic the new test catches is a rewrite bug, not a refusal.** `a_panic_in_the_rewrite_is_an_error_the_split_form_takes_over_from` (`fold_tests.rs`) folds a VOP3 `v_cmp_eq_u32` with `VDST` 255 and expects "the rewrite panicked". Catching the panic is a reasonable safety net, since `catch_unwind` works with the workspace's unwinding profile. But this known input should be refused by name in `fold`, and the test should expect that refusal. Otherwise the default panic hook still prints a backtrace for it, and a later bug that panics looks the same in the log. <details><summary>Checked and fine</summary> - `automatic_plan` now gets `compute && (split || fold.is_some())`, and the refusal check uses `wanted_plan(.., true)`, so a folded program is planned as a split one is. `a_folded_program_with_a_returning_atomic_takes_the_compact_form` checks that 100 more copies cost under a quarter of the DXIL of 100, and returns early when `compact_mode` is forced. - `translate_folded` wraps only `fold::fold` in `catch_unwind`, maps a panic to an error, and keeps `fold`'s own refusals as they were (`??`). The closure borrows only `code` and `cs`, so no shared state is left half-written. - This also covers the earlier compact-limit nit: the refusal check now uses the plan the folded program would actually get. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
Royalflamejlh commented 2026-12-02 23:16:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Royalflamejlh on 2026-12-02T23:16:48Z.


Thanks. At 2196dfd10:

  1. Split: no change. As answered before, we will split it if the maintainer asks for that.
  2. Nit: done. A VOP3 compare whose destination is above EXEC_HI is now refused in valu_copy (fold.rs:465) with "a compare into a constant". what_the_rewrite_does_not_cover_is_refused_with_its_reason expects that refusal; it fails without the check. The panic test is gone. catch_unwind in translate_folded stays as the safety net. After the check, 20 million random instruction words through fold raised no panic.

AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.

<!-- greyfinch-sync:ivall/xcl:comment:7361791292 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7361791292). Originally posted by [Royalflamejlh](https://github.com/Royalflamejlh) on 2026-12-02T23:16:48Z. --- Thanks. At `2196dfd10`: 1. Split: no change. As answered before, we will split it if the maintainer asks for that. 2. Nit: done. A VOP3 compare whose destination is above EXEC_HI is now refused in `valu_copy` (fold.rs:465) with "a compare into a constant". `what_the_rewrite_does_not_cover_is_refused_with_its_reason` expects that refusal; it fails without the check. The panic test is gone. `catch_unwind` in `translate_folded` stays as the safety net. After the check, 20 million random instruction words through `fold` raised no panic. AI use: Claude Code (Claude Opus 5.5) made the change and wrote this reply.
Foniass commented 2026-12-02 23:18:30 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T23:18:30Z.


Follow-up review of 2196dfd1, since fbac76fd (code reading only, not a merge-check) · 1 high

In short: This push fixes the nit from my last review. A VOP3 compare whose destination is a constant code (above EXEC_HI), which overflowed the mask arithmetic, is now refused by name ("a compare into a constant"). The panic test is replaced by an assertion in the refusal test. The catch_unwind safety net stays. Commits 1-5 are unchanged, and the size still blocks it.

High

  1. Please split it (still open). 2,220 changed lines, none generated. The stack suggested earlier still applies: the preparation, the rewrite of scalar code and vector runs, the lane instructions, turning it on behind XCL_WAVE64_FOLD=1, and the census.
Checked and fine
  • Earlier finding fixed: the known panic input is refused by name in valu_copy (fold.rs) before the mask arithmetic, and what_the_rewrite_does_not_cover_is_refused_with_its_reason expects that reason. Destinations up to EXEC_HI (VCC, TTMP, M0, NULL, EXEC) still go the way they did.
  • translate_folded still maps any other panic in fold to an error, so the split form takes over.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7361827124 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3562#issuecomment-7361827124). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T23:18:30Z. --- **Follow-up review** of `2196dfd1`, since `fbac76fd` (code reading only, not a merge-check) · 1 high **In short:** This push fixes the nit from my last review. A VOP3 compare whose destination is a constant code (above `EXEC_HI`), which overflowed the mask arithmetic, is now refused by name ("a compare into a constant"). The panic test is replaced by an assertion in the refusal test. The `catch_unwind` safety net stays. Commits 1-5 are unchanged, and the size still blocks it. #### High 1. **Please split it (still open).** 2,220 changed lines, none generated. The stack suggested earlier still applies: the preparation, the rewrite of scalar code and vector runs, the lane instructions, turning it on behind `XCL_WAVE64_FOLD=1`, and the census. <details><summary>Checked and fine</summary> - Earlier finding fixed: the known panic input is refused by name in `valu_copy` (`fold.rs`) before the mask arithmetic, and `what_the_rewrite_does_not_cover_is_refused_with_its_reason` expects that reason. Destinations up to `EXEC_HI` (VCC, TTMP, M0, NULL, EXEC) still go the way they did. - `translate_folded` still maps any other panic in `fold` to an error, so the split form takes over. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3562:upstream-pr/3562'
git switch 'upstream-pr/3562'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3562'
git switch 'upstream-pr/3562'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3562'
git switch 'upstream-pr/3562'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3562'
git switch 'main'
git merge --squash 'upstream-pr/3562'
git switch 'main'
git merge --ff-only 'upstream-pr/3562'
git switch 'main'
git merge 'upstream-pr/3562'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!3562
No description provided.