GPU: host pipelines with a geometry stage from the merged ES+GS pair (#314) #400

Open
github-bot wants to merge 10 commits from github-bot/gh-400 into main AGit
Owner

@⁠Revens2 on GitHub · 2026-11-25 00:25 UTC · original
Revens2:fix/issue-314 → main · +3057 −34 · 21 files · 10 commits · open

Step 5 of #138, for #314. Stacked on #381 (#313), itself on #373 (#312), #367 (#311) and #309: the diff here includes theirs until they merge; the commit of this step is the last one. Base is main because the stacked branches are not in this repository.

What is in it

  • A title pipeline with a "vertex" and a "geometry" container is a merged ES+GS stage. pipeline::merged_pair translates the two containers together (emit::translate_merged_gs) into a vertex and a geometry shader, each a Shader with its translation made; the pair is kept by the two containers' hashes, so two pipelines sharing a GS container with different ES containers are two pairs (in memory only, translated again at each start).
  • HostPipeline::new takes geometry stages: vertex, geometry (root parameters with geometry visibility, same user-data / root-view handling as the other stages) and pixel; the GS bytecode goes in the PSO. Stages are found by visibility rather than by position. The library name of such a pipeline is its own (graphics geometry).
  • Topology: the title's own, used as it gives it; the emitted geometry shader takes triangles, so a geometry stage on any other topology type, or without its vertex container, or with a mesh shader, is refused (logged, the draws are dropped as for any pipeline that does not translate).
  • victory-shader gets a synthetic feature with the synthetic containers its tests use, for the victory-gpu test.

Tested

  • victory-shader (synthetic programs): the host device makes a PSO of the translated vertex shader, geometry shader and a pixel stage.
  • victory-gpu: HostPipeline::new on a synthetic ES+GS pair and a pixel container gives a three-stage host pipeline (vertex, geometry, pixel), the pair's translation is shared, a non-triangle topology and a missing vertex container are refused. Runs on the host GPU (skipped without one).
  • cargo build --workspace --locked, cargo test --workspace --locked --no-fail-fast -- --test-threads=4: 536 passed, 0 failed, 7 ignored (Windows).

Not tested / assumed

  • Everything #381 lists as assumed (record layout 4 dwords per register, emits in code order, strip topology, ES vertex id in v0, vertex offsets in v0/v1) still holds: nothing here checks it on a title program. The draw side is unchanged: a draw of such a pipeline sets the user data of the merged layout on both stages from the title's root slots, and that is not exercised outside the unit tests.
  • victory translate still counts geometry programs on their own line: the ES half a GS pairs with lives in another container, only known from a title pipeline at run time, so the batch tool cannot measure the pair path.
  • Whether the 195 failing programs of #138 translate with this: non verifie in this PR (see the comment below if a run was made).

AI use
Written with Claude Code (Claude Sonnet 5.5). The tests are synthetic programs; no title shaders or game files were read.

🤖 Generated with Claude Code

**@⁠Revens2** on GitHub · 2026-11-25 00:25 UTC · [original](https://github.com/fxceless/victory-fork/pull/400) `Revens2:fix/issue-314` → `main` · +3057 −34 · 21 files · 10 commits · open Step 5 of #138, for #314. **Stacked on #381 (#313), itself on #373 (#312), #367 (#311) and #309**: the diff here includes theirs until they merge; the commit of this step is the last one. Base is `main` because the stacked branches are not in this repository. **What is in it** - A title pipeline with a "vertex" and a "geometry" container is a merged ES+GS stage. `pipeline::merged_pair` translates the two containers together (`emit::translate_merged_gs`) into a vertex and a geometry shader, each a `Shader` with its translation made; the pair is kept by the two containers' hashes, so two pipelines sharing a GS container with different ES containers are two pairs (in memory only, translated again at each start). - `HostPipeline::new` takes `geometry` stages: vertex, geometry (root parameters with geometry visibility, same user-data / root-view handling as the other stages) and pixel; the GS bytecode goes in the PSO. Stages are found by visibility rather than by position. The library name of such a pipeline is its own (`graphics geometry`). - Topology: the title's own, used as it gives it; the emitted geometry shader takes triangles, so a geometry stage on any other topology type, or without its vertex container, or with a mesh shader, is refused (logged, the draws are dropped as for any pipeline that does not translate). - victory-shader gets a `synthetic` feature with the synthetic containers its tests use, for the victory-gpu test. **Tested** - victory-shader (synthetic programs): the host device makes a PSO of the translated vertex shader, geometry shader and a pixel stage. - victory-gpu: `HostPipeline::new` on a synthetic ES+GS pair and a pixel container gives a three-stage host pipeline (vertex, geometry, pixel), the pair's translation is shared, a non-triangle topology and a missing vertex container are refused. Runs on the host GPU (skipped without one). - `cargo build --workspace --locked`, `cargo test --workspace --locked --no-fail-fast -- --test-threads=4`: 536 passed, 0 failed, 7 ignored (Windows). **Not tested / assumed** - Everything #381 lists as assumed (record layout 4 dwords per register, emits in code order, strip topology, ES vertex id in v0, vertex offsets in v0/v1) still holds: nothing here checks it on a title program. The draw side is unchanged: a draw of such a pipeline sets the user data of the merged layout on both stages from the title's root slots, and that is not exercised outside the unit tests. - `victory translate` still counts geometry programs on their own line: the ES half a GS pairs with lives in another container, only known from a title pipeline at run time, so the batch tool cannot measure the pair path. - Whether the 195 failing programs of #138 translate with this: `non verifie` in this PR (see the comment below if a run was made). **AI use** Written with Claude Code (Claude Sonnet 5.5). The tests are synthetic programs; no title shaders or game files were read. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
The 195 "an address in an SGPR that is no root parameter" failures are the
GS half of one merged ES+GS stage (#138). Step 1 of its support, without
emitting anything:

- StageIo::Gs and io::raise for a geometry program. User data 0 and 1 of
  the merged stage (s8, s9) are the console runtime's table pointer when the
  root layout puts nothing there; resource tracking traces a load through it
  to resource::RUNTIME_TABLE instead of failing. Other stages and other
  unbound SGPRs fail as before.
- merged::pair_es_gs pairs the ES program (vertex container) with the GS
  program (geometry container): same wave size, one meaning per user-data
  dword, merged root layout. emit::translate_merged_gs runs the pair as far
  as emission.
- emit refuses a geometry program with GS_EMIT ("GS emit"). `translate`
  counts those on their own "geometry" line, not among the failures.

Not done: DXIL geometry emission, the ES to GS handoff through LDS, the
output records, GS_EMIT/GS_CUT, the host pipeline. The runtime table's
contents and the GS stage data are not read.

Refs #138

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
pair_es_gs keeps both halves' ranges of one descriptor table pointer
instead of calling them a user-data conflict. The runtime table pointer
is only inferred through resource::track_merged, i.e. for the merged
layout of a pair (translate_merged_gs) or, in victory translate, as a
stated assumption for an unpaired geometry program: a geometry program
traced alone no longer takes user data 0 and 1 as free.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
StageIo::Es and StageIo::Gs now carry MergedIo (LDS bytes from the common
record). merged::limits counts the vertices a GS program emits along its
longest path from its s_sendmsg GS_EMIT / GS_CUT / GS_EMIT_CUT messages,
refusing a message in a loop. The runtime table pointer is also resolved
for the ES half, which shares the SGPRs. victory translate counts the GS
programs with a bounded vertex count.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Review fixes: a GS program with an indirect jump has no vertex bound, and
the user-data overlap tests saturate the container-supplied SGPR count.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
handoff finds the record the ES half writes to LDS (whole-dword writes at
one base, then s_barrier and the s_setpc_b64 handover) and the GS half's
reads of its input vertices (the halves of the offsets in v0 and v1). The
GS half may only read dwords the ES half writes. emit::merged_halves
pairs two containers, traces and raises the ES half and checks the
handoff; victory translate counts the ES programs on their own line.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Review fixes: an ES half must hand over on every reachable path (a
reachable s_endpgm loses the record), the barrier flag holds only when a
barrier precedes every handover, v_bfe_u32 offsets are read in five bits,
and victory translate reports an ES half whose record analysis fails.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The ES half becomes a DXIL vertex shader: each record dword written to
LDS is a channel of a synthetic TEXCOORD register (32-bit integers),
s_barrier a nop and the s_setpc_b64 handover an end. The GS half becomes
a geometry shader (triangles in, triangle strip out, stream 0): reads of
an input vertex record are loadInput, its own LDS writes go to a private
array, the k-th GS_EMIT copies record k to the output signature and
emits, GS_CUT cuts the strip, the runtime table load reads zero.

translate_merged_gs now returns both shaders. Tests use synthetic GCN
programs only; the DXIL validator accepts both modules.

Assumed, not verified on a title program: record dword 4*row+col is that
channel of the output register, emits are numbered in code order,
triangle strip topology, one instance, ES vertex id in v0.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Review fixes: s_sendmsghalt emits/cuts and half-precision outputs are
refused, the emitted output signature marks the components the emits store,
an input vertex offset must be scaled to bytes, a second runtime table field
is refused (the one read is taken as the output base), and the returned
vertex shader says it is a vertex shader.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A title pipeline with a vertex and a geometry container is a merged ES+GS
stage: the two containers are translated together (translate_merged_gs,
kept by the pair of hashes) and the host pipeline gets a vertex shader, a
geometry shader (root parameters with geometry visibility) and the pixel
stage. Triangle topologies only; the library name of such a pipeline is
its own. victory-shader gets a synthetic feature with the synthetic
containers its tests use, for the victory-gpu test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Closes the six gaps JRamos1993 found offline on the merged ES+GS path:
paired LDS accesses (ds_write2/read2, st64), SDWA word selects,
s_mov_b32 constants and shift-then-mask offsets in the handoff model, the
thread-count prologue as no-ops, a short last output row, and a runtime
table high half masked to its low bits.

Also: the shifted-half mask is refused past a shift of 16 (the patch's
mask overflowed there), and an SDWA op with clamp or omod is not
evaluated.

Co-authored-by: JRamos1993 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:42:36 +00:00
Author
Owner

@⁠Revens2 on GitHub · 2026-11-25 00:36 UTC · original

In-game run of the stacked head (release build, one session of about 9 minutes, the usual script to the lit cell scene): 0 ERROR, 0 device removed, 4 fps at ~4,900 draws a frame like the runs before it, and no pipeline with a geometry stage was created (no geometry stage translated nor does not translate line, no geometry shader seen), so the new path was not exercised in game. That matches #138: the title's GS_VoxelizeGeneric_* programs are not on a path this scene reaches.

The 195 failing programs: non verifie. victory translate reads the title's shader files, which I did not do, and it cannot pair an ES half with its GS half (the pair is only known from a title pipeline at run time), so it would not measure this path anyway.

**@⁠Revens2** on GitHub · 2026-11-25 00:36 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#issuecomment-7148683681) In-game run of the stacked head (release build, one session of about 9 minutes, the usual script to the lit cell scene): 0 `ERROR`, 0 device removed, 4 fps at ~4,900 draws a frame like the runs before it, and **no pipeline with a geometry stage was created** (no `geometry stage translated` nor `does not translate` line, no geometry shader seen), so the new path was not exercised in game. That matches #138: the title's `GS_VoxelizeGeneric_*` programs are not on a path this scene reaches. The 195 failing programs: `non verifie`. `victory translate` reads the title's shader files, which I did not do, and it cannot pair an ES half with its GS half (the pair is only known from a title pipeline at run time), so it would not measure this path anyway.
Author
Owner

@⁠Revens2 on GitHub · 2026-11-25 00:44 UTC · original

Review findings: the three on the geometry emission (s_sendmsghalt, half-precision outputs, runtime table loads) are handled in #381 (1c4de71) and merged into this branch; see the comment there. The fourth, on the user-data block:

  • Shared merged-stage user-data block: not changed. Each translated shader numbers its user-data dwords itself (UserData::index), so the vertex and geometry halves of a pair do not necessarily use the same index for the same dword, and one shared block could have one stage overwrite the other's values. Each stage keeps its own block, as every other stage does. A pair whose two blocks and other root parameters exceed the 64 DWORD limit fails at root signature creation (logged as host root signature refused) and its draws are dropped; I did not measure how close a title's pairs get, as none was created in the run.

Workspace tests on the head (cargo test --workspace --locked --no-fail-fast -- --test-threads=4): 539 passed, 0 failed, 7 ignored.

**@⁠Revens2** on GitHub · 2026-11-25 00:44 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#issuecomment-7148834961) Review findings: the three on the geometry emission (`s_sendmsghalt`, half-precision outputs, runtime table loads) are handled in #381 (1c4de71) and merged into this branch; see the comment there. The fourth, on the user-data block: - **Shared merged-stage user-data block**: not changed. Each translated shader numbers its user-data dwords itself (`UserData::index`), so the vertex and geometry halves of a pair do not necessarily use the same index for the same dword, and one shared block could have one stage overwrite the other's values. Each stage keeps its own block, as every other stage does. A pair whose two blocks and other root parameters exceed the 64 DWORD limit fails at root signature creation (logged as `host root signature refused`) and its draws are dropped; I did not measure how close a title's pairs get, as none was created in the run. Workspace tests on the head (`cargo test --workspace --locked --no-fail-fast -- --test-threads=4`): 539 passed, 0 failed, 7 ignored.
Author
Owner

@⁠JRamos1993 on GitHub · 2026-11-25 04:28 UTC · original

Offline check of this head (64f781d) against the title's 195 geometry programs: the pair path stops at six small gaps. With them closed, every geometry container pairs, translates and validates, and makes a host pipeline. The patch is at the end, on top of this branch.

Setup:

  • RTX 5090, driver 621.24, Windows 11.
  • victory translate --validate --list over the title's shader pack with this branch.
  • A local harness that calls emit::translate_merged_gs on the ES and GS containers (dumped on my machine with VICTORY_DUMP_MATCH, not shared) and validates both outputs with dxil.dll.

What this head does with them. The batch tool runs the ES record step and the GS resource step:

  • All 195 ES halves fail with ES record: an LDS access of the ES half other than a record write. The instruction is ds_write2_b64 in every one; 190 also have one ds_write_b64.
  • All 195 GS halves fail with resources: an address with an untracked high half, at the runtime table. The high half is the table's high half masked with s_and_b32 …, 0xff (a 40-bit address), and high_half does not accept that mask.
  • Nothing is lost: the 195 ES halves now get a line of their own, but each program still validates on its plain vertex-shader line. 25,370 programs validate, as on main.

Past those, inside translate_merged_gs (found with the harness, in this order):

  1. No input-vertex reads found. vertex_reads finds none, because the title computes the offsets differently from the model:
    • vertex 0 is (v0 << 2) & (0xffff << 2) (shift first, then mask), and vertex 2 the same on v1;
    • vertex 1 is an SDWA v_lshlrev_b32 of v0 with src1_sel:WORD_1, whose shift amount (2) is in an SGPR set by s_mov_b32;
    • the reads are ds_read2_b32 and ds_read_b32.
  2. Paired accesses refused. own_accesses refuses the GS half's ds_write2_b32 and ds_read2_b32 on its output records.
  3. Thread-count prologue. Both halves start with the merged wave's thread-count mask: s_bfe_i32 s0, s3, <count field>, s_bfm_b64 exec, s0, 0, s_cmp_eq_u32 s0, 64, s_cselect_b64 exec, -1, exec. The lowering stops there with "an opaque lane mask".
  4. Short last row. The last output row holds three values (signature mask xyz) and the program writes 12 bytes of it. So the records end one dword before emits × record_dwords, and plan refuses them.

The patch:

  • handoff: one elements() helper for single and paired LDS accesses (offsets scaled by the element size, ×64 for st64). es_record, vertex_reads and own_accesses use it.
  • Eval: also follows s_mov_b32 constants, SDWA word selects (only with dst_sel:DWORD and no sext, neg or abs), and v_and_b32 with 0xffff << n of an input scaled by 2^n.
  • emit::gs:
    • The plan's maps hold a list per site.
    • es_as_vertex_shader writes one exp per write instruction. Both elements of a paired write must fall in one record row, which holds for all 195.
    • drop_thread_masks turns the two exec writes of the prologue into s_nop. A host invocation is one vertex or one primitive, so it is a thread that runs. It runs in merged_halves, before anything numbers the instructions: s_nop is dropped from the IR, and the handoff's sites must match the lowering's.
    • plan accepts records that end at the last row's signature columns, and nothing else short of the full array.
  • lower::gs_ds: handles every element of a site; each stored element takes its data from its own operand.
  • resource::high_half: accepts s_and_b32 of the expected high half with a mask of low bits (0xff or wider).
  • Tests: 7 new unit tests on synthetic programs, one per change above.

Results with the patch:

  • Pack: victory translate --validate validates 25,370, the same as before, and loses none that validate on main. Failing programs go from 714 to 324: the 390 ES and GS lines are gone. The summary reads geometry 195 programs: 195 resources traced, 195 I/O raised, 195 stopped at GS emit.
  • Pairs: the ES half that pairs with a given GS is not known offline. So I tried each GS container with every ES container of the same name: 11,229 pairs.
    • All 195 GS containers have at least one pair that translates, and both of its shaders validate. 6,905 pairs do in all: VS 2.9–4.1 KB and GS 6.7–7.4 KB of DXIL, records of 4–6 dwords.
    • The other 4,324 are refused by the pairing checks: 4,322 with "ES and GS programs disagree about a user-data dword", 2 with "a record dword the ES half never writes". None fails in translation or validation.
  • Host pipelines: each GS container with the first ES of its name that translates, plus victory_shader::synthetic::pixel_container(). This is the call a_geometry_pipeline_is_made_from_the_pair_of_containers makes. HostPipeline::new gives 195 vertex+geometry+pixel pipelines; D3D12 refused 0.
  • Checks: cargo test --workspace --locked --no-fail-fast -- --test-threads=4 gives 546 passed, 0 failed, 7 ignored. cargo clippy -p victory-shader --all-targets --locked -- -D warnings is clean, with and without --all-features.

Not tested:

  • Whether the title's real pairs are among those; its pipelines pair them at run time.
  • A draw with these shaders, and the user-data side of the draw.
  • What the GS outputs look like on screen.
Patch on 64f781d (git apply)
diff --git a/crates/victory-shader/src/emit/gs.rs b/crates/victory-shader/src/emit/gs.rs
index 4dd022d..75f129e 100644
--- a/crates/victory-shader/src/emit/gs.rs
+++ b/crates/victory-shader/src/emit/gs.rs
@@ -39,7 +39,8 @@ use std::collections::HashMap;
 use super::container::SigElement;
 use crate::ShaderError::{self, Unsupported};
 use crate::handoff::{Handoff, Access, VertexRead, own_accesses};
-use crate::ir::Program;
+use crate::gfx10::{Fields, Operand};
+use crate::ir::{Program, Reg};
 use crate::merged::{GsMessage, MergedGs, limits, message_of};
 use crate::native::{NativeProgram, StageIo, Usage, VsOutput};
 
@@ -53,13 +54,13 @@ fn unsupported(what: &'static str) -> ShaderError {
 /// messages.
 #[derive(Debug, Clone, Default)]
 pub(crate) struct GsPlan {
-    /// Reads of an input vertex's record.
-    pub reads: HashMap<Site, VertexRead>,
+    /// Reads of an input vertex's record (two at a paired read).
+    pub reads: HashMap<Site, Vec<VertexRead>>,
     /// Writes to the program's own array: (first dword in it, dwords, first
-    /// VGPR).
-    pub stores: HashMap<Site, (u32, u32, u8)>,
+    /// VGPR), two at a paired write.
+    pub stores: HashMap<Site, Vec<(u32, u32, u8)>>,
     /// Reads back from it.
-    pub loads: HashMap<Site, (u32, u32, u8)>,
+    pub loads: HashMap<Site, Vec<(u32, u32, u8)>>,
     /// `GS_EMIT` and friends: the emit's number and the message.
     pub messages: HashMap<Site, (u32, GsMessage)>,
     /// Dwords of an output record.
@@ -107,6 +108,34 @@ pub(crate) fn vertex_id_input() -> Vec<SigElement> {
     }]
 }
 
+/// The merged wave's thread-count masks as no-ops: each half of the console
+/// stage starts by setting `exec` to the lanes below its ES or GS thread
+/// count (`s_bfm_b64 exec`, then `s_cselect_b64 exec, -1, exec` for a full
+/// wave); a host invocation is one thread, which runs.
+pub(crate) fn drop_thread_masks(code: &mut [u8], p: &Program) -> Result<(), ShaderError> {
+    const S_NOP: u32 = 0xBF80_0000;
+    const EXEC: u8 = 126;
+    let Some(entry) = p.blocks.first() else { return Ok(()) };
+    for inst in &entry.insts {
+        if !inst.writes.iter().any(|w| w.0 == Reg::S(EXEC)) {
+            continue;
+        }
+        let mask = match (inst.name(), &inst.fields) {
+            ("s_bfm_b64", _) => true,
+            ("s_cselect_b64", Fields::Sop { src, .. }) => {
+                matches!(src.as_slice(), [Operand::Const(193), Operand::Scalar { code: EXEC, .. }])
+            }
+            _ => false,
+        };
+        if mask {
+            let at = inst.machine.offset;
+            let word = code.get_mut(at..at + 4).ok_or(unsupported("an exec mask outside the code"))?;
+            word.copy_from_slice(&S_NOP.to_le_bytes());
+        }
+    }
+    Ok(())
+}
+
 /// The ES half as a vertex shader: `code` with the record writes as exports
 /// (see the module notes) and the I/O of a vertex shader whose outputs are the
 /// record's rows.
@@ -125,19 +154,28 @@ pub(crate) fn es_as_vertex_shader(
         }
         Ok(())
     };
-    for s in &handoff.es.stores {
-        let inst = &es.blocks[s.site.0].insts[s.site.1];
-        let (row, ch) = (s.dword / 4, s.dword % 4);
-        if ch + s.count > 4 {
-            return Err(unsupported("a record write across two registers"));
+    // One export per write instruction: the two stores of a paired write
+    // (`ds_write2_*`) must fall in one record row.
+    let mut sites: Vec<_> = handoff.es.stores.iter().map(|s| s.site).collect();
+    sites.dedup();
+    for site in sites {
+        let inst = &es.blocks[site.0].insts[site.1];
+        let (mut row, mut en, mut regs) = (None, 0u32, [0u32; 4]);
+        for s in handoff.es.stores.iter().filter(|s| s.site == site) {
+            let (r, ch) = (s.dword / 4, s.dword % 4);
+            let bits = ((1u32 << s.count) - 1) << ch;
+            if ch + s.count > 4 || row.is_some_and(|x| x != r) || en & bits != 0 {
+                return Err(unsupported("a record write across two registers"));
+            }
+            row = Some(r);
+            en |= bits;
+            for k in 0..s.count {
+                regs[(ch + k) as usize] = u32::from(s.reg) + k;
+            }
         }
+        let Some(row) = row else { continue };
         // exp param<row>, the written VGPRs in their channels
-        let en = ((1u32 << s.count) - 1) << ch;
         let word0 = 0xF800_0000 | (32 + row) << 4 | en;
-        let mut regs = [0u32; 4];
-        for k in 0..s.count {
-            regs[(ch + k) as usize] = u32::from(s.reg) + k;
-        }
         let word1 = regs[0] | regs[1] << 8 | regs[2] << 16 | regs[3] << 24;
         put(inst.machine.offset, &[word0, word1])?;
     }
@@ -214,7 +252,17 @@ pub(crate) fn plan(gs: &Program, handoff: &Handoff, outputs: &[SigElement]) -> R
     let lo = writes.clone().map(|a| a.byte / 4).min().ok_or(unsupported("a geometry program that writes no output record"))?;
     let hi = writes.map(|a| a.byte / 4 + a.count).max().unwrap_or(lo);
     let array_dwords = emits * record_dwords;
-    if hi - lo != array_dwords || record_dwords == 0 {
+    // (the last row of a record may hold fewer than four values: the
+    // program need not write the dwords past them in the last record)
+    let last = outputs.iter().filter_map(|e| e.row).max().unwrap_or(0);
+    let last_cols = outputs
+        .iter()
+        .filter(|e| e.row == Some(last))
+        .map(|e| u32::from(e.col) + u32::from(e.cols))
+        .max()
+        .unwrap_or(4)
+        .min(4);
+    if record_dwords == 0 || hi - lo != array_dwords && hi - lo != array_dwords - 4 + last_cols {
         return Err(unsupported("the output records do not fit the output signature"));
     }
     let mut p = GsPlan {
@@ -230,13 +278,12 @@ pub(crate) fn plan(gs: &Program, handoff: &Handoff, outputs: &[SigElement]) -> R
             return Err(unsupported("a geometry output access outside the records"));
         }
         let entry = (at - lo, a.count, a.reg);
-        if a.write {
-            p.stores.insert(a.site, entry);
-        } else {
-            p.loads.insert(a.site, entry);
-        }
+        let at = if a.write { &mut p.stores } else { &mut p.loads };
+        at.entry(a.site).or_default().push(entry);
+    }
+    for r in &handoff.reads {
+        p.reads.entry(r.site).or_default().push(*r);
     }
-    p.reads = handoff.reads.iter().map(|r| (r.site, *r)).collect();
     Ok(p)
 }
 
@@ -356,6 +403,60 @@ pub(crate) mod tests {
         assert_eq!(outputs.iter().map(|o| (o.row, o.param)).collect::<Vec<_>>(), [(0, 0), (1, 1)]);
     }
 
+    /// The merged wave's thread-count prologue of the title's halves:
+    /// `s_bfe_i32 s0, s3, <count>`, `s_bfm_b64 exec, s0, 0`, `s_cmp_eq_u32
+    /// s0, 64`, `s_cselect_b64 exec, -1, exec`. The two exec writes become
+    /// no-ops; other selects stay.
+    #[test]
+    fn the_thread_count_masks_become_no_ops() {
+        let words = [
+            0x8000_0000 | 0x28 << 23 | 255 << 8 | 3, // s_bfe_i32 s0, s3, lit
+            0x0008_0008,
+            0x92FE_8000, // s_bfm_b64 exec, s0, 0
+            0xBF06_C000, // s_cmp_eq_u32 s0, 64
+            0x85FE_7EC1, // s_cselect_b64 exec, -1, exec
+            0x8586_807E, // s_cselect_b64 s[6:7], exec, 0
+            S_ENDPGM,
+        ];
+        let mut code = bytes(&words);
+        let before = program(&words);
+        let exec_writes = |p: &Program| {
+            p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.writes.iter().any(|w| w.0 == Reg::S(126))).count()
+        };
+        assert_eq!(exec_writes(&before), 2);
+        drop_thread_masks(&mut code, &before).unwrap();
+        let after = crate::ir::build(&code, true, 64).unwrap();
+        assert_eq!(exec_writes(&after), 0);
+        let names: Vec<_> = after.blocks.iter().flat_map(|b| b.insts.iter().map(|i| i.name())).collect();
+        assert_eq!(names, ["s_bfe_i32", "s_cmp_eq_u32", "s_cselect_b64", "s_endpgm"]);
+    }
+
+    /// A paired write of the ES half is one export of both elements.
+    #[test]
+    fn a_paired_record_write_is_one_export() {
+        let es = [
+            vop2(V_LSHLREV, 1, 133, 0),
+            ds(DS_WRITE2_B64, 1 << 8),
+            ds_regs2(1, 4, 6, 0),
+            ds(DS_WRITE_B32, 16),
+            ds_regs(1, 8, 0),
+            S_BARRIER,
+            S_SETPC,
+        ];
+        let es_c = container_parts(&[(HwStage::Es, &bytes(&es)), (HwStage::Vs, &bytes(&[S_ENDPGM]))], &[]);
+        let (merged, h) = super::super::merged_halves(&es_c, &gs_container(3)).unwrap();
+        let ir = crate::spill::build(&merged.es).unwrap();
+        let vs = es_as_vertex_shader(&merged, &ir, &h).unwrap();
+        let ir = crate::spill::build(&vs).unwrap();
+        let exps: Vec<_> = ir.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "exp").collect();
+        assert_eq!(exps.len(), 2);
+        // exp param0 with all four channels: v4, v5, v6, v7
+        let at = exps[0].machine.offset;
+        let w0 = u32::from_le_bytes(vs.code[at..at + 4].try_into().unwrap());
+        let w1 = u32::from_le_bytes(vs.code[at + 4..at + 8].try_into().unwrap());
+        assert_eq!((w0 >> 4 & 0x3F, w0 & 0xF, w1), (32, 0xF, 4 | 5 << 8 | 6 << 16 | 7 << 24));
+    }
+
     #[test]
     fn the_gs_plan_numbers_the_emits_and_places_the_records() {
         let (_, h) = super::super::merged_halves(&es_container(), &gs_container(3)).unwrap();
@@ -367,7 +468,7 @@ pub(crate) mod tests {
         m.sort_by_key(|x| x.0);
         assert_eq!(m[2], (2, GsMessage::EmitCut { stream: 0 }));
         assert_eq!(p.stores.len(), 15);
-        assert!(p.stores.values().all(|s| s.0 % 4 == 0 && s.1 == 4));
+        assert!(p.stores.values().flatten().all(|s| s.0 % 4 == 0 && s.1 == 4));
         assert_eq!(p.reads.len(), 2);
         // Records that do not fill the signature's size are refused.
         let (_, h2) = super::super::merged_halves(&es_container(), &gs_container(2)).unwrap();
@@ -375,6 +476,35 @@ pub(crate) mod tests {
         assert!(plan(&gs2, &h2, &outs[..4]).is_err());
     }
 
+    /// The title's last output row holds three values: the program writes
+    /// twelve bytes of it, and the last record ends a dword early.
+    #[test]
+    fn the_last_row_of_a_record_may_be_short() {
+        const DS_WRITE_B96: u32 = 0xde;
+        let mut w = gs_words(3);
+        // the last row of each record: 12 bytes
+        for n in 0..3 {
+            let k = w.iter().position(|&x| x == ds(DS_WRITE_B128, n * 80 + 64)).unwrap();
+            w[k] = ds(DS_WRITE_B96, n * 80 + 64);
+        }
+        let short = osg1(&[
+            ("SV_Position", 0, 1, 3, 0, 0xF),
+            ("TEXCOORD", 0, 0, 3, 1, 0xF),
+            ("TEXCOORD", 1, 0, 3, 2, 0xF),
+            ("TEXCOORD", 2, 0, 3, 3, 0xF),
+            ("TEXCOORD", 3, 0, 3, 4, 0x7),
+        ]);
+        let gs_c = container_parts(&[(HwStage::Gs, &bytes(&w))], &[(FourCC::OSG1, &short)]);
+        let (_, h) = super::super::merged_halves(&es_container(), &gs_c).unwrap();
+        let gs = crate::spill::build(&native_of(&gs_c)).unwrap();
+        let outs = signature_of(&gs_c, FourCC::OSG1);
+        let p = plan(&gs, &h, &outs).unwrap();
+        assert_eq!((p.record_dwords, p.array_dwords), (20, 60));
+        // With four values in that row, a dword is missing: refused.
+        let full = signature_of(&gs_container(3), FourCC::OSG1);
+        assert!(plan(&gs, &h, &full).is_err());
+    }
+
     /// A merged stage of synthetic programs comes out as a vertex shader and
     /// a geometry shader of the declared shapes, which the validator, where
     /// there is one, accepts.
diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs
index 1f19cc7..3ef9279 100644
--- a/crates/victory-shader/src/emit/lower.rs
+++ b/crates/victory-shader/src/emit/lower.rs
@@ -4214,50 +4214,62 @@ impl<'a> Lower<'a> {
         let Some(g) = x.gs.as_ref() else {
             return Ok(false);
         };
-        let Fields::Ds { data, .. } = &inst.fields else {
+        let Fields::Ds { .. } = &inst.fields else {
             unreachable!()
         };
         let guard = self.guard(site.0, site.1)?;
         let c = self.cur;
-        if let Some(r) = g.reads.get(&site) {
-            for k in 0..r.count {
-                let d = r.dword + k;
-                let (id, col) = (d / 4, d % 4);
-                let known = self.s.inputs.get(id as usize).is_some_and(|e| u32::from(e.cols) > col);
-                if !known {
-                    return Err("a read of a record dword the signature does not have");
-                }
-                let args = [
-                    self.s.m.i32(id),
-                    self.s.m.i32(0),
-                    self.s.m.i8(col as u8),
-                    self.s.m.i32(u32::from(r.vertex)),
-                ];
-                let i32t = self.s.t.i32;
-                let v = self.s.op(c, "loadInput.i32", Attr::ReadNone, i32t, 4, &args);
-                self.write(inst, Reg::V(r.reg + k as u8), v, guard);
+        if let Some(reads) = g.reads.get(&site) {
+            for r in reads {
+                for k in 0..r.count {
+                    let d = r.dword + k;
+                    let (id, col) = (d / 4, d % 4);
+                    let known = self.s.inputs.get(id as usize).is_some_and(|e| u32::from(e.cols) > col);
+                    if !known {
+                        return Err("a read of a record dword the signature does not have");
+                    }
+                    let args = [
+                        self.s.m.i32(id),
+                        self.s.m.i32(0),
+                        self.s.m.i8(col as u8),
+                        self.s.m.i32(u32::from(r.vertex)),
+                    ];
+                    let i32t = self.s.t.i32;
+                    let v = self.s.op(c, "loadInput.i32", Attr::ReadNone, i32t, 4, &args);
+                    self.write(inst, Reg::V(r.reg + k as u8), v, guard);
+                }
             }
             return Ok(true);
         }
-        if let Some(&(at, count, _)) = g.stores.get(&site) {
-            let vals = self.vgprs(inst, data.first().ok_or("an LDS write")?, count as u8)?;
+        if let Some(stores) = g.stores.get(&site) {
+            // (each element's data from its own operand: the plan has its
+            // first VGPR)
+            let mut vals = Vec::new();
+            for &(at, count, reg) in stores {
+                let op = Operand::Vector { reg, dwords: count as u8 };
+                for (k, v) in self.vgprs(inst, &op, count as u8)?.into_iter().enumerate() {
+                    vals.push((at + k as u32, v));
+                }
+            }
             let arr = self.s.lds();
             let open = self.begin_guarded(guard);
-            for (k, v) in vals.into_iter().enumerate() {
-                let index = self.s.m.i32(at + k as u32);
+            for (at, v) in vals {
+                let index = self.s.m.i32(at);
                 let p = self.s.m.element(self.cur, arr, index);
                 self.s.m.store(self.cur, p, v);
             }
             self.end_guarded(open, &[]);
             return Ok(true);
         }
-        if let Some(&(at, count, reg)) = g.loads.get(&site) {
+        if let Some(loads) = g.loads.get(&site) {
             let arr = self.s.lds();
-            for k in 0..count {
-                let index = self.s.m.i32(at + k);
-                let p = self.s.m.element(c, arr, index);
-                let v = self.s.m.load(c, p);
-                self.write(inst, Reg::V(reg + k as u8), v, guard);
+            for &(at, count, reg) in loads {
+                for k in 0..count {
+                    let index = self.s.m.i32(at + k);
+                    let p = self.s.m.element(c, arr, index);
+                    let v = self.s.m.load(c, p);
+                    self.write(inst, Reg::V(reg + k as u8), v, guard);
+                }
             }
             return Ok(true);
         }
diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs
index 0bc5590..b147072 100644
--- a/crates/victory-shader/src/emit/mod.rs
+++ b/crates/victory-shader/src/emit/mod.rs
@@ -324,7 +324,12 @@ pub fn merged_halves(
                 what: "a container without the ES or GS program of a merged stage",
             })
     };
-    let merged = crate::merged::pair_es_gs(stage_of(es, HwStage::Es)?, stage_of(gs, HwStage::Gs)?)?;
+    let mut merged = crate::merged::pair_es_gs(stage_of(es, HwStage::Es)?, stage_of(gs, HwStage::Gs)?)?;
+    // (before anything numbers the instructions: the no-ops are dropped)
+    for half in [&mut merged.es, &mut merged.gs] {
+        let ir = crate::spill::build(half)?;
+        gs::drop_thread_masks(&mut half.code, &ir)?;
+    }
     let es_native = NativeProgram {
         layout: merged.layout.clone(),
         ..merged.es.clone()
diff --git a/crates/victory-shader/src/handoff.rs b/crates/victory-shader/src/handoff.rs
index ca6f5f6..608d517 100644
--- a/crates/victory-shader/src/handoff.rs
+++ b/crates/victory-shader/src/handoff.rs
@@ -124,18 +124,43 @@ impl<'a> Eval<'a> {
 
     fn inst(&self, inst: &Inst, v: Value, depth: u32) -> Lin {
         let opaque = Lin::of(Base::Opaque(v));
+        // (a constant the code puts in an SGPR, such as a shift amount)
+        if let Fields::Sop { src, .. } = &inst.fields
+            && inst.name() == "s_mov_b32"
+        {
+            return src
+                .first()
+                .and_then(|o| self.operand(inst, o, depth))
+                .filter(Lin::is_constant)
+                .unwrap_or(opaque);
+        }
         let Fields::Valu(f) = &inst.fields else {
             return opaque;
         };
         let args: Option<Vec<Lin>> = f.src.iter().map(|s| self.operand(inst, s, depth)).collect();
-        let Some(a) = args else { return opaque };
+        let Some(mut a) = args else { return opaque };
         let c = |l: &Lin| l.is_constant().then_some(l.add);
+        let plain = |x: &Lin| x.mul == 1 && x.add == 0;
+        // SDWA: a whole-dword result of word selects (`src1_sel:WORD_1` is
+        // the high half of a VGPR as it arrived).
+        if let Some(sd) = f.sdwa {
+            if sd.dst_sel != 6 || sd.sext != 0 || f.neg != 0 || f.abs != 0 {
+                return opaque;
+            }
+            for (x, sel) in a.iter_mut().zip(sd.src_sel) {
+                *x = match (sel, x.base) {
+                    (6, _) => *x,
+                    (4 | 5, _) if x.is_constant() => Lin::constant(x.add >> (16 * u32::from(sel - 4)) & 0xFFFF),
+                    (4 | 5, Base::Input(reg)) if plain(x) => Lin::of(Base::Half { reg, high: sel == 5 }),
+                    _ => return opaque,
+                };
+            }
+        }
         let shifted = |x: Lin, s: u32| Lin {
             base: x.base,
             mul: x.mul.wrapping_shl(s),
             add: x.add.wrapping_shl(s),
         };
-        let plain = |x: &Lin| x.mul == 1 && x.add == 0;
         match (inst.name(), a.as_slice()) {
             ("v_mov_b32", [x]) => *x,
             ("v_and_b32", [x, y]) | ("v_and_b32", [y, x]) if c(y) == Some(0xFFFF) => match x.base {
@@ -143,6 +168,16 @@ impl<'a> Eval<'a> {
                 Base::Half { .. } if plain(x) => *x,
                 _ => opaque,
             },
+            // (the shift first: `(v << n) & (0xFFFF << n)` is the low half, scaled)
+            ("v_and_b32", [x, y]) | ("v_and_b32", [y, x])
+                if x.add == 0 && x.mul > 1 && x.mul.is_power_of_two() && c(y) == Some(0xFFFF * x.mul) =>
+            {
+                match x.base {
+                    Base::Input(reg) => Lin { base: Base::Half { reg, high: false }, ..*x },
+                    Base::Half { .. } => *x,
+                    _ => opaque,
+                }
+            }
             ("v_lshrrev_b32", [s, x]) if c(s) == Some(16) => match x.base {
                 Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: true }),
                 _ => opaque,
@@ -191,6 +226,34 @@ fn width(name: &str) -> Option<u32> {
     }
 }
 
+/// The elements an LDS read or write moves: (byte offset from its address,
+/// dwords). One for a single address (`ds_read_b32`...), two for a pair
+/// (`ds_read2_b32`, `ds_write2_b64`...: each offset counts elements, ×64 for
+/// `st64`); `None` for anything else (bytes and halves, atomics, exchanges).
+/// The k-th element goes to or comes from the k-th data operand of a write,
+/// and the k-th group of `dwords` destination VGPRs of a read.
+fn elements(name: &str, offset0: u8, offset1: u8) -> Option<Vec<(u32, u32)>> {
+    if let Some(w) = width(name) {
+        return Some(vec![(u32::from(offset0) | u32::from(offset1) << 8, w)]);
+    }
+    let w = match name {
+        "ds_read2_b32" | "ds_read2st64_b32" | "ds_write2_b32" | "ds_write2st64_b32" => 1,
+        "ds_read2_b64" | "ds_read2st64_b64" | "ds_write2_b64" | "ds_write2st64_b64" => 2,
+        _ => return None,
+    };
+    let scale = 4 * w * if name.contains("st64") { 64 } else { 1 };
+    Some(vec![(u32::from(offset0) * scale, w), (u32::from(offset1) * scale, w)])
+}
+
+/// The first VGPR of element `k` of an LDS access (see [`elements`]).
+fn element_reg(write: bool, data: &[Operand], dst: Option<Operand>, k: usize, dwords: u32) -> Option<u8> {
+    match (write, data.get(k), dst) {
+        (true, Some(&Operand::Vector { reg, .. }), _) => Some(reg),
+        (false, _, Some(Operand::Vector { reg, .. })) => Some(reg + (k as u32 * dwords) as u8),
+        _ => None,
+    }
+}
+
 /// Instructions that name LDS in the encoding but touch none.
 fn no_memory(name: &str) -> bool {
     name.starts_with("ds_swizzle") || name.contains("permute") || name == "ds_nop"
@@ -290,15 +353,12 @@ pub fn es_record(p: &Program) -> Result<EsRecord, ShaderError> {
             if no_memory(name) {
                 continue;
             }
-            let Some(count) = width(name).filter(|_| name.starts_with("ds_write") && !gds) else {
+            let Some(parts) = elements(name, *offset0, *offset1).filter(|_| name.starts_with("ds_write") && !gds) else {
                 return Err(unsupported("an LDS access of the ES half other than a record write"));
             };
             let Some(Operand::Vector { reg: a, .. }) = *addr else {
                 return Err(unsupported("an LDS write without an address"));
             };
-            let Some(Operand::Vector { reg: d, .. }) = data.first().copied() else {
-                return Err(unsupported("an LDS write without data"));
-            };
             let lin = eval.value(inst.read(Reg::V(a)).ok_or(unsupported("an unread LDS address"))?, 0);
             if lin.is_constant() {
                 return Err(unsupported("a record write at a constant address"));
@@ -308,11 +368,14 @@ pub fn es_record(p: &Program) -> Result<EsRecord, ShaderError> {
                 Some(first) if first == (lin.base, lin.mul) => {}
                 Some(_) => return Err(unsupported("ES record writes at more than one base")),
             }
-            let byte = lin.add.wrapping_add(u32::from(*offset0) | u32::from(*offset1) << 8);
-            if byte % 4 != 0 {
-                return Err(unsupported("a record write off a dword"));
+            for (k, (off, count)) in parts.into_iter().enumerate() {
+                let reg = element_reg(true, data, None, k, count).ok_or(unsupported("an LDS write without data"))?;
+                let byte = lin.add.wrapping_add(off);
+                if byte % 4 != 0 {
+                    return Err(unsupported("a record write off a dword"));
+                }
+                stores.push(Store { site: (b, i), dword: byte / 4, count, reg });
             }
-            stores.push(Store { site: (b, i), dword: byte / 4, count, reg: d });
         }
     }
     let dwords = stores.iter().map(|s| s.dword + s.count).max().ok_or(unsupported("an ES half that writes no record"))?;
@@ -358,17 +421,17 @@ pub fn vertex_reads(p: &Program) -> Result<Vec<VertexRead>, ShaderError> {
             if lin.mul != 4 {
                 return Err(unsupported("a vertex offset not scaled to bytes"));
             }
-            let Some(count) = width(name) else {
+            let Some(parts) = elements(name, *offset0, *offset1) else {
                 return Err(unsupported("an LDS read of a vertex record that is not whole dwords"));
             };
-            let Some(Operand::Vector { reg: d, .. }) = *dst else {
-                return Err(unsupported("an LDS read without a destination"));
-            };
-            let byte = lin.add.wrapping_add(u32::from(*offset0) | u32::from(*offset1) << 8);
-            if byte % 4 != 0 {
-                return Err(unsupported("a vertex read off a dword"));
+            for (k, (off, count)) in parts.into_iter().enumerate() {
+                let reg = element_reg(false, &[], *dst, k, count).ok_or(unsupported("an LDS read without a destination"))?;
+                let byte = lin.add.wrapping_add(off);
+                if byte % 4 != 0 {
+                    return Err(unsupported("a vertex read off a dword"));
+                }
+                out.push(VertexRead { site: (b, i), vertex: vertex as u8, dword: byte / 4, count, reg });
             }
-            out.push(VertexRead { site: (b, i), vertex: vertex as u8, dword: byte / 4, count, reg: d });
         }
     }
     Ok(out)
@@ -391,8 +454,8 @@ pub struct Access {
 }
 
 /// The LDS accesses of a GS program that are not reads of input vertices, in
-/// code order. Fails on any other LDS operation (atomics, paired reads and
-/// writes, bytes and halves).
+/// code order (a paired read or write is two). Fails on any other LDS
+/// operation (atomics, bytes and halves).
 pub fn own_accesses(p: &Program) -> Result<Vec<Access>, ShaderError> {
     let eval = Eval::new(p);
     let mut out = Vec::new();
@@ -406,7 +469,7 @@ pub fn own_accesses(p: &Program) -> Result<Vec<Access>, ShaderError> {
                 continue;
             }
             let write = name.starts_with("ds_write");
-            let Some(count) = width(name).filter(|_| !gds) else {
+            let Some(parts) = elements(name, *offset0, *offset1).filter(|_| !gds) else {
                 return Err(unsupported("an LDS operation of the GS half beyond whole-dword reads and writes"));
             };
             let Some(Operand::Vector { reg: a, .. }) = *addr else {
@@ -416,15 +479,14 @@ pub fn own_accesses(p: &Program) -> Result<Vec<Access>, ShaderError> {
             if matches!(lin.base, Base::Half { .. }) && !write {
                 continue; // an input vertex ([`vertex_reads`])
             }
-            let reg = match (write, data.first(), dst) {
-                (true, Some(Operand::Vector { reg, .. }), _) | (false, _, Some(Operand::Vector { reg, .. })) => *reg,
-                _ => return Err(unsupported("an LDS access without a register")),
-            };
-            let byte = lin.add.wrapping_add(u32::from(*offset0) | u32::from(*offset1) << 8);
-            if byte % 4 != 0 {
-                return Err(unsupported("an LDS access off a dword"));
+            for (k, (off, count)) in parts.into_iter().enumerate() {
+                let reg = element_reg(write, data, *dst, k, count).ok_or(unsupported("an LDS access without a register"))?;
+                let byte = lin.add.wrapping_add(off);
+                if byte % 4 != 0 {
+                    return Err(unsupported("an LDS access off a dword"));
+                }
+                out.push(Access { site: (b, i), write, base: lin.base, mul: lin.mul, byte, count, reg });
             }
-            out.push(Access { site: (b, i), write, base: lin.base, mul: lin.mul, byte, count, reg });
         }
     }
     Ok(out)
@@ -491,6 +553,15 @@ pub(crate) mod tests {
     pub const DS_WRITE_B128: u32 = 0x0df;
     pub const DS_READ_B32: u32 = 0x36;
     pub const DS_READ_B128: u32 = 0x0ff;
+    pub const DS_WRITE2_B32: u32 = 0x0e;
+    pub const DS_WRITE2ST64_B32: u32 = 0x0f;
+    pub const DS_WRITE2_B64: u32 = 0x4e;
+    pub const DS_READ2_B32: u32 = 0x37;
+
+    /// The second dword of a DS instruction with two data operands.
+    pub fn ds_regs2(addr: u32, data0: u32, data1: u32, dst: u32) -> u32 {
+        dst << 24 | data1 << 16 | data0 << 8 | addr
+    }
 
     pub fn program(words: &[u32]) -> Program {
         let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
@@ -522,6 +593,32 @@ pub(crate) mod tests {
         assert!(r.writes(3) && r.writes(4) && !r.writes(5));
     }
 
+    /// The title's ES halves write their records with `ds_write2_b64`: two
+    /// stores at one site, each offset counting 8-byte elements.
+    #[test]
+    fn a_paired_write_is_two_stores_at_one_site() {
+        let words = [
+            vop2(V_LSHLREV, 1, 133, 0), // v_lshlrev_b32 v1, 5, v0
+            ds(DS_WRITE2_B64, 1 << 8),  // offset0:0 offset1:1
+            ds_regs2(1, 4, 6, 0),       // v[4:5], v[6:7]
+            ds(DS_WRITE_B32, 16),
+            ds_regs(1, 8, 0),
+            S_BARRIER,
+            S_SETPC,
+        ];
+        let r = es_record(&program(&words)).unwrap();
+        let at: Vec<_> = r.stores.iter().map(|s| (s.dword, s.count, s.reg)).collect();
+        assert_eq!(at, [(0, 2, 4), (2, 2, 6), (4, 1, 8)]);
+        assert_eq!(r.stores[0].site, r.stores[1].site);
+        assert_eq!(r.dwords, 5);
+        // st64: an offset counts 64 elements (of 4 bytes here).
+        let mut st64 = words;
+        st64[1] = ds(DS_WRITE2ST64_B32, 1 << 8);
+        let r = es_record(&program(&st64)).unwrap();
+        let at: Vec<_> = r.stores.iter().map(|s| (s.dword, s.count, s.reg)).collect();
+        assert_eq!(at, [(0, 1, 4), (64, 1, 6), (4, 1, 8)]);
+    }
+
     #[test]
     fn an_es_half_that_does_not_hand_over_or_writes_oddly_is_refused() {
         let mut ends = es_words();
@@ -620,6 +717,47 @@ pub(crate) mod tests {
         assert_eq!(at, [(0, 0, 4, 4), (1, 4, 1, 8)]);
     }
 
+    /// The title's GS halves compute the offsets the other way round: vertex 0
+    /// and 2 shift first and mask with `0xffff << 2`, vertex 1 is an SDWA
+    /// shift of the high word of v0 by an SGPR that holds 2; and they read
+    /// with `ds_read2_b32`.
+    #[test]
+    fn the_gs_half_reads_vertices_by_shifted_and_selected_halves() {
+        const SDWA: u32 = 0xF9;
+        let words = [
+            vop2(V_LSHLREV, 3, 130, 0), // v_lshlrev_b32 v3, 2, v0
+            vop2(V_AND, 10, 255, 3),    // v_and_b32 v10, 0x3fffc, v3
+            0x3FFFC,
+            ds(DS_READ2_B32, 1 << 8), // ds_read2_b32 v[4:5], v10 offset1:1
+            ds_regs(10, 0, 4),
+            0xBE81_0382, // s_mov_b32 s1, 2
+            // v_lshlrev_b32 v8, s1, v0 dst_sel:DWORD src0_sel:DWORD src1_sel:WORD_1
+            vop2(V_LSHLREV, 8, SDWA, 0),
+            1 | 6 << 8 | 6 << 16 | 1 << 23 | 5 << 24,
+            ds(DS_READ_B32, 8), // ds_read_b32 v6, v8 offset:8
+            ds_regs(8, 0, 6),
+            vop2(V_LSHLREV, 9, 130, 1), // v_lshlrev_b32 v9, 2, v1
+            vop2(V_AND, 7, 255, 9),     // v_and_b32 v7, 0x3fffc, v9
+            0x3FFFC,
+            ds(DS_READ2_B32, 4 | 5 << 8), // ds_read2_b32 v[12:13], v7 offset0:4 offset1:5
+            ds_regs(7, 0, 12),
+            S_ENDPGM,
+        ];
+        let r = vertex_reads(&program(&words)).unwrap();
+        let at: Vec<_> = r.iter().map(|r| (r.vertex, r.dword, r.count, r.reg)).collect();
+        assert_eq!(at, [(0, 0, 1, 4), (0, 1, 1, 5), (1, 2, 1, 6), (2, 4, 1, 12), (2, 5, 1, 13)]);
+        // A byte select is no half: that read is the program's own memory.
+        let mut byte = words;
+        byte[7] = 1 | 6 << 8 | 6 << 16 | 1 << 23 | 1 << 24;
+        let r = vertex_reads(&program(&byte)).unwrap();
+        assert!(r.iter().all(|r| r.vertex != 1));
+        // A mask that is not the scaled half is no offset either.
+        let mut mask = words;
+        mask[2] = 0xFFFF;
+        let r = vertex_reads(&program(&mask)).unwrap();
+        assert!(r.iter().all(|r| r.reg != 4));
+    }
+
     #[test]
     fn an_input_offset_is_scaled_to_bytes() {
         // v_lshlrev_b32 v2, 3, v2 instead of 2: not a dword offset.
@@ -670,6 +808,24 @@ pub(crate) mod tests {
         assert!(own_accesses(&program(&gs_words())).unwrap().is_empty());
     }
 
+    #[test]
+    fn a_paired_access_of_the_gs_halfs_own_memory_is_two() {
+        // v_lshlrev_b32 v2, 2, v15, ds_write2_b32 v2, v4, v5 offset0:2
+        // offset1:3, ds_read2_b32 v[8:9], v2 offset0:2 offset1:3.
+        let words = [
+            vop2(V_LSHLREV, 2, 130, 15),
+            ds(DS_WRITE2_B32, 2 | 3 << 8),
+            ds_regs2(2, 4, 5, 0),
+            ds(DS_READ2_B32, 2 | 3 << 8),
+            ds_regs(2, 0, 8),
+            S_ENDPGM,
+        ];
+        let a = own_accesses(&program(&words)).unwrap();
+        let at: Vec<_> = a.iter().map(|a| (a.write, a.byte, a.count, a.reg)).collect();
+        assert_eq!(at, [(true, 8, 1, 4), (true, 12, 1, 5), (false, 8, 1, 8), (false, 12, 1, 9)]);
+        assert!(a[0].site == a[1].site && a[2].site == a[3].site && a[0].site != a[2].site);
+    }
+
     #[test]
     fn the_handoff_pairs_reads_with_writes() {
         let h = handoff(&program(&es_words()), &program(&gs_words())).unwrap();
diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs
index 7b747f6..318929e 100644
--- a/crates/victory-shader/src/resource.rs
+++ b/crates/victory-shader/src/resource.rs
@@ -1068,13 +1068,20 @@ impl<'a> Tracer<'a> {
         })
     }
 
-    /// `hi` is `high` (0 for a table), possibly plus a carry.
+    /// `hi` is `high` (0 for a table), possibly plus a carry or masked to
+    /// its low bits.
     fn high_half(&self, hi: Term, high: Option<Value>) -> bool {
         let want = high.map_or(Term::Const(0), Term::Value);
+        // (`s_and_b32` with a mask of the low bits, 0xff for a 40-bit
+        // address, keeps a high half that fits it)
+        let low_mask = |t: Term| matches!(t, Term::Const(c) if c >= 0xff && c.wrapping_add(1).is_power_of_two());
         hi == want
             || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and(
                 |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0)
             ))
+            || matches!(hi, Term::Value(v) if self.sop2(v, &["s_and_b32"]).is_some_and(
+                |(_, [a, b])| a == want && low_mask(b) || b == want && low_mask(a)
+            ))
     }
 
     /// `hi` adds something (with carry) to `high`: `s_addc_u32` or
@@ -3949,6 +3956,26 @@ pub(crate) mod tests {
         assert_eq!(r.scalar, [((0, 0), at(RUNTIME_TABLE, 0xB8))]);
     }
 
+    /// The title's geometry programs take the table's high half masked to its
+    /// low byte (a 40-bit address): `s_and_b32 s1, s9, 0xff`, then the load
+    /// through s[0:1] with s0 = s8. A mask that keeps fewer bits is refused.
+    #[test]
+    fn a_runtime_table_high_half_masked_to_its_low_bits_is_the_table() {
+        let words = |mask: u32| {
+            let and = 0x8000_0000 | 0x0e << 23 | 1 << 16 | 255 << 8 | 9; // s_and_b32 s1, s9, lit
+            let [load, offset, end] = load_b8(0);
+            [and, mask, 0xBE80_0308, load, offset, end] // s_mov_b32 s0, s8
+        };
+        let r = track_words(&words(0xFF), &[], HwStage::Gs);
+        assert_eq!(r.scalar.iter().map(|s| s.1).collect::<Vec<_>>(), [at(RUNTIME_TABLE, 0xB8)]);
+        let r = track_words(&words(0xFFFF), &[], HwStage::Gs);
+        assert_eq!(r.scalar.iter().map(|s| s.1).collect::<Vec<_>>(), [at(RUNTIME_TABLE, 0xB8)]);
+        for mask in [0x7F, 0xFF00] {
+            let err = track_error(&words(mask), &[], HwStage::Gs);
+            assert!(matches!(err, ShaderError::Unsupported { .. }), "{mask:#x}: {err:?}");
+        }
+    }
+
     /// Only a layout that holds both halves' parameters can say the first two
     /// user-data dwords are no one's: a geometry program tracked as it is, with
     /// the ES half unknown, still fails on a load through them.

AI use: Claude Code with Claude Opus 5.5 ran the pack, wrote the harness and the patch, ran the tests and wrote this. The unit tests use synthetic programs. The title's shaders were only read on my machine.

**@⁠JRamos1993** on GitHub · 2026-11-25 04:28 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#issuecomment-7152882106) **Offline check of this head (`64f781d`) against the title's 195 geometry programs: the pair path stops at six small gaps. With them closed, every geometry container pairs, translates and validates, and makes a host pipeline.** The patch is at the end, on top of this branch. **Setup:** - RTX 5090, driver 621.24, Windows 11. - `victory translate --validate --list` over the title's shader pack with this branch. - A local harness that calls `emit::translate_merged_gs` on the ES and GS containers (dumped on my machine with `VICTORY_DUMP_MATCH`, not shared) and validates both outputs with `dxil.dll`. **What this head does with them.** The batch tool runs the ES record step and the GS resource step: - **All 195 ES halves** fail with `ES record: an LDS access of the ES half other than a record write`. The instruction is `ds_write2_b64` in every one; 190 also have one `ds_write_b64`. - **All 195 GS halves** fail with `resources: an address with an untracked high half`, at the runtime table. The high half is the table's high half masked with `s_and_b32 …, 0xff` (a 40-bit address), and `high_half` does not accept that mask. - **Nothing is lost:** the 195 ES halves now get a line of their own, but each program still validates on its plain vertex-shader line. 25,370 programs validate, as on `main`. **Past those, inside `translate_merged_gs`** (found with the harness, in this order): 1. **No input-vertex reads found.** `vertex_reads` finds none, because the title computes the offsets differently from the model: - vertex 0 is `(v0 << 2) & (0xffff << 2)` (shift first, then mask), and vertex 2 the same on v1; - vertex 1 is an SDWA `v_lshlrev_b32` of v0 with `src1_sel:WORD_1`, whose shift amount (2) is in an SGPR set by `s_mov_b32`; - the reads are `ds_read2_b32` and `ds_read_b32`. 2. **Paired accesses refused.** `own_accesses` refuses the GS half's `ds_write2_b32` and `ds_read2_b32` on its output records. 3. **Thread-count prologue.** Both halves start with the merged wave's thread-count mask: `s_bfe_i32 s0, s3, <count field>`, `s_bfm_b64 exec, s0, 0`, `s_cmp_eq_u32 s0, 64`, `s_cselect_b64 exec, -1, exec`. The lowering stops there with "an opaque lane mask". 4. **Short last row.** The last output row holds three values (signature mask `xyz`) and the program writes 12 bytes of it. So the records end one dword before `emits × record_dwords`, and `plan` refuses them. **The patch:** - **`handoff`:** one `elements()` helper for single and paired LDS accesses (offsets scaled by the element size, ×64 for `st64`). `es_record`, `vertex_reads` and `own_accesses` use it. - **`Eval`:** also follows `s_mov_b32` constants, SDWA word selects (only with `dst_sel:DWORD` and no sext, neg or abs), and `v_and_b32` with `0xffff << n` of an input scaled by `2^n`. - **`emit::gs`:** - The plan's maps hold a list per site. - `es_as_vertex_shader` writes one `exp` per write instruction. Both elements of a paired write must fall in one record row, which holds for all 195. - `drop_thread_masks` turns the two `exec` writes of the prologue into `s_nop`. A host invocation is one vertex or one primitive, so it is a thread that runs. It runs in `merged_halves`, before anything numbers the instructions: `s_nop` is dropped from the IR, and the handoff's sites must match the lowering's. - `plan` accepts records that end at the last row's signature columns, and nothing else short of the full array. - **`lower::gs_ds`:** handles every element of a site; each stored element takes its data from its own operand. - **`resource::high_half`:** accepts `s_and_b32` of the expected high half with a mask of low bits (`0xff` or wider). - **Tests:** 7 new unit tests on synthetic programs, one per change above. **Results with the patch:** - **Pack:** `victory translate --validate` validates 25,370, the same as before, and loses none that validate on `main`. Failing programs go from 714 to 324: the 390 ES and GS lines are gone. The summary reads `geometry 195 programs: 195 resources traced, 195 I/O raised, 195 stopped at GS emit`. - **Pairs:** the ES half that pairs with a given GS is not known offline. So I tried each GS container with every ES container of the same name: 11,229 pairs. - **All 195 GS containers have at least one pair that translates, and both of its shaders validate.** 6,905 pairs do in all: VS 2.9–4.1 KB and GS 6.7–7.4 KB of DXIL, records of 4–6 dwords. - The other 4,324 are refused by the pairing checks: 4,322 with "ES and GS programs disagree about a user-data dword", 2 with "a record dword the ES half never writes". None fails in translation or validation. - **Host pipelines:** each GS container with the first ES of its name that translates, plus `victory_shader::synthetic::pixel_container()`. This is the call `a_geometry_pipeline_is_made_from_the_pair_of_containers` makes. **`HostPipeline::new` gives 195 vertex+geometry+pixel pipelines; D3D12 refused 0.** - **Checks:** `cargo test --workspace --locked --no-fail-fast -- --test-threads=4` gives 546 passed, 0 failed, 7 ignored. `cargo clippy -p victory-shader --all-targets --locked -- -D warnings` is clean, with and without `--all-features`. **Not tested:** - Whether the title's real pairs are among those; its pipelines pair them at run time. - A draw with these shaders, and the user-data side of the draw. - What the GS outputs look like on screen. <details><summary>Patch on <code>64f781d</code> (<code>git apply</code>)</summary> ```diff diff --git a/crates/victory-shader/src/emit/gs.rs b/crates/victory-shader/src/emit/gs.rs index 4dd022d..75f129e 100644 --- a/crates/victory-shader/src/emit/gs.rs +++ b/crates/victory-shader/src/emit/gs.rs @@ -39,7 +39,8 @@ use std::collections::HashMap; use super::container::SigElement; use crate::ShaderError::{self, Unsupported}; use crate::handoff::{Handoff, Access, VertexRead, own_accesses}; -use crate::ir::Program; +use crate::gfx10::{Fields, Operand}; +use crate::ir::{Program, Reg}; use crate::merged::{GsMessage, MergedGs, limits, message_of}; use crate::native::{NativeProgram, StageIo, Usage, VsOutput}; @@ -53,13 +54,13 @@ fn unsupported(what: &'static str) -> ShaderError { /// messages. #[derive(Debug, Clone, Default)] pub(crate) struct GsPlan { - /// Reads of an input vertex's record. - pub reads: HashMap<Site, VertexRead>, + /// Reads of an input vertex's record (two at a paired read). + pub reads: HashMap<Site, Vec<VertexRead>>, /// Writes to the program's own array: (first dword in it, dwords, first - /// VGPR). - pub stores: HashMap<Site, (u32, u32, u8)>, + /// VGPR), two at a paired write. + pub stores: HashMap<Site, Vec<(u32, u32, u8)>>, /// Reads back from it. - pub loads: HashMap<Site, (u32, u32, u8)>, + pub loads: HashMap<Site, Vec<(u32, u32, u8)>>, /// `GS_EMIT` and friends: the emit's number and the message. pub messages: HashMap<Site, (u32, GsMessage)>, /// Dwords of an output record. @@ -107,6 +108,34 @@ pub(crate) fn vertex_id_input() -> Vec<SigElement> { }] } +/// The merged wave's thread-count masks as no-ops: each half of the console +/// stage starts by setting `exec` to the lanes below its ES or GS thread +/// count (`s_bfm_b64 exec`, then `s_cselect_b64 exec, -1, exec` for a full +/// wave); a host invocation is one thread, which runs. +pub(crate) fn drop_thread_masks(code: &mut [u8], p: &Program) -> Result<(), ShaderError> { + const S_NOP: u32 = 0xBF80_0000; + const EXEC: u8 = 126; + let Some(entry) = p.blocks.first() else { return Ok(()) }; + for inst in &entry.insts { + if !inst.writes.iter().any(|w| w.0 == Reg::S(EXEC)) { + continue; + } + let mask = match (inst.name(), &inst.fields) { + ("s_bfm_b64", _) => true, + ("s_cselect_b64", Fields::Sop { src, .. }) => { + matches!(src.as_slice(), [Operand::Const(193), Operand::Scalar { code: EXEC, .. }]) + } + _ => false, + }; + if mask { + let at = inst.machine.offset; + let word = code.get_mut(at..at + 4).ok_or(unsupported("an exec mask outside the code"))?; + word.copy_from_slice(&S_NOP.to_le_bytes()); + } + } + Ok(()) +} + /// The ES half as a vertex shader: `code` with the record writes as exports /// (see the module notes) and the I/O of a vertex shader whose outputs are the /// record's rows. @@ -125,19 +154,28 @@ pub(crate) fn es_as_vertex_shader( } Ok(()) }; - for s in &handoff.es.stores { - let inst = &es.blocks[s.site.0].insts[s.site.1]; - let (row, ch) = (s.dword / 4, s.dword % 4); - if ch + s.count > 4 { - return Err(unsupported("a record write across two registers")); + // One export per write instruction: the two stores of a paired write + // (`ds_write2_*`) must fall in one record row. + let mut sites: Vec<_> = handoff.es.stores.iter().map(|s| s.site).collect(); + sites.dedup(); + for site in sites { + let inst = &es.blocks[site.0].insts[site.1]; + let (mut row, mut en, mut regs) = (None, 0u32, [0u32; 4]); + for s in handoff.es.stores.iter().filter(|s| s.site == site) { + let (r, ch) = (s.dword / 4, s.dword % 4); + let bits = ((1u32 << s.count) - 1) << ch; + if ch + s.count > 4 || row.is_some_and(|x| x != r) || en & bits != 0 { + return Err(unsupported("a record write across two registers")); + } + row = Some(r); + en |= bits; + for k in 0..s.count { + regs[(ch + k) as usize] = u32::from(s.reg) + k; + } } + let Some(row) = row else { continue }; // exp param<row>, the written VGPRs in their channels - let en = ((1u32 << s.count) - 1) << ch; let word0 = 0xF800_0000 | (32 + row) << 4 | en; - let mut regs = [0u32; 4]; - for k in 0..s.count { - regs[(ch + k) as usize] = u32::from(s.reg) + k; - } let word1 = regs[0] | regs[1] << 8 | regs[2] << 16 | regs[3] << 24; put(inst.machine.offset, &[word0, word1])?; } @@ -214,7 +252,17 @@ pub(crate) fn plan(gs: &Program, handoff: &Handoff, outputs: &[SigElement]) -> R let lo = writes.clone().map(|a| a.byte / 4).min().ok_or(unsupported("a geometry program that writes no output record"))?; let hi = writes.map(|a| a.byte / 4 + a.count).max().unwrap_or(lo); let array_dwords = emits * record_dwords; - if hi - lo != array_dwords || record_dwords == 0 { + // (the last row of a record may hold fewer than four values: the + // program need not write the dwords past them in the last record) + let last = outputs.iter().filter_map(|e| e.row).max().unwrap_or(0); + let last_cols = outputs + .iter() + .filter(|e| e.row == Some(last)) + .map(|e| u32::from(e.col) + u32::from(e.cols)) + .max() + .unwrap_or(4) + .min(4); + if record_dwords == 0 || hi - lo != array_dwords && hi - lo != array_dwords - 4 + last_cols { return Err(unsupported("the output records do not fit the output signature")); } let mut p = GsPlan { @@ -230,13 +278,12 @@ pub(crate) fn plan(gs: &Program, handoff: &Handoff, outputs: &[SigElement]) -> R return Err(unsupported("a geometry output access outside the records")); } let entry = (at - lo, a.count, a.reg); - if a.write { - p.stores.insert(a.site, entry); - } else { - p.loads.insert(a.site, entry); - } + let at = if a.write { &mut p.stores } else { &mut p.loads }; + at.entry(a.site).or_default().push(entry); + } + for r in &handoff.reads { + p.reads.entry(r.site).or_default().push(*r); } - p.reads = handoff.reads.iter().map(|r| (r.site, *r)).collect(); Ok(p) } @@ -356,6 +403,60 @@ pub(crate) mod tests { assert_eq!(outputs.iter().map(|o| (o.row, o.param)).collect::<Vec<_>>(), [(0, 0), (1, 1)]); } + /// The merged wave's thread-count prologue of the title's halves: + /// `s_bfe_i32 s0, s3, <count>`, `s_bfm_b64 exec, s0, 0`, `s_cmp_eq_u32 + /// s0, 64`, `s_cselect_b64 exec, -1, exec`. The two exec writes become + /// no-ops; other selects stay. + #[test] + fn the_thread_count_masks_become_no_ops() { + let words = [ + 0x8000_0000 | 0x28 << 23 | 255 << 8 | 3, // s_bfe_i32 s0, s3, lit + 0x0008_0008, + 0x92FE_8000, // s_bfm_b64 exec, s0, 0 + 0xBF06_C000, // s_cmp_eq_u32 s0, 64 + 0x85FE_7EC1, // s_cselect_b64 exec, -1, exec + 0x8586_807E, // s_cselect_b64 s[6:7], exec, 0 + S_ENDPGM, + ]; + let mut code = bytes(&words); + let before = program(&words); + let exec_writes = |p: &Program| { + p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.writes.iter().any(|w| w.0 == Reg::S(126))).count() + }; + assert_eq!(exec_writes(&before), 2); + drop_thread_masks(&mut code, &before).unwrap(); + let after = crate::ir::build(&code, true, 64).unwrap(); + assert_eq!(exec_writes(&after), 0); + let names: Vec<_> = after.blocks.iter().flat_map(|b| b.insts.iter().map(|i| i.name())).collect(); + assert_eq!(names, ["s_bfe_i32", "s_cmp_eq_u32", "s_cselect_b64", "s_endpgm"]); + } + + /// A paired write of the ES half is one export of both elements. + #[test] + fn a_paired_record_write_is_one_export() { + let es = [ + vop2(V_LSHLREV, 1, 133, 0), + ds(DS_WRITE2_B64, 1 << 8), + ds_regs2(1, 4, 6, 0), + ds(DS_WRITE_B32, 16), + ds_regs(1, 8, 0), + S_BARRIER, + S_SETPC, + ]; + let es_c = container_parts(&[(HwStage::Es, &bytes(&es)), (HwStage::Vs, &bytes(&[S_ENDPGM]))], &[]); + let (merged, h) = super::super::merged_halves(&es_c, &gs_container(3)).unwrap(); + let ir = crate::spill::build(&merged.es).unwrap(); + let vs = es_as_vertex_shader(&merged, &ir, &h).unwrap(); + let ir = crate::spill::build(&vs).unwrap(); + let exps: Vec<_> = ir.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "exp").collect(); + assert_eq!(exps.len(), 2); + // exp param0 with all four channels: v4, v5, v6, v7 + let at = exps[0].machine.offset; + let w0 = u32::from_le_bytes(vs.code[at..at + 4].try_into().unwrap()); + let w1 = u32::from_le_bytes(vs.code[at + 4..at + 8].try_into().unwrap()); + assert_eq!((w0 >> 4 & 0x3F, w0 & 0xF, w1), (32, 0xF, 4 | 5 << 8 | 6 << 16 | 7 << 24)); + } + #[test] fn the_gs_plan_numbers_the_emits_and_places_the_records() { let (_, h) = super::super::merged_halves(&es_container(), &gs_container(3)).unwrap(); @@ -367,7 +468,7 @@ pub(crate) mod tests { m.sort_by_key(|x| x.0); assert_eq!(m[2], (2, GsMessage::EmitCut { stream: 0 })); assert_eq!(p.stores.len(), 15); - assert!(p.stores.values().all(|s| s.0 % 4 == 0 && s.1 == 4)); + assert!(p.stores.values().flatten().all(|s| s.0 % 4 == 0 && s.1 == 4)); assert_eq!(p.reads.len(), 2); // Records that do not fill the signature's size are refused. let (_, h2) = super::super::merged_halves(&es_container(), &gs_container(2)).unwrap(); @@ -375,6 +476,35 @@ pub(crate) mod tests { assert!(plan(&gs2, &h2, &outs[..4]).is_err()); } + /// The title's last output row holds three values: the program writes + /// twelve bytes of it, and the last record ends a dword early. + #[test] + fn the_last_row_of_a_record_may_be_short() { + const DS_WRITE_B96: u32 = 0xde; + let mut w = gs_words(3); + // the last row of each record: 12 bytes + for n in 0..3 { + let k = w.iter().position(|&x| x == ds(DS_WRITE_B128, n * 80 + 64)).unwrap(); + w[k] = ds(DS_WRITE_B96, n * 80 + 64); + } + let short = osg1(&[ + ("SV_Position", 0, 1, 3, 0, 0xF), + ("TEXCOORD", 0, 0, 3, 1, 0xF), + ("TEXCOORD", 1, 0, 3, 2, 0xF), + ("TEXCOORD", 2, 0, 3, 3, 0xF), + ("TEXCOORD", 3, 0, 3, 4, 0x7), + ]); + let gs_c = container_parts(&[(HwStage::Gs, &bytes(&w))], &[(FourCC::OSG1, &short)]); + let (_, h) = super::super::merged_halves(&es_container(), &gs_c).unwrap(); + let gs = crate::spill::build(&native_of(&gs_c)).unwrap(); + let outs = signature_of(&gs_c, FourCC::OSG1); + let p = plan(&gs, &h, &outs).unwrap(); + assert_eq!((p.record_dwords, p.array_dwords), (20, 60)); + // With four values in that row, a dword is missing: refused. + let full = signature_of(&gs_container(3), FourCC::OSG1); + assert!(plan(&gs, &h, &full).is_err()); + } + /// A merged stage of synthetic programs comes out as a vertex shader and /// a geometry shader of the declared shapes, which the validator, where /// there is one, accepts. diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 1f19cc7..3ef9279 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -4214,50 +4214,62 @@ impl<'a> Lower<'a> { let Some(g) = x.gs.as_ref() else { return Ok(false); }; - let Fields::Ds { data, .. } = &inst.fields else { + let Fields::Ds { .. } = &inst.fields else { unreachable!() }; let guard = self.guard(site.0, site.1)?; let c = self.cur; - if let Some(r) = g.reads.get(&site) { - for k in 0..r.count { - let d = r.dword + k; - let (id, col) = (d / 4, d % 4); - let known = self.s.inputs.get(id as usize).is_some_and(|e| u32::from(e.cols) > col); - if !known { - return Err("a read of a record dword the signature does not have"); - } - let args = [ - self.s.m.i32(id), - self.s.m.i32(0), - self.s.m.i8(col as u8), - self.s.m.i32(u32::from(r.vertex)), - ]; - let i32t = self.s.t.i32; - let v = self.s.op(c, "loadInput.i32", Attr::ReadNone, i32t, 4, &args); - self.write(inst, Reg::V(r.reg + k as u8), v, guard); + if let Some(reads) = g.reads.get(&site) { + for r in reads { + for k in 0..r.count { + let d = r.dword + k; + let (id, col) = (d / 4, d % 4); + let known = self.s.inputs.get(id as usize).is_some_and(|e| u32::from(e.cols) > col); + if !known { + return Err("a read of a record dword the signature does not have"); + } + let args = [ + self.s.m.i32(id), + self.s.m.i32(0), + self.s.m.i8(col as u8), + self.s.m.i32(u32::from(r.vertex)), + ]; + let i32t = self.s.t.i32; + let v = self.s.op(c, "loadInput.i32", Attr::ReadNone, i32t, 4, &args); + self.write(inst, Reg::V(r.reg + k as u8), v, guard); + } } return Ok(true); } - if let Some(&(at, count, _)) = g.stores.get(&site) { - let vals = self.vgprs(inst, data.first().ok_or("an LDS write")?, count as u8)?; + if let Some(stores) = g.stores.get(&site) { + // (each element's data from its own operand: the plan has its + // first VGPR) + let mut vals = Vec::new(); + for &(at, count, reg) in stores { + let op = Operand::Vector { reg, dwords: count as u8 }; + for (k, v) in self.vgprs(inst, &op, count as u8)?.into_iter().enumerate() { + vals.push((at + k as u32, v)); + } + } let arr = self.s.lds(); let open = self.begin_guarded(guard); - for (k, v) in vals.into_iter().enumerate() { - let index = self.s.m.i32(at + k as u32); + for (at, v) in vals { + let index = self.s.m.i32(at); let p = self.s.m.element(self.cur, arr, index); self.s.m.store(self.cur, p, v); } self.end_guarded(open, &[]); return Ok(true); } - if let Some(&(at, count, reg)) = g.loads.get(&site) { + if let Some(loads) = g.loads.get(&site) { let arr = self.s.lds(); - for k in 0..count { - let index = self.s.m.i32(at + k); - let p = self.s.m.element(c, arr, index); - let v = self.s.m.load(c, p); - self.write(inst, Reg::V(reg + k as u8), v, guard); + for &(at, count, reg) in loads { + for k in 0..count { + let index = self.s.m.i32(at + k); + let p = self.s.m.element(c, arr, index); + let v = self.s.m.load(c, p); + self.write(inst, Reg::V(reg + k as u8), v, guard); + } } return Ok(true); } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0bc5590..b147072 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -324,7 +324,12 @@ pub fn merged_halves( what: "a container without the ES or GS program of a merged stage", }) }; - let merged = crate::merged::pair_es_gs(stage_of(es, HwStage::Es)?, stage_of(gs, HwStage::Gs)?)?; + let mut merged = crate::merged::pair_es_gs(stage_of(es, HwStage::Es)?, stage_of(gs, HwStage::Gs)?)?; + // (before anything numbers the instructions: the no-ops are dropped) + for half in [&mut merged.es, &mut merged.gs] { + let ir = crate::spill::build(half)?; + gs::drop_thread_masks(&mut half.code, &ir)?; + } let es_native = NativeProgram { layout: merged.layout.clone(), ..merged.es.clone() diff --git a/crates/victory-shader/src/handoff.rs b/crates/victory-shader/src/handoff.rs index ca6f5f6..608d517 100644 --- a/crates/victory-shader/src/handoff.rs +++ b/crates/victory-shader/src/handoff.rs @@ -124,18 +124,43 @@ impl<'a> Eval<'a> { fn inst(&self, inst: &Inst, v: Value, depth: u32) -> Lin { let opaque = Lin::of(Base::Opaque(v)); + // (a constant the code puts in an SGPR, such as a shift amount) + if let Fields::Sop { src, .. } = &inst.fields + && inst.name() == "s_mov_b32" + { + return src + .first() + .and_then(|o| self.operand(inst, o, depth)) + .filter(Lin::is_constant) + .unwrap_or(opaque); + } let Fields::Valu(f) = &inst.fields else { return opaque; }; let args: Option<Vec<Lin>> = f.src.iter().map(|s| self.operand(inst, s, depth)).collect(); - let Some(a) = args else { return opaque }; + let Some(mut a) = args else { return opaque }; let c = |l: &Lin| l.is_constant().then_some(l.add); + let plain = |x: &Lin| x.mul == 1 && x.add == 0; + // SDWA: a whole-dword result of word selects (`src1_sel:WORD_1` is + // the high half of a VGPR as it arrived). + if let Some(sd) = f.sdwa { + if sd.dst_sel != 6 || sd.sext != 0 || f.neg != 0 || f.abs != 0 { + return opaque; + } + for (x, sel) in a.iter_mut().zip(sd.src_sel) { + *x = match (sel, x.base) { + (6, _) => *x, + (4 | 5, _) if x.is_constant() => Lin::constant(x.add >> (16 * u32::from(sel - 4)) & 0xFFFF), + (4 | 5, Base::Input(reg)) if plain(x) => Lin::of(Base::Half { reg, high: sel == 5 }), + _ => return opaque, + }; + } + } let shifted = |x: Lin, s: u32| Lin { base: x.base, mul: x.mul.wrapping_shl(s), add: x.add.wrapping_shl(s), }; - let plain = |x: &Lin| x.mul == 1 && x.add == 0; match (inst.name(), a.as_slice()) { ("v_mov_b32", [x]) => *x, ("v_and_b32", [x, y]) | ("v_and_b32", [y, x]) if c(y) == Some(0xFFFF) => match x.base { @@ -143,6 +168,16 @@ impl<'a> Eval<'a> { Base::Half { .. } if plain(x) => *x, _ => opaque, }, + // (the shift first: `(v << n) & (0xFFFF << n)` is the low half, scaled) + ("v_and_b32", [x, y]) | ("v_and_b32", [y, x]) + if x.add == 0 && x.mul > 1 && x.mul.is_power_of_two() && c(y) == Some(0xFFFF * x.mul) => + { + match x.base { + Base::Input(reg) => Lin { base: Base::Half { reg, high: false }, ..*x }, + Base::Half { .. } => *x, + _ => opaque, + } + } ("v_lshrrev_b32", [s, x]) if c(s) == Some(16) => match x.base { Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: true }), _ => opaque, @@ -191,6 +226,34 @@ fn width(name: &str) -> Option<u32> { } } +/// The elements an LDS read or write moves: (byte offset from its address, +/// dwords). One for a single address (`ds_read_b32`...), two for a pair +/// (`ds_read2_b32`, `ds_write2_b64`...: each offset counts elements, ×64 for +/// `st64`); `None` for anything else (bytes and halves, atomics, exchanges). +/// The k-th element goes to or comes from the k-th data operand of a write, +/// and the k-th group of `dwords` destination VGPRs of a read. +fn elements(name: &str, offset0: u8, offset1: u8) -> Option<Vec<(u32, u32)>> { + if let Some(w) = width(name) { + return Some(vec![(u32::from(offset0) | u32::from(offset1) << 8, w)]); + } + let w = match name { + "ds_read2_b32" | "ds_read2st64_b32" | "ds_write2_b32" | "ds_write2st64_b32" => 1, + "ds_read2_b64" | "ds_read2st64_b64" | "ds_write2_b64" | "ds_write2st64_b64" => 2, + _ => return None, + }; + let scale = 4 * w * if name.contains("st64") { 64 } else { 1 }; + Some(vec![(u32::from(offset0) * scale, w), (u32::from(offset1) * scale, w)]) +} + +/// The first VGPR of element `k` of an LDS access (see [`elements`]). +fn element_reg(write: bool, data: &[Operand], dst: Option<Operand>, k: usize, dwords: u32) -> Option<u8> { + match (write, data.get(k), dst) { + (true, Some(&Operand::Vector { reg, .. }), _) => Some(reg), + (false, _, Some(Operand::Vector { reg, .. })) => Some(reg + (k as u32 * dwords) as u8), + _ => None, + } +} + /// Instructions that name LDS in the encoding but touch none. fn no_memory(name: &str) -> bool { name.starts_with("ds_swizzle") || name.contains("permute") || name == "ds_nop" @@ -290,15 +353,12 @@ pub fn es_record(p: &Program) -> Result<EsRecord, ShaderError> { if no_memory(name) { continue; } - let Some(count) = width(name).filter(|_| name.starts_with("ds_write") && !gds) else { + let Some(parts) = elements(name, *offset0, *offset1).filter(|_| name.starts_with("ds_write") && !gds) else { return Err(unsupported("an LDS access of the ES half other than a record write")); }; let Some(Operand::Vector { reg: a, .. }) = *addr else { return Err(unsupported("an LDS write without an address")); }; - let Some(Operand::Vector { reg: d, .. }) = data.first().copied() else { - return Err(unsupported("an LDS write without data")); - }; let lin = eval.value(inst.read(Reg::V(a)).ok_or(unsupported("an unread LDS address"))?, 0); if lin.is_constant() { return Err(unsupported("a record write at a constant address")); @@ -308,11 +368,14 @@ pub fn es_record(p: &Program) -> Result<EsRecord, ShaderError> { Some(first) if first == (lin.base, lin.mul) => {} Some(_) => return Err(unsupported("ES record writes at more than one base")), } - let byte = lin.add.wrapping_add(u32::from(*offset0) | u32::from(*offset1) << 8); - if byte % 4 != 0 { - return Err(unsupported("a record write off a dword")); + for (k, (off, count)) in parts.into_iter().enumerate() { + let reg = element_reg(true, data, None, k, count).ok_or(unsupported("an LDS write without data"))?; + let byte = lin.add.wrapping_add(off); + if byte % 4 != 0 { + return Err(unsupported("a record write off a dword")); + } + stores.push(Store { site: (b, i), dword: byte / 4, count, reg }); } - stores.push(Store { site: (b, i), dword: byte / 4, count, reg: d }); } } let dwords = stores.iter().map(|s| s.dword + s.count).max().ok_or(unsupported("an ES half that writes no record"))?; @@ -358,17 +421,17 @@ pub fn vertex_reads(p: &Program) -> Result<Vec<VertexRead>, ShaderError> { if lin.mul != 4 { return Err(unsupported("a vertex offset not scaled to bytes")); } - let Some(count) = width(name) else { + let Some(parts) = elements(name, *offset0, *offset1) else { return Err(unsupported("an LDS read of a vertex record that is not whole dwords")); }; - let Some(Operand::Vector { reg: d, .. }) = *dst else { - return Err(unsupported("an LDS read without a destination")); - }; - let byte = lin.add.wrapping_add(u32::from(*offset0) | u32::from(*offset1) << 8); - if byte % 4 != 0 { - return Err(unsupported("a vertex read off a dword")); + for (k, (off, count)) in parts.into_iter().enumerate() { + let reg = element_reg(false, &[], *dst, k, count).ok_or(unsupported("an LDS read without a destination"))?; + let byte = lin.add.wrapping_add(off); + if byte % 4 != 0 { + return Err(unsupported("a vertex read off a dword")); + } + out.push(VertexRead { site: (b, i), vertex: vertex as u8, dword: byte / 4, count, reg }); } - out.push(VertexRead { site: (b, i), vertex: vertex as u8, dword: byte / 4, count, reg: d }); } } Ok(out) @@ -391,8 +454,8 @@ pub struct Access { } /// The LDS accesses of a GS program that are not reads of input vertices, in -/// code order. Fails on any other LDS operation (atomics, paired reads and -/// writes, bytes and halves). +/// code order (a paired read or write is two). Fails on any other LDS +/// operation (atomics, bytes and halves). pub fn own_accesses(p: &Program) -> Result<Vec<Access>, ShaderError> { let eval = Eval::new(p); let mut out = Vec::new(); @@ -406,7 +469,7 @@ pub fn own_accesses(p: &Program) -> Result<Vec<Access>, ShaderError> { continue; } let write = name.starts_with("ds_write"); - let Some(count) = width(name).filter(|_| !gds) else { + let Some(parts) = elements(name, *offset0, *offset1).filter(|_| !gds) else { return Err(unsupported("an LDS operation of the GS half beyond whole-dword reads and writes")); }; let Some(Operand::Vector { reg: a, .. }) = *addr else { @@ -416,15 +479,14 @@ pub fn own_accesses(p: &Program) -> Result<Vec<Access>, ShaderError> { if matches!(lin.base, Base::Half { .. }) && !write { continue; // an input vertex ([`vertex_reads`]) } - let reg = match (write, data.first(), dst) { - (true, Some(Operand::Vector { reg, .. }), _) | (false, _, Some(Operand::Vector { reg, .. })) => *reg, - _ => return Err(unsupported("an LDS access without a register")), - }; - let byte = lin.add.wrapping_add(u32::from(*offset0) | u32::from(*offset1) << 8); - if byte % 4 != 0 { - return Err(unsupported("an LDS access off a dword")); + for (k, (off, count)) in parts.into_iter().enumerate() { + let reg = element_reg(write, data, *dst, k, count).ok_or(unsupported("an LDS access without a register"))?; + let byte = lin.add.wrapping_add(off); + if byte % 4 != 0 { + return Err(unsupported("an LDS access off a dword")); + } + out.push(Access { site: (b, i), write, base: lin.base, mul: lin.mul, byte, count, reg }); } - out.push(Access { site: (b, i), write, base: lin.base, mul: lin.mul, byte, count, reg }); } } Ok(out) @@ -491,6 +553,15 @@ pub(crate) mod tests { pub const DS_WRITE_B128: u32 = 0x0df; pub const DS_READ_B32: u32 = 0x36; pub const DS_READ_B128: u32 = 0x0ff; + pub const DS_WRITE2_B32: u32 = 0x0e; + pub const DS_WRITE2ST64_B32: u32 = 0x0f; + pub const DS_WRITE2_B64: u32 = 0x4e; + pub const DS_READ2_B32: u32 = 0x37; + + /// The second dword of a DS instruction with two data operands. + pub fn ds_regs2(addr: u32, data0: u32, data1: u32, dst: u32) -> u32 { + dst << 24 | data1 << 16 | data0 << 8 | addr + } pub fn program(words: &[u32]) -> Program { let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); @@ -522,6 +593,32 @@ pub(crate) mod tests { assert!(r.writes(3) && r.writes(4) && !r.writes(5)); } + /// The title's ES halves write their records with `ds_write2_b64`: two + /// stores at one site, each offset counting 8-byte elements. + #[test] + fn a_paired_write_is_two_stores_at_one_site() { + let words = [ + vop2(V_LSHLREV, 1, 133, 0), // v_lshlrev_b32 v1, 5, v0 + ds(DS_WRITE2_B64, 1 << 8), // offset0:0 offset1:1 + ds_regs2(1, 4, 6, 0), // v[4:5], v[6:7] + ds(DS_WRITE_B32, 16), + ds_regs(1, 8, 0), + S_BARRIER, + S_SETPC, + ]; + let r = es_record(&program(&words)).unwrap(); + let at: Vec<_> = r.stores.iter().map(|s| (s.dword, s.count, s.reg)).collect(); + assert_eq!(at, [(0, 2, 4), (2, 2, 6), (4, 1, 8)]); + assert_eq!(r.stores[0].site, r.stores[1].site); + assert_eq!(r.dwords, 5); + // st64: an offset counts 64 elements (of 4 bytes here). + let mut st64 = words; + st64[1] = ds(DS_WRITE2ST64_B32, 1 << 8); + let r = es_record(&program(&st64)).unwrap(); + let at: Vec<_> = r.stores.iter().map(|s| (s.dword, s.count, s.reg)).collect(); + assert_eq!(at, [(0, 1, 4), (64, 1, 6), (4, 1, 8)]); + } + #[test] fn an_es_half_that_does_not_hand_over_or_writes_oddly_is_refused() { let mut ends = es_words(); @@ -620,6 +717,47 @@ pub(crate) mod tests { assert_eq!(at, [(0, 0, 4, 4), (1, 4, 1, 8)]); } + /// The title's GS halves compute the offsets the other way round: vertex 0 + /// and 2 shift first and mask with `0xffff << 2`, vertex 1 is an SDWA + /// shift of the high word of v0 by an SGPR that holds 2; and they read + /// with `ds_read2_b32`. + #[test] + fn the_gs_half_reads_vertices_by_shifted_and_selected_halves() { + const SDWA: u32 = 0xF9; + let words = [ + vop2(V_LSHLREV, 3, 130, 0), // v_lshlrev_b32 v3, 2, v0 + vop2(V_AND, 10, 255, 3), // v_and_b32 v10, 0x3fffc, v3 + 0x3FFFC, + ds(DS_READ2_B32, 1 << 8), // ds_read2_b32 v[4:5], v10 offset1:1 + ds_regs(10, 0, 4), + 0xBE81_0382, // s_mov_b32 s1, 2 + // v_lshlrev_b32 v8, s1, v0 dst_sel:DWORD src0_sel:DWORD src1_sel:WORD_1 + vop2(V_LSHLREV, 8, SDWA, 0), + 1 | 6 << 8 | 6 << 16 | 1 << 23 | 5 << 24, + ds(DS_READ_B32, 8), // ds_read_b32 v6, v8 offset:8 + ds_regs(8, 0, 6), + vop2(V_LSHLREV, 9, 130, 1), // v_lshlrev_b32 v9, 2, v1 + vop2(V_AND, 7, 255, 9), // v_and_b32 v7, 0x3fffc, v9 + 0x3FFFC, + ds(DS_READ2_B32, 4 | 5 << 8), // ds_read2_b32 v[12:13], v7 offset0:4 offset1:5 + ds_regs(7, 0, 12), + S_ENDPGM, + ]; + let r = vertex_reads(&program(&words)).unwrap(); + let at: Vec<_> = r.iter().map(|r| (r.vertex, r.dword, r.count, r.reg)).collect(); + assert_eq!(at, [(0, 0, 1, 4), (0, 1, 1, 5), (1, 2, 1, 6), (2, 4, 1, 12), (2, 5, 1, 13)]); + // A byte select is no half: that read is the program's own memory. + let mut byte = words; + byte[7] = 1 | 6 << 8 | 6 << 16 | 1 << 23 | 1 << 24; + let r = vertex_reads(&program(&byte)).unwrap(); + assert!(r.iter().all(|r| r.vertex != 1)); + // A mask that is not the scaled half is no offset either. + let mut mask = words; + mask[2] = 0xFFFF; + let r = vertex_reads(&program(&mask)).unwrap(); + assert!(r.iter().all(|r| r.reg != 4)); + } + #[test] fn an_input_offset_is_scaled_to_bytes() { // v_lshlrev_b32 v2, 3, v2 instead of 2: not a dword offset. @@ -670,6 +808,24 @@ pub(crate) mod tests { assert!(own_accesses(&program(&gs_words())).unwrap().is_empty()); } + #[test] + fn a_paired_access_of_the_gs_halfs_own_memory_is_two() { + // v_lshlrev_b32 v2, 2, v15, ds_write2_b32 v2, v4, v5 offset0:2 + // offset1:3, ds_read2_b32 v[8:9], v2 offset0:2 offset1:3. + let words = [ + vop2(V_LSHLREV, 2, 130, 15), + ds(DS_WRITE2_B32, 2 | 3 << 8), + ds_regs2(2, 4, 5, 0), + ds(DS_READ2_B32, 2 | 3 << 8), + ds_regs(2, 0, 8), + S_ENDPGM, + ]; + let a = own_accesses(&program(&words)).unwrap(); + let at: Vec<_> = a.iter().map(|a| (a.write, a.byte, a.count, a.reg)).collect(); + assert_eq!(at, [(true, 8, 1, 4), (true, 12, 1, 5), (false, 8, 1, 8), (false, 12, 1, 9)]); + assert!(a[0].site == a[1].site && a[2].site == a[3].site && a[0].site != a[2].site); + } + #[test] fn the_handoff_pairs_reads_with_writes() { let h = handoff(&program(&es_words()), &program(&gs_words())).unwrap(); diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 7b747f6..318929e 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -1068,13 +1068,20 @@ impl<'a> Tracer<'a> { }) } - /// `hi` is `high` (0 for a table), possibly plus a carry. + /// `hi` is `high` (0 for a table), possibly plus a carry or masked to + /// its low bits. fn high_half(&self, hi: Term, high: Option<Value>) -> bool { let want = high.map_or(Term::Const(0), Term::Value); + // (`s_and_b32` with a mask of the low bits, 0xff for a 40-bit + // address, keeps a high half that fits it) + let low_mask = |t: Term| matches!(t, Term::Const(c) if c >= 0xff && c.wrapping_add(1).is_power_of_two()); hi == want || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and( |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0) )) + || matches!(hi, Term::Value(v) if self.sop2(v, &["s_and_b32"]).is_some_and( + |(_, [a, b])| a == want && low_mask(b) || b == want && low_mask(a) + )) } /// `hi` adds something (with carry) to `high`: `s_addc_u32` or @@ -3949,6 +3956,26 @@ pub(crate) mod tests { assert_eq!(r.scalar, [((0, 0), at(RUNTIME_TABLE, 0xB8))]); } + /// The title's geometry programs take the table's high half masked to its + /// low byte (a 40-bit address): `s_and_b32 s1, s9, 0xff`, then the load + /// through s[0:1] with s0 = s8. A mask that keeps fewer bits is refused. + #[test] + fn a_runtime_table_high_half_masked_to_its_low_bits_is_the_table() { + let words = |mask: u32| { + let and = 0x8000_0000 | 0x0e << 23 | 1 << 16 | 255 << 8 | 9; // s_and_b32 s1, s9, lit + let [load, offset, end] = load_b8(0); + [and, mask, 0xBE80_0308, load, offset, end] // s_mov_b32 s0, s8 + }; + let r = track_words(&words(0xFF), &[], HwStage::Gs); + assert_eq!(r.scalar.iter().map(|s| s.1).collect::<Vec<_>>(), [at(RUNTIME_TABLE, 0xB8)]); + let r = track_words(&words(0xFFFF), &[], HwStage::Gs); + assert_eq!(r.scalar.iter().map(|s| s.1).collect::<Vec<_>>(), [at(RUNTIME_TABLE, 0xB8)]); + for mask in [0x7F, 0xFF00] { + let err = track_error(&words(mask), &[], HwStage::Gs); + assert!(matches!(err, ShaderError::Unsupported { .. }), "{mask:#x}: {err:?}"); + } + } + /// Only a layout that holds both halves' parameters can say the first two /// user-data dwords are no one's: a geometry program tracked as it is, with /// the ES half unknown, still fails on a load through them. ``` </details> AI use: Claude Code with Claude Opus 5.5 ran the pack, wrote the harness and the patch, ran the tests and wrote this. The unit tests use synthetic programs. The title's shaders were only read on my machine.
Author
Owner

@⁠Revens2 on GitHub · 2026-11-25 04:39 UTC · original

Thank you, JRamos1993: this is exactly the check this PR lacked. I read each point against the code, applied the patch (it applied cleanly on the previous head), and made two corrections to it. The branch is rebased on the current main and pushed (head 10f4c02).

Point by point

  1. ES ds_write2_b64 in the LDS (all 195 ES halves): fixed. handoff::elements() gives one or two elements per access (offsets scaled by the element size, x64 for st64); es_record stores both, and es_as_vertex_shader makes one exp per write instruction, refusing a pair that spans two record rows. Unit tests: a paired write is two stores at one site, and one export of both elements.
  2. 0xff mask on the table's high half (GS resources): fixed. high_half accepts s_and_b32 with a mask of the low bits at least 0xff. A mask of 0x7f or 0xff00 is still refused (tested).
  3. Input-vertex reads not found: fixed, with two corrections.
    • Applied: shift-then-mask offsets, SDWA word selects (src1_sel:WORD_1), constants through s_mov_b32, paired reads.
    • Correction 1: 0xFFFF * mul overflows once the shift passes 16, and from a shift of 17 the mask no longer keeps a whole half, so the rewrite is not valid there. It now holds only for shifts of 1 to 16 (new test, shifts 17 and 31 give no vertex read).
    • Correction 2: an SDWA instruction with clamp or omod is not evaluated (the patch checked neg, abs, sext and dst_sel only).
  4. Paired accesses refused in own_accesses: fixed, each element has its own site entry; lower::gs_ds takes each element's data from its own operand. Test on ds_write2_b32 and ds_read2_b32.
  5. Thread-count prologue ("an opaque lane mask"): fixed, with a limit I could not check. drop_thread_masks turns the two exec writes of the entry block into s_nop, before anything numbers the instructions. This rests on a host invocation being one vertex or one primitive, which is a thread that runs. I tested it on a synthetic prologue only (the other s_cselect stays); whether every real prologue has this exact shape: non verifie.
  6. Short last row: fixed. plan accepts records that end at the last row's signature columns, and nothing else short of the full array (tested both ways).

Your numbers. The 195 programs, the 11,229 pairs and the 195 host pipelines are yours: I did not read the title's shaders, so I did not reproduce them (non verifie on my side). All tests here use synthetic GCN programs.

Checks on the new head. cargo build --workspace --locked and cargo test --workspace --locked --no-fail-fast -- --test-threads=4: 561 passed, 0 failed, 9 ignored. The rebase needed two small fixes: one conflict in the gs.rs tests (both sets kept) and a new valu_tests.rs test that needed gs: None in Parts. No game run for this update: the earlier run of this stack never created a geometry pipeline, and nothing here changes a path that scene reaches.

Codex finding "Share the merged-stage user-data block": decision kept, now with a measurement. The two halves keep one block each, because each translated half numbers its user-data dwords itself, so one shared block could have one stage overwrite the other's values. The risk was the 64 DWORD root-signature limit. Your run answers it: HostPipeline::new made 195 vertex+geometry+pixel pipelines and D3D12 refused none (that is a measurement of yours, on the title's own pairs, with the root parameters of the pair path). I did not measure it myself. If a pair is ever refused, the log says host root signature refused, and I will reopen this then, probably by sharing the block between the two halves.

Not tested (same as your list): the title's real ES/GS pairs, a draw with these shaders, and what the geometry looks like on screen.

AI use: Claude Code with Claude Sonnet 5.5 checked the points, adapted the patch, rebased and ran the tests. The patch itself is JRamos1993's (credited as co-author on the commit).

**@⁠Revens2** on GitHub · 2026-11-25 04:39 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#issuecomment-7153037584) Thank you, JRamos1993: this is exactly the check this PR lacked. I read each point against the code, applied the patch (it applied cleanly on the previous head), and made two corrections to it. The branch is rebased on the current `main` and pushed (head `10f4c02`). **Point by point** 1. **ES `ds_write2_b64` in the LDS (all 195 ES halves): fixed.** `handoff::elements()` gives one or two elements per access (offsets scaled by the element size, x64 for `st64`); `es_record` stores both, and `es_as_vertex_shader` makes one `exp` per write instruction, refusing a pair that spans two record rows. Unit tests: a paired write is two stores at one site, and one export of both elements. 2. **`0xff` mask on the table's high half (GS resources): fixed.** `high_half` accepts `s_and_b32` with a mask of the low bits at least `0xff`. A mask of `0x7f` or `0xff00` is still refused (tested). 3. **Input-vertex reads not found: fixed, with two corrections.** - Applied: shift-then-mask offsets, SDWA word selects (`src1_sel:WORD_1`), constants through `s_mov_b32`, paired reads. - Correction 1: `0xFFFF * mul` overflows once the shift passes 16, and from a shift of 17 the mask no longer keeps a whole half, so the rewrite is not valid there. It now holds only for shifts of 1 to 16 (new test, shifts 17 and 31 give no vertex read). - Correction 2: an SDWA instruction with `clamp` or `omod` is not evaluated (the patch checked `neg`, `abs`, `sext` and `dst_sel` only). 4. **Paired accesses refused in `own_accesses`: fixed**, each element has its own site entry; `lower::gs_ds` takes each element's data from its own operand. Test on `ds_write2_b32` and `ds_read2_b32`. 5. **Thread-count prologue ("an opaque lane mask"): fixed, with a limit I could not check.** `drop_thread_masks` turns the two `exec` writes of the entry block into `s_nop`, before anything numbers the instructions. This rests on a host invocation being one vertex or one primitive, which is a thread that runs. I tested it on a synthetic prologue only (the other `s_cselect` stays); whether every real prologue has this exact shape: `non verifie`. 6. **Short last row: fixed.** `plan` accepts records that end at the last row's signature columns, and nothing else short of the full array (tested both ways). **Your numbers.** The 195 programs, the 11,229 pairs and the 195 host pipelines are yours: I did not read the title's shaders, so I did not reproduce them (`non verifie` on my side). All tests here use synthetic GCN programs. **Checks on the new head.** `cargo build --workspace --locked` and `cargo test --workspace --locked --no-fail-fast -- --test-threads=4`: 561 passed, 0 failed, 9 ignored. The rebase needed two small fixes: one conflict in the `gs.rs` tests (both sets kept) and a new `valu_tests.rs` test that needed `gs: None` in `Parts`. No game run for this update: the earlier run of this stack never created a geometry pipeline, and nothing here changes a path that scene reaches. **Codex finding "Share the merged-stage user-data block": decision kept, now with a measurement.** The two halves keep one block each, because each translated half numbers its user-data dwords itself, so one shared block could have one stage overwrite the other's values. The risk was the 64 DWORD root-signature limit. Your run answers it: `HostPipeline::new` made 195 vertex+geometry+pixel pipelines and D3D12 refused none (that is a measurement of yours, on the title's own pairs, with the root parameters of the pair path). I did not measure it myself. If a pair is ever refused, the log says `host root signature refused`, and I will reopen this then, probably by sharing the block between the two halves. Not tested (same as your list): the title's real ES/GS pairs, a draw with these shaders, and what the geometry looks like on screen. AI use: Claude Code with Claude Sonnet 5.5 checked the points, adapted the patch, rebased and ran the tests. The patch itself is JRamos1993's (credited as co-author on the commit).
Author
Owner

@⁠JRamos1993 on GitHub · 2026-11-25 05:43 UTC · original

Your head 10f4c02 checked on the title's programs: same results as my patch, and the two corrections change nothing for these programs. Same machine and method as above:

  • Pack (victory translate --validate --list):
    • 25,382 programs validate, the same set as main 310c6eb, and each one's DXIL is byte-identical to main's (local DXIL hash on each validated line).
    • geometry 195 programs: 195 resources traced, 195 I/O raised, 195 stopped at GS emit.
    • No ES or GS failure lines.
  • Pairs: each GS container against every ES container of the same name, as before.
    • All 195 GS containers pair, translate and validate: 6,905 pairs.
    • The other 4,324 are refused by the pairing checks: 4,322 disagree about a user-data dword, 2 read a record dword the ES half never writes.
  • Same DXIL as my patch: for each GS container with the first ES of its name that translates, the vertex and geometry DXIL are byte-identical between my patch (on 64f781d) and this head, for all 195 pairs.
    • So the 195 vertex+geometry+pixel host pipelines measured above apply to this head unchanged.
    • I did not rerun that GPU step tonight, to keep one GPU job at a time on this machine.

Your two restrictions (shifts 1–16, SDWA without clamp or omod) don't touch the title's idioms: its offsets shift by 2, and its SDWA shift has neither.

AI use: Claude Code with Claude Opus 5.5 ran the checks and wrote this. Nothing from the title is in it.

**@⁠JRamos1993** on GitHub · 2026-11-25 05:43 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#issuecomment-7154079130) **Your head `10f4c02` checked on the title's programs: same results as my patch, and the two corrections change nothing for these programs.** Same machine and method as above: - **Pack** (`victory translate --validate --list`): - 25,382 programs validate, the same set as `main` `310c6eb`, and each one's DXIL is byte-identical to `main`'s (local DXIL hash on each validated line). - `geometry 195 programs: 195 resources traced, 195 I/O raised, 195 stopped at GS emit`. - No ES or GS failure lines. - **Pairs:** each GS container against every ES container of the same name, as before. - All 195 GS containers pair, translate and validate: 6,905 pairs. - The other 4,324 are refused by the pairing checks: 4,322 disagree about a user-data dword, 2 read a record dword the ES half never writes. - **Same DXIL as my patch:** for each GS container with the first ES of its name that translates, the vertex and geometry DXIL are byte-identical between my patch (on `64f781d`) and this head, for all 195 pairs. - So the 195 vertex+geometry+pixel host pipelines measured above apply to this head unchanged. - I did not rerun that GPU step tonight, to keep one GPU job at a time on this machine. Your two restrictions (shifts 1–16, SDWA without clamp or omod) don't touch the title's idioms: its offsets shift by 2, and its SDWA shift has neither. AI use: Claude Code with Claude Opus 5.5 ran the checks and wrote this. Nothing from the title is in it.
Author
Owner

@⁠Revens2 on GitHub · 2026-11-25 07:10 UTC · original

Rebased on main (a26859f), stacked on #381; head now 77b24c1. Conflict in the test module of emit/gs.rs (two tests added at the same spot), resolved by keeping both; the earlier "rebase fix" test commit is now part of #381. Tree is identical to the previous head apart from the main changes. cargo build --workspace --locked ok; cargo test --workspace --locked -- --test-threads=4: 584 passed, 0 failed, 10 ignored (one earlier run of the same command had a victory-gpu lib failure while the machine was loaded; two reruns passed, cause not identified). No game run. Ready for another review pass.

**@⁠Revens2** on GitHub · 2026-11-25 07:10 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#issuecomment-7155564348) Rebased on main (a26859f), stacked on #381; head now 77b24c1. Conflict in the test module of `emit/gs.rs` (two tests added at the same spot), resolved by keeping both; the earlier "rebase fix" test commit is now part of #381. Tree is identical to the previous head apart from the main changes. `cargo build --workspace --locked` ok; `cargo test --workspace --locked -- --test-threads=4`: 584 passed, 0 failed, 10 ignored (one earlier run of the same command had a `victory-gpu` lib failure while the machine was loaded; two reruns passed, cause not identified). No game run. Ready for another review pass.
Author
Owner

@⁠Revens2 on GitHub · 2026-11-25 09:35 UTC · original

@⁠codex review (head rebased on origin/main; earlier findings were addressed before the rebase)

**@⁠Revens2** on GitHub · 2026-11-25 09:35 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#issuecomment-7158535166) @⁠codex review (head rebased on origin/main; earlier findings were addressed before the rebase)
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 09:35 UTC · original

Codex Review: Something went wrong. Try again later by commenting “@⁠codex review”.

Setup repeatedly failed. Update the setup script or commit, then try again later.
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@⁠codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@⁠codex address that feedback".

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 09:35 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#issuecomment-7158542345) Codex Review: Something went wrong. Try again later by commenting “@⁠codex review”. ``` Setup repeatedly failed. Update the setup script or commit, then try again later. ``` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@⁠codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@⁠codex address that feedback". </details>
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:25 UTC · original · edited 2026-11-25 09:35 UTC

Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-25T09:35:44.100347Z
We couldn’t complete this review. Comment @codex review to try again.
77b24c1 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@⁠codex review" or "@⁠codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:25 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#issuecomment-7148495310) · edited 2026-11-25 09:35 UTC <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"77b24c19917b3d8ad95baa00af32b4a30a90940d","has_any_findings":true,"has_unresolved_findings":true,"status":"failed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ❌ Failed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ❌ **Failed** <relative-time datetime="2026-11-25T09:35:44.100347Z">2026-11-25T09:35:44.100347Z</relative-time><br/>We couldn’t complete this review. Comment `@codex review` to try again. | `77b24c1` | Manual request | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@⁠codex review" or "@⁠codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
@ -4359,0 +4468,4 @@
let p = self.s.m.element(c, arr, index);
let bits = self.s.m.load(c, p);
let (name, value) = if e.comp == 9 {
("storeOutput.f32", self.as_float(bits))
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:33 UTC · original

P2 Badge Convert half-precision geometry outputs

When the geometry output signature marks an element as 16-bit (e.half), this path still reads a full record dword and forwards its raw bits through a 32-bit output operation. Unlike the regular export path, it never unpacks or widens the half value, so GS varyings or positions from such signatures are corrupted; reject these outputs or convert them before storing.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:33 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#discussion_r4688548693) **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Convert half-precision geometry outputs** When the geometry output signature marks an element as 16-bit (`e.half`), this path still reads a full record dword and forwards its raw bits through a 32-bit output operation. Unlike the regular export path, it never unpacks or widens the half value, so GS varyings or positions from such signatures are corrupted; reject these outputs or convert them before storing. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
@ -4818,6 +4953,9 @@ impl<'a> Lower<'a> {
.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
Ok(())
}
Fields::Sopp { .. } if name == "s_sendmsg" && self.x.gs.is_some() => {
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:33 UTC · original

P2 Badge Handle halting geometry messages

When a GS uses s_sendmsghalt for GS_EMIT or GS_CUT, planning recognizes the message and assigns it an output record, but this dispatch handles only s_sendmsg. The halting instruction falls through as a no-op, so the translated shader omits the emission or cut while still declaring the vertex maximum; handle both opcodes or refuse the halting form.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:33 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#discussion_r4688548705) **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Handle halting geometry messages** When a GS uses `s_sendmsghalt` for `GS_EMIT` or `GS_CUT`, planning recognizes the message and assigns it an output record, but this dispatch handles only `s_sendmsg`. The halting instruction falls through as a no-op, so the translated shader omits the emission or cut while still declaring the vertex maximum; handle both opcodes or refuse the halting form. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
@ -5459,6 +5597,19 @@ impl<'a> Lower<'a> {
unreachable!()
};
let name = inst.name();
if self.scalar.get(&site).is_some_and(|a| a.param == RUNTIME_TABLE) {
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:33 UTC · original

P2 Badge Preserve non-base runtime-table loads

Whenever a GS reads the runtime table, this branch replaces every scalar destination with zero without checking the load offset or proving that the value is used only as the relocatable LDS base. If a table field also feeds an output value, condition, or other computation, the pair is still accepted but silently produces results based on zero; limit this substitution to proven base-only uses or refuse other accesses.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:33 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#discussion_r4688548712) **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Preserve non-base runtime-table loads** Whenever a GS reads the runtime table, this branch replaces every scalar destination with zero without checking the load offset or proving that the value is used only as the relocatable LDS base. If a table field also feeds an output value, condition, or other computation, the pair is still accepted but silently produces results based on zero; limit this substitution to proven base-only uses or refuse other accesses. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
@ -367,3 +383,4 @@
(None, None) => return refuse("no vertex or mesh shader", shaders),
};
let mut stages = vec![first];
stages.extend(merged.as_ref().map(|m| (&m.1, D3D12_SHADER_VISIBILITY_GEOMETRY)));
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:33 UTC · original

P2 Badge Share the merged-stage user-data block

The ES and GS halves share one user-data layout, but adding the translated GS here sends it through the per-stage root-parameter construction, which allocates a second root-constants block for the same registers. If those duplicated constants plus the other parameters exceed D3D12's 64-DWORD root-signature limit, serialization fails and HostPipeline::new drops every draw for that pair; share the merged block or otherwise keep it within the limit.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:33 UTC · [original](https://github.com/fxceless/victory-fork/pull/400#discussion_r4688548719) **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Share the merged-stage user-data block** The ES and GS halves share one user-data layout, but adding the translated GS here sends it through the per-stage root-parameter construction, which allocates a second root-constants block for the same registers. If those duplicated constants plus the other parameters exceed D3D12's 64-DWORD root-signature limit, serialization fails and `HostPipeline::new` drops every draw for that pair; share the merged block or otherwise keep it within the limit. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
This pull request has changes conflicting with the target branch.
  • crates/victory-shader/src/emit/lower.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/400/head:github-bot/gh-400'
git switch 'github-bot/gh-400'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-400'
git switch 'github-bot/gh-400'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-400'
git switch 'github-bot/gh-400'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-400'
git switch 'main'
git merge --squash 'github-bot/gh-400'
git switch 'main'
git merge --ff-only 'github-bot/gh-400'
git switch 'main'
git merge 'github-bot/gh-400'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.