Shaders: model the ES to GS handoff, check the ES half too (#312) #373

Open
github-bot wants to merge 6 commits from github-bot/gh-373 into main AGit
Owner

@⁠Revens2 on GitHub · 2026-11-25 00:02 UTC · original
Revens2:fix/issue-312 → main · +1622 −13 · 9 files · 6 commits · open

Step 3 of #138, for #312. Stacked on #311 (#367), itself on #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

  • handoff::es_record: from the ES program, the record it writes to LDS (ds_write_b32 .. b128 at one base address with constant offsets: dwords, VGPRs, highest dword), whether an s_barrier precedes the handover, and a refusal of an ES half that does not leave through s_setpc_b64, reads or does atomics on LDS, writes at two bases, off a dword, or writes nothing.
  • handoff::vertex_reads: from the GS program, its reads of input vertices: an address that is the low or high half of v0 or v1 (v_and_b32 0xffff, v_lshrrev_b32 16, v_bfe_u32, scaled and offset) is vertex 0, 1 or 2's record. A fourth vertex is refused; reads at other addresses are the GS half's own output memory and left to the output step.
  • handoff::handoff checks the GS half reads only dwords the ES half writes. emit::merged_halves is the pairing entry point: pair, ES half traced / raised / structured with the merged layout, then the handoff; translate_merged_gs goes through it before stopping at GS emit.
  • victory translate: ES programs get their own es line (traced, raised, writing a record, largest record) and no longer fall out of the batch silently.

What the LDS in a graphics stage comes to (reading emit/lower.rs, not tested): LDS exists in the lowering only where a stage declares groupshared memory (compute, mesh). The handoff does not need it: the ES records become vertex outputs, the GS reads become input loads, and the barrier is the stage boundary. That is the model the next step emits.

Tested

  • Synthetic GCN programs: an ES record of a 16-byte and a 4-byte write, refused ES halves (no handover, LDS read, two bases, no write), GS reads of vertices 0 and 1 through the halves of v0, reads at other addresses ignored, a fourth vertex refused, a read past the record refused, and containers going through merged_halves and translate_merged_gs.
  • cargo build --workspace --locked, cargo test --workspace --locked --no-fail-fast -- --test-threads=4: 523 passed, 0 failed, 7 ignored (Windows).

Not tested / assumed

  • The GS input convention (offsets of vertex 0 and 1 in the halves of v0, vertex 2 in v1) is the ISA's for a merged stage, not checked against a title program; neither is that the ES half's address and the GS half's offset are in the same units. Whether the title's programs hit these forms is only visible by running victory translate over the title, which I did not.
  • No emission yet (#313), nothing bound by the host (#314), not run in game.

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

**@⁠Revens2** on GitHub · 2026-11-25 00:02 UTC · [original](https://github.com/fxceless/victory-fork/pull/373) `Revens2:fix/issue-312` → `main` · +1622 −13 · 9 files · 6 commits · open Step 3 of #138, for #312. **Stacked on #311 (#367), itself on #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** - `handoff::es_record`: from the ES program, the record it writes to LDS (`ds_write_b32` .. `b128` at one base address with constant offsets: dwords, VGPRs, highest dword), whether an `s_barrier` precedes the handover, and a refusal of an ES half that does not leave through `s_setpc_b64`, reads or does atomics on LDS, writes at two bases, off a dword, or writes nothing. - `handoff::vertex_reads`: from the GS program, its reads of input vertices: an address that is the low or high half of v0 or v1 (`v_and_b32 0xffff`, `v_lshrrev_b32 16`, `v_bfe_u32`, scaled and offset) is vertex 0, 1 or 2's record. A fourth vertex is refused; reads at other addresses are the GS half's own output memory and left to the output step. - `handoff::handoff` checks the GS half reads only dwords the ES half writes. `emit::merged_halves` is the pairing entry point: pair, ES half traced / raised / structured with the merged layout, then the handoff; `translate_merged_gs` goes through it before stopping at `GS emit`. - `victory translate`: ES programs get their own `es` line (traced, raised, writing a record, largest record) and no longer fall out of the batch silently. **What the LDS in a graphics stage comes to (reading `emit/lower.rs`, not tested)**: LDS exists in the lowering only where a stage declares groupshared memory (compute, mesh). The handoff does not need it: the ES records become vertex outputs, the GS reads become input loads, and the barrier is the stage boundary. That is the model the next step emits. **Tested** - Synthetic GCN programs: an ES record of a 16-byte and a 4-byte write, refused ES halves (no handover, LDS read, two bases, no write), GS reads of vertices 0 and 1 through the halves of v0, reads at other addresses ignored, a fourth vertex refused, a read past the record refused, and containers going through `merged_halves` and `translate_merged_gs`. - `cargo build --workspace --locked`, `cargo test --workspace --locked --no-fail-fast -- --test-threads=4`: 523 passed, 0 failed, 7 ignored (Windows). **Not tested / assumed** - The GS input convention (offsets of vertex 0 and 1 in the halves of v0, vertex 2 in v1) is the ISA's for a merged stage, not checked against a title program; neither is that the ES half's address and the GS half's offset are in the same units. Whether the title's programs hit these forms is only visible by running `victory translate` over the title, which I did not. - No emission yet (#313), nothing bound by the host (#314), not run in game. **AI use** Written with Claude Code (Claude Sonnet 5.5). The tests are synthetic programs; no title shaders or game files were read.
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]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:41:54 +00:00
Author
Owner

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

All four findings fixed in 9acd8f0 (with tests), on top of the #311 fixes (d8e53e1):

  • Every ES exit hands off: a reachable s_endpgm now refuses the ES half (an ES half that does not hand over to the GS half); an end nothing reaches is ignored.
  • BFE offsets: v_bfe_u32 offsets are read in five bits, so 48 is the high half like 16 and 32 the low half.
  • Barrier flag: EsRecord.barrier is true only when an s_barrier precedes every reachable handover (must-analysis over the CFG); a barrier on one arm or in unreachable code does not count.
  • victory translate: an ES half whose record analysis fails is now counted as a failure (ES record: ...) and listed with --list.

Workspace build and cargo test --workspace --locked --no-fail-fast -- --test-threads=4 on the stacked head: 534 passed, 0 failed, 7 ignored.

**@⁠Revens2** on GitHub · 2026-11-25 00:18 UTC · [original](https://github.com/fxceless/victory-fork/pull/373#issuecomment-7148374570) All four findings fixed in 9acd8f0 (with tests), on top of the #311 fixes (d8e53e1): - **Every ES exit hands off**: a reachable `s_endpgm` now refuses the ES half (`an ES half that does not hand over to the GS half`); an end nothing reaches is ignored. - **BFE offsets**: `v_bfe_u32` offsets are read in five bits, so 48 is the high half like 16 and 32 the low half. - **Barrier flag**: `EsRecord.barrier` is true only when an `s_barrier` precedes every reachable handover (must-analysis over the CFG); a barrier on one arm or in unreachable code does not count. - **`victory translate`**: an ES half whose record analysis fails is now counted as a failure (`ES record: ...`) and listed with `--list`. Workspace build and `cargo test --workspace --locked --no-fail-fast -- --test-threads=4` on the stacked head: 534 passed, 0 failed, 7 ignored.
Author
Owner

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

Rebased on main (a26859f), stacked on #367; head now 5386d73. No new conflicts. cargo build --workspace --locked ok; cargo test -p victory-shader -p victory-gpu --locked: 137 + 247 passed, 0 failed. Ready for another review pass.

**@⁠Revens2** on GitHub · 2026-11-25 07:10 UTC · [original](https://github.com/fxceless/victory-fork/pull/373#issuecomment-7155563642) Rebased on main (a26859f), stacked on #367; head now 5386d73. No new conflicts. `cargo build --workspace --locked` ok; `cargo test -p victory-shader -p victory-gpu --locked`: 137 + 247 passed, 0 failed. 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/373#issuecomment-7158534120) @⁠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/373#issuecomment-7158539844) 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:02 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:37.582392Z
We couldn’t complete this review. Comment @codex review to try again.
5386d73 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:02 UTC · [original](https://github.com/fxceless/victory-fork/pull/373#issuecomment-7148073324) · edited 2026-11-25 09:35 UTC <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"5386d73416070c7c9753af00087abe91156834a8","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:37.582392Z">2026-11-25T09:35:37.582392Z</relative-time><br/>We couldn’t complete this review. Comment `@codex review` to try again. | `5386d73` | 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>
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:08 UTC · original
On crates/victory-shader/src/handoff.rs line 235 (outdated):

@@ -0,0 +1,497 @@
+//! The ES to GS handoff of a merged geometry stage ([`crate::merged`]), as
+//! the code of the two halves shows it.
+//!
+//! The ES half fetches a vertex, writes it to LDS as a fixed-size record
+//! (`ds_write_b32` .. `ds_write_b128` at one base address and constant
+//! offsets), waits at `s_barrier` and leaves through `s_setpc_b64` into the
+//! GS half. The GS half reads the records of the vertices of its primitive
+//! (`ds_read_b32` .. `ds_read_b128`) at the offset the hardware gives it for
+//! each vertex.
+//!
+//! A host vertex shader has no LDS and a host geometry shader no way to read
+//! another stage's memory, so the handoff is modeled, not run: what the ES
+//! half writes at record dword k is output k of the vertex, and what the GS
+//! half reads at vertex v, record dword k is input k of vertex v. This module
+//! finds those writes and reads. Emission is [`crate::emit`]'s.
+//!
+//! What is assumed (the ISA's convention for a merged stage, not checked
+//! against a title program):
+//!
+//! * The GS half gets the ES-ring offsets of its vertices packed two to a
+//!   VGPR: vertex 0 in the low half of v0, vertex 1 in its high half, vertex
+//!   2 in the low half of v1 ([`VERTEX_OFFSETS`]). A read whose address is
+//!   such a half (scaled, plus constants) is a read of that vertex's record;
+//!   a read at any other address is the GS half's own output memory.
+//! * The ES half's writes all use one base address (its vertex's slot) and
+//!   constant offsets, the same units as the GS half's.
+
+use std::collections::{BTreeSet, HashMap};
+
+use crate::ShaderError::{self, Unsupported};
+use crate::gfx10::{Fields, Operand};
+use crate::ir::{Exit, Inst, Program, Reg, Value};
+
+/// Where the GS half finds the ES-ring offset of input vertex `n`: the VGPR
+/// and whether it is the high half.
+pub const VERTEX_OFFSETS: [(u8, bool); 4] = [(0, false), (0, true), (1, false), (1, true)];
+
+/// Triangles in.
+pub const MAX_VERTICES: usize = 3;
+
+type Site = (usize, usize);
+
+/// What a value is, as `base * mul + add` in wrapping 32-bit arithmetic.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Base {
+    /// No base: `add` is the whole value.
+    Constant,
+    /// A VGPR as it arrived.
+    Input(u8),
+    /// The low or high 16 bits of an arrived VGPR.
+    Half { reg: u8, high: bool },
+    /// Anything else, named by the value that holds it.
+    Opaque(Value),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Lin {
+    pub base: Base,
+    pub mul: u32,
+    pub add: u32,
+}
+
+impl Lin {
+    fn constant(add: u32) -> Lin {
+        Lin { base: Base::Constant, mul: 0, add }
+    }
+
+    fn of(base: Base) -> Lin {
+        Lin { base, mul: 1, add: 0 }
+    }
+
+    fn is_constant(&self) -> bool {
+        self.base == Base::Constant
+    }
+}
+
+struct Eval<'a> {
+    p: &'a Program,
+    defs: HashMap<Value, Site>,
+    inputs: HashMap<Value, u8>,
+}
+
+impl<'a> Eval<'a> {
+    fn new(p: &'a Program) -> Self {
+        let mut defs = HashMap::new();
+        for (b, block) in p.blocks.iter().enumerate() {
+            for (i, inst) in block.insts.iter().enumerate() {
+                for &(_, v) in &inst.writes {
+                    defs.insert(v, (b, i));
+                }
+            }
+        }
+        let inputs = p
+            .inputs
+            .iter()
+            .filter_map(|&(reg, v)| match reg {
+                Reg::V(r) => Some((v, r)),
+                _ => None,
+            })
+            .collect();
+        Eval { p, defs, inputs }
+    }
+
+    fn value(&self, v: Value, depth: u32) -> Lin {
+        if let Some(&r) = self.inputs.get(&v) {
+            return Lin::of(Base::Input(r));
+        }
+        match self.defs.get(&v) {
+            Some(&(b, i)) if depth < 32 => self.inst(&self.p.blocks[b].insts[i], v, depth),
+            _ => Lin::of(Base::Opaque(v)),
+        }
+    }
+
+    fn operand(&self, inst: &Inst, op: &Operand, depth: u32) -> Option<Lin> {
+        match *op {
+            Operand::Const(c @ 128..=192) => Some(Lin::constant(u32::from(c) - 128)),
+            Operand::Const(c @ 193..=208) => Some(Lin::constant(0u32.wrapping_sub(u32::from(c) - 192))),
+            Operand::Literal(l) => Some(Lin::constant(l)),
+            Operand::Vector { reg, .. } => Some(self.value(inst.read(Reg::V(reg))?, depth + 1)),
+            Operand::Scalar { code, .. } => Some(self.value(inst.read(Reg::S(code))?, depth + 1)),
+            _ => None,
+        }
+    }
+
+    fn inst(&self, inst: &Inst, v: Value, depth: u32) -> Lin {
+        let opaque = Lin::of(Base::Opaque(v));
+        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 c = |l: &Lin| l.is_constant().then_some(l.add);
+        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 {
+                Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: false }),
+                Base::Half { .. } if plain(x) => *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,
+            },
+            ("v_bfe_u32", [x, off, width]) if c(width) == Some(16) && c(off).is_some_and(|o| o % 16 == 0) => {
+                match x.base {
+                    Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: c(off) == Some(16) }),
+                    _ => opaque,
+                }
+            }
+            ("v_lshlrev_b32", [s, x]) if c(s).is_some_and(|s| s < 32) => {
+                if x.is_constant() {
+                    Lin::constant(x.add.wrapping_shl(c(s).unwrap()))
+                } else {
+                    shifted(*x, c(s).unwrap())
+                }
+            }
+            ("v_add_nc_u32" | "v_add_u32" | "v_add_co_u32", [x, y]) => match (c(x), c(y)) {
+                (Some(p), Some(q)) => Lin::constant(p.wrapping_add(q)),
+                (Some(k), None) => Lin { add: y.add.wrapping_add(k), ..*y },
+                (None, Some(k)) => Lin { add: x.add.wrapping_add(k), ..*x },
+                _ => opaque,
+            },
+            ("v_mul_u32_u24", [x, y]) => match (c(x), c(y)) {
+                (Some(p), Some(q)) => Lin::constant(p.wrapping_mul(q)),
+                (None, Some(k)) | (Some(k), None) => {
+                    let x = if c(x).is_some() { y } else { x };
+                    Lin { base: x.base, mul: x.mul.wrapping_mul(k), add: x.add.wrapping_mul(k) }
+                }
+                _ => opaque,
+            },
+            _ => opaque,
+        }
+    }
+}
+
+/// How many dwords an LDS read or write moves, from its name.
+fn width(name: &str) -> Option<u32> {
+    match name {
+        "ds_read_b32" | "ds_write_b32" => Some(1),
+        "ds_read_b64" | "ds_write_b64" => Some(2),
+        "ds_read_b96" | "ds_write_b96" => Some(3),
+        "ds_read_b128" | "ds_write_b128" => Some(4),
+        _ => 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"
+}
+
+fn unsupported(what: &'static str) -> ShaderError {
+    Unsupported { offset: 0, what }
+}
+
+/// A record write of the ES half: VGPRs `reg..reg + count` go to record
+/// dwords `dword..dword + count`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Store {
+    pub site: Site,
+    pub dword: u32,
+    pub count: u32,
+    pub reg: u8,
+}
+
+/// The ES half's record.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct EsRecord {
+    pub stores: Vec<Store>,
+    /// Dwords of the record: past the highest one written.
+    pub dwords: u32,
+    /// An `s_barrier` comes before the handover.
+    pub barrier: bool,
+}
+
+impl EsRecord {
+    /// Whether some store writes record dword `dword`.
+    pub fn writes(&self, dword: u32) -> bool {
+        self.stores.iter().any(|s| (s.dword..s.dword + s.count).contains(&dword))
+    }
+}
+
+/// The records an ES program writes.
+///
+/// Fails when it does not end by handing over to the GS half
+/// (`s_setpc_b64`), touches LDS in any way but whole-dword record writes,
+/// writes at more than one base, or writes nothing.
+pub fn es_record(p: &Program) -> Result<EsRecord, ShaderError> {
+    if !p.blocks.iter().any(|b| b.exit == Exit::Indirect) {

P2 Badge Require every reachable ES exit to hand off

If an ES CFG has one reachable s_setpc_b64 exit and another reachable s_endpgm exit, this check succeeds, so es_record and handoff accept a pair even though that branch never transfers the record to GS. Validate that every reachable terminal path hands off, rather than only requiring one indirect exit.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:08 UTC · [original](https://github.com/fxceless/victory-fork/pull/373#discussion_r4688365624) On `crates/victory-shader/src/handoff.rs` line 235 (outdated): ```diff @@ -0,0 +1,497 @@ +//! The ES to GS handoff of a merged geometry stage ([`crate::merged`]), as +//! the code of the two halves shows it. +//! +//! The ES half fetches a vertex, writes it to LDS as a fixed-size record +//! (`ds_write_b32` .. `ds_write_b128` at one base address and constant +//! offsets), waits at `s_barrier` and leaves through `s_setpc_b64` into the +//! GS half. The GS half reads the records of the vertices of its primitive +//! (`ds_read_b32` .. `ds_read_b128`) at the offset the hardware gives it for +//! each vertex. +//! +//! A host vertex shader has no LDS and a host geometry shader no way to read +//! another stage's memory, so the handoff is modeled, not run: what the ES +//! half writes at record dword k is output k of the vertex, and what the GS +//! half reads at vertex v, record dword k is input k of vertex v. This module +//! finds those writes and reads. Emission is [`crate::emit`]'s. +//! +//! What is assumed (the ISA's convention for a merged stage, not checked +//! against a title program): +//! +//! * The GS half gets the ES-ring offsets of its vertices packed two to a +//! VGPR: vertex 0 in the low half of v0, vertex 1 in its high half, vertex +//! 2 in the low half of v1 ([`VERTEX_OFFSETS`]). A read whose address is +//! such a half (scaled, plus constants) is a read of that vertex's record; +//! a read at any other address is the GS half's own output memory. +//! * The ES half's writes all use one base address (its vertex's slot) and +//! constant offsets, the same units as the GS half's. + +use std::collections::{BTreeSet, HashMap}; + +use crate::ShaderError::{self, Unsupported}; +use crate::gfx10::{Fields, Operand}; +use crate::ir::{Exit, Inst, Program, Reg, Value}; + +/// Where the GS half finds the ES-ring offset of input vertex `n`: the VGPR +/// and whether it is the high half. +pub const VERTEX_OFFSETS: [(u8, bool); 4] = [(0, false), (0, true), (1, false), (1, true)]; + +/// Triangles in. +pub const MAX_VERTICES: usize = 3; + +type Site = (usize, usize); + +/// What a value is, as `base * mul + add` in wrapping 32-bit arithmetic. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Base { + /// No base: `add` is the whole value. + Constant, + /// A VGPR as it arrived. + Input(u8), + /// The low or high 16 bits of an arrived VGPR. + Half { reg: u8, high: bool }, + /// Anything else, named by the value that holds it. + Opaque(Value), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Lin { + pub base: Base, + pub mul: u32, + pub add: u32, +} + +impl Lin { + fn constant(add: u32) -> Lin { + Lin { base: Base::Constant, mul: 0, add } + } + + fn of(base: Base) -> Lin { + Lin { base, mul: 1, add: 0 } + } + + fn is_constant(&self) -> bool { + self.base == Base::Constant + } +} + +struct Eval<'a> { + p: &'a Program, + defs: HashMap<Value, Site>, + inputs: HashMap<Value, u8>, +} + +impl<'a> Eval<'a> { + fn new(p: &'a Program) -> Self { + let mut defs = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs.insert(v, (b, i)); + } + } + } + let inputs = p + .inputs + .iter() + .filter_map(|&(reg, v)| match reg { + Reg::V(r) => Some((v, r)), + _ => None, + }) + .collect(); + Eval { p, defs, inputs } + } + + fn value(&self, v: Value, depth: u32) -> Lin { + if let Some(&r) = self.inputs.get(&v) { + return Lin::of(Base::Input(r)); + } + match self.defs.get(&v) { + Some(&(b, i)) if depth < 32 => self.inst(&self.p.blocks[b].insts[i], v, depth), + _ => Lin::of(Base::Opaque(v)), + } + } + + fn operand(&self, inst: &Inst, op: &Operand, depth: u32) -> Option<Lin> { + match *op { + Operand::Const(c @ 128..=192) => Some(Lin::constant(u32::from(c) - 128)), + Operand::Const(c @ 193..=208) => Some(Lin::constant(0u32.wrapping_sub(u32::from(c) - 192))), + Operand::Literal(l) => Some(Lin::constant(l)), + Operand::Vector { reg, .. } => Some(self.value(inst.read(Reg::V(reg))?, depth + 1)), + Operand::Scalar { code, .. } => Some(self.value(inst.read(Reg::S(code))?, depth + 1)), + _ => None, + } + } + + fn inst(&self, inst: &Inst, v: Value, depth: u32) -> Lin { + let opaque = Lin::of(Base::Opaque(v)); + 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 c = |l: &Lin| l.is_constant().then_some(l.add); + 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 { + Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: false }), + Base::Half { .. } if plain(x) => *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, + }, + ("v_bfe_u32", [x, off, width]) if c(width) == Some(16) && c(off).is_some_and(|o| o % 16 == 0) => { + match x.base { + Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: c(off) == Some(16) }), + _ => opaque, + } + } + ("v_lshlrev_b32", [s, x]) if c(s).is_some_and(|s| s < 32) => { + if x.is_constant() { + Lin::constant(x.add.wrapping_shl(c(s).unwrap())) + } else { + shifted(*x, c(s).unwrap()) + } + } + ("v_add_nc_u32" | "v_add_u32" | "v_add_co_u32", [x, y]) => match (c(x), c(y)) { + (Some(p), Some(q)) => Lin::constant(p.wrapping_add(q)), + (Some(k), None) => Lin { add: y.add.wrapping_add(k), ..*y }, + (None, Some(k)) => Lin { add: x.add.wrapping_add(k), ..*x }, + _ => opaque, + }, + ("v_mul_u32_u24", [x, y]) => match (c(x), c(y)) { + (Some(p), Some(q)) => Lin::constant(p.wrapping_mul(q)), + (None, Some(k)) | (Some(k), None) => { + let x = if c(x).is_some() { y } else { x }; + Lin { base: x.base, mul: x.mul.wrapping_mul(k), add: x.add.wrapping_mul(k) } + } + _ => opaque, + }, + _ => opaque, + } + } +} + +/// How many dwords an LDS read or write moves, from its name. +fn width(name: &str) -> Option<u32> { + match name { + "ds_read_b32" | "ds_write_b32" => Some(1), + "ds_read_b64" | "ds_write_b64" => Some(2), + "ds_read_b96" | "ds_write_b96" => Some(3), + "ds_read_b128" | "ds_write_b128" => Some(4), + _ => 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" +} + +fn unsupported(what: &'static str) -> ShaderError { + Unsupported { offset: 0, what } +} + +/// A record write of the ES half: VGPRs `reg..reg + count` go to record +/// dwords `dword..dword + count`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Store { + pub site: Site, + pub dword: u32, + pub count: u32, + pub reg: u8, +} + +/// The ES half's record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EsRecord { + pub stores: Vec<Store>, + /// Dwords of the record: past the highest one written. + pub dwords: u32, + /// An `s_barrier` comes before the handover. + pub barrier: bool, +} + +impl EsRecord { + /// Whether some store writes record dword `dword`. + pub fn writes(&self, dword: u32) -> bool { + self.stores.iter().any(|s| (s.dword..s.dword + s.count).contains(&dword)) + } +} + +/// The records an ES program writes. +/// +/// Fails when it does not end by handing over to the GS half +/// (`s_setpc_b64`), touches LDS in any way but whole-dword record writes, +/// writes at more than one base, or writes nothing. +pub fn es_record(p: &Program) -> Result<EsRecord, ShaderError> { + if !p.blocks.iter().any(|b| b.exit == Exit::Indirect) { ``` **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Require every reachable ES exit to hand off** If an ES CFG has one reachable `s_setpc_b64` exit and another reachable `s_endpgm` exit, this check succeeds, so `es_record` and `handoff` accept a pair even though that branch never transfers the record to GS. Validate that every reachable terminal path hands off, rather than only requiring one indirect exit. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:08 UTC · original
On crates/victory-shader/src/handoff.rs line 152 (outdated):

@@ -0,0 +1,497 @@
+//! The ES to GS handoff of a merged geometry stage ([`crate::merged`]), as
+//! the code of the two halves shows it.
+//!
+//! The ES half fetches a vertex, writes it to LDS as a fixed-size record
+//! (`ds_write_b32` .. `ds_write_b128` at one base address and constant
+//! offsets), waits at `s_barrier` and leaves through `s_setpc_b64` into the
+//! GS half. The GS half reads the records of the vertices of its primitive
+//! (`ds_read_b32` .. `ds_read_b128`) at the offset the hardware gives it for
+//! each vertex.
+//!
+//! A host vertex shader has no LDS and a host geometry shader no way to read
+//! another stage's memory, so the handoff is modeled, not run: what the ES
+//! half writes at record dword k is output k of the vertex, and what the GS
+//! half reads at vertex v, record dword k is input k of vertex v. This module
+//! finds those writes and reads. Emission is [`crate::emit`]'s.
+//!
+//! What is assumed (the ISA's convention for a merged stage, not checked
+//! against a title program):
+//!
+//! * The GS half gets the ES-ring offsets of its vertices packed two to a
+//!   VGPR: vertex 0 in the low half of v0, vertex 1 in its high half, vertex
+//!   2 in the low half of v1 ([`VERTEX_OFFSETS`]). A read whose address is
+//!   such a half (scaled, plus constants) is a read of that vertex's record;
+//!   a read at any other address is the GS half's own output memory.
+//! * The ES half's writes all use one base address (its vertex's slot) and
+//!   constant offsets, the same units as the GS half's.
+
+use std::collections::{BTreeSet, HashMap};
+
+use crate::ShaderError::{self, Unsupported};
+use crate::gfx10::{Fields, Operand};
+use crate::ir::{Exit, Inst, Program, Reg, Value};
+
+/// Where the GS half finds the ES-ring offset of input vertex `n`: the VGPR
+/// and whether it is the high half.
+pub const VERTEX_OFFSETS: [(u8, bool); 4] = [(0, false), (0, true), (1, false), (1, true)];
+
+/// Triangles in.
+pub const MAX_VERTICES: usize = 3;
+
+type Site = (usize, usize);
+
+/// What a value is, as `base * mul + add` in wrapping 32-bit arithmetic.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Base {
+    /// No base: `add` is the whole value.
+    Constant,
+    /// A VGPR as it arrived.
+    Input(u8),
+    /// The low or high 16 bits of an arrived VGPR.
+    Half { reg: u8, high: bool },
+    /// Anything else, named by the value that holds it.
+    Opaque(Value),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Lin {
+    pub base: Base,
+    pub mul: u32,
+    pub add: u32,
+}
+
+impl Lin {
+    fn constant(add: u32) -> Lin {
+        Lin { base: Base::Constant, mul: 0, add }
+    }
+
+    fn of(base: Base) -> Lin {
+        Lin { base, mul: 1, add: 0 }
+    }
+
+    fn is_constant(&self) -> bool {
+        self.base == Base::Constant
+    }
+}
+
+struct Eval<'a> {
+    p: &'a Program,
+    defs: HashMap<Value, Site>,
+    inputs: HashMap<Value, u8>,
+}
+
+impl<'a> Eval<'a> {
+    fn new(p: &'a Program) -> Self {
+        let mut defs = HashMap::new();
+        for (b, block) in p.blocks.iter().enumerate() {
+            for (i, inst) in block.insts.iter().enumerate() {
+                for &(_, v) in &inst.writes {
+                    defs.insert(v, (b, i));
+                }
+            }
+        }
+        let inputs = p
+            .inputs
+            .iter()
+            .filter_map(|&(reg, v)| match reg {
+                Reg::V(r) => Some((v, r)),
+                _ => None,
+            })
+            .collect();
+        Eval { p, defs, inputs }
+    }
+
+    fn value(&self, v: Value, depth: u32) -> Lin {
+        if let Some(&r) = self.inputs.get(&v) {
+            return Lin::of(Base::Input(r));
+        }
+        match self.defs.get(&v) {
+            Some(&(b, i)) if depth < 32 => self.inst(&self.p.blocks[b].insts[i], v, depth),
+            _ => Lin::of(Base::Opaque(v)),
+        }
+    }
+
+    fn operand(&self, inst: &Inst, op: &Operand, depth: u32) -> Option<Lin> {
+        match *op {
+            Operand::Const(c @ 128..=192) => Some(Lin::constant(u32::from(c) - 128)),
+            Operand::Const(c @ 193..=208) => Some(Lin::constant(0u32.wrapping_sub(u32::from(c) - 192))),
+            Operand::Literal(l) => Some(Lin::constant(l)),
+            Operand::Vector { reg, .. } => Some(self.value(inst.read(Reg::V(reg))?, depth + 1)),
+            Operand::Scalar { code, .. } => Some(self.value(inst.read(Reg::S(code))?, depth + 1)),
+            _ => None,
+        }
+    }
+
+    fn inst(&self, inst: &Inst, v: Value, depth: u32) -> Lin {
+        let opaque = Lin::of(Base::Opaque(v));
+        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 c = |l: &Lin| l.is_constant().then_some(l.add);
+        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 {
+                Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: false }),
+                Base::Half { .. } if plain(x) => *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,
+            },
+            ("v_bfe_u32", [x, off, width]) if c(width) == Some(16) && c(off).is_some_and(|o| o % 16 == 0) => {
+                match x.base {
+                    Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: c(off) == Some(16) }),

P2 Badge Normalize BFE offsets before classifying halves

For a v_bfe_u32 with inline offset 48, this condition accepts the offset, but the branch below labels only exactly 16 as the high half. GFX10 masks BFE offsets to five bits (as emit/lower.rs::bfe does with off & 31), so 48 selects bit 16; vertex_reads then attributes a vertex-1 read to vertex 0, which can make the handoff check validate the wrong record. Classify the masked offset or reject values other than 0 and 16.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:08 UTC · [original](https://github.com/fxceless/victory-fork/pull/373#discussion_r4688365629) On `crates/victory-shader/src/handoff.rs` line 152 (outdated): ```diff @@ -0,0 +1,497 @@ +//! The ES to GS handoff of a merged geometry stage ([`crate::merged`]), as +//! the code of the two halves shows it. +//! +//! The ES half fetches a vertex, writes it to LDS as a fixed-size record +//! (`ds_write_b32` .. `ds_write_b128` at one base address and constant +//! offsets), waits at `s_barrier` and leaves through `s_setpc_b64` into the +//! GS half. The GS half reads the records of the vertices of its primitive +//! (`ds_read_b32` .. `ds_read_b128`) at the offset the hardware gives it for +//! each vertex. +//! +//! A host vertex shader has no LDS and a host geometry shader no way to read +//! another stage's memory, so the handoff is modeled, not run: what the ES +//! half writes at record dword k is output k of the vertex, and what the GS +//! half reads at vertex v, record dword k is input k of vertex v. This module +//! finds those writes and reads. Emission is [`crate::emit`]'s. +//! +//! What is assumed (the ISA's convention for a merged stage, not checked +//! against a title program): +//! +//! * The GS half gets the ES-ring offsets of its vertices packed two to a +//! VGPR: vertex 0 in the low half of v0, vertex 1 in its high half, vertex +//! 2 in the low half of v1 ([`VERTEX_OFFSETS`]). A read whose address is +//! such a half (scaled, plus constants) is a read of that vertex's record; +//! a read at any other address is the GS half's own output memory. +//! * The ES half's writes all use one base address (its vertex's slot) and +//! constant offsets, the same units as the GS half's. + +use std::collections::{BTreeSet, HashMap}; + +use crate::ShaderError::{self, Unsupported}; +use crate::gfx10::{Fields, Operand}; +use crate::ir::{Exit, Inst, Program, Reg, Value}; + +/// Where the GS half finds the ES-ring offset of input vertex `n`: the VGPR +/// and whether it is the high half. +pub const VERTEX_OFFSETS: [(u8, bool); 4] = [(0, false), (0, true), (1, false), (1, true)]; + +/// Triangles in. +pub const MAX_VERTICES: usize = 3; + +type Site = (usize, usize); + +/// What a value is, as `base * mul + add` in wrapping 32-bit arithmetic. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Base { + /// No base: `add` is the whole value. + Constant, + /// A VGPR as it arrived. + Input(u8), + /// The low or high 16 bits of an arrived VGPR. + Half { reg: u8, high: bool }, + /// Anything else, named by the value that holds it. + Opaque(Value), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Lin { + pub base: Base, + pub mul: u32, + pub add: u32, +} + +impl Lin { + fn constant(add: u32) -> Lin { + Lin { base: Base::Constant, mul: 0, add } + } + + fn of(base: Base) -> Lin { + Lin { base, mul: 1, add: 0 } + } + + fn is_constant(&self) -> bool { + self.base == Base::Constant + } +} + +struct Eval<'a> { + p: &'a Program, + defs: HashMap<Value, Site>, + inputs: HashMap<Value, u8>, +} + +impl<'a> Eval<'a> { + fn new(p: &'a Program) -> Self { + let mut defs = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs.insert(v, (b, i)); + } + } + } + let inputs = p + .inputs + .iter() + .filter_map(|&(reg, v)| match reg { + Reg::V(r) => Some((v, r)), + _ => None, + }) + .collect(); + Eval { p, defs, inputs } + } + + fn value(&self, v: Value, depth: u32) -> Lin { + if let Some(&r) = self.inputs.get(&v) { + return Lin::of(Base::Input(r)); + } + match self.defs.get(&v) { + Some(&(b, i)) if depth < 32 => self.inst(&self.p.blocks[b].insts[i], v, depth), + _ => Lin::of(Base::Opaque(v)), + } + } + + fn operand(&self, inst: &Inst, op: &Operand, depth: u32) -> Option<Lin> { + match *op { + Operand::Const(c @ 128..=192) => Some(Lin::constant(u32::from(c) - 128)), + Operand::Const(c @ 193..=208) => Some(Lin::constant(0u32.wrapping_sub(u32::from(c) - 192))), + Operand::Literal(l) => Some(Lin::constant(l)), + Operand::Vector { reg, .. } => Some(self.value(inst.read(Reg::V(reg))?, depth + 1)), + Operand::Scalar { code, .. } => Some(self.value(inst.read(Reg::S(code))?, depth + 1)), + _ => None, + } + } + + fn inst(&self, inst: &Inst, v: Value, depth: u32) -> Lin { + let opaque = Lin::of(Base::Opaque(v)); + 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 c = |l: &Lin| l.is_constant().then_some(l.add); + 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 { + Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: false }), + Base::Half { .. } if plain(x) => *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, + }, + ("v_bfe_u32", [x, off, width]) if c(width) == Some(16) && c(off).is_some_and(|o| o % 16 == 0) => { + match x.base { + Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: c(off) == Some(16) }), ``` **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Normalize BFE offsets before classifying halves** For a `v_bfe_u32` with inline offset 48, this condition accepts the offset, but the branch below labels only exactly 16 as the high half. GFX10 masks BFE offsets to five bits (as `emit/lower.rs::bfe` does with `off & 31`), so 48 selects bit 16; `vertex_reads` then attributes a vertex-1 read to vertex 0, which can make the handoff check validate the wrong record. Classify the masked offset or reject values other than 0 and 16. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:08 UTC · original
On crates/victory-shader/src/handoff.rs line 244 (outdated):

@@ -0,0 +1,497 @@
+//! The ES to GS handoff of a merged geometry stage ([`crate::merged`]), as
+//! the code of the two halves shows it.
+//!
+//! The ES half fetches a vertex, writes it to LDS as a fixed-size record
+//! (`ds_write_b32` .. `ds_write_b128` at one base address and constant
+//! offsets), waits at `s_barrier` and leaves through `s_setpc_b64` into the
+//! GS half. The GS half reads the records of the vertices of its primitive
+//! (`ds_read_b32` .. `ds_read_b128`) at the offset the hardware gives it for
+//! each vertex.
+//!
+//! A host vertex shader has no LDS and a host geometry shader no way to read
+//! another stage's memory, so the handoff is modeled, not run: what the ES
+//! half writes at record dword k is output k of the vertex, and what the GS
+//! half reads at vertex v, record dword k is input k of vertex v. This module
+//! finds those writes and reads. Emission is [`crate::emit`]'s.
+//!
+//! What is assumed (the ISA's convention for a merged stage, not checked
+//! against a title program):
+//!
+//! * The GS half gets the ES-ring offsets of its vertices packed two to a
+//!   VGPR: vertex 0 in the low half of v0, vertex 1 in its high half, vertex
+//!   2 in the low half of v1 ([`VERTEX_OFFSETS`]). A read whose address is
+//!   such a half (scaled, plus constants) is a read of that vertex's record;
+//!   a read at any other address is the GS half's own output memory.
+//! * The ES half's writes all use one base address (its vertex's slot) and
+//!   constant offsets, the same units as the GS half's.
+
+use std::collections::{BTreeSet, HashMap};
+
+use crate::ShaderError::{self, Unsupported};
+use crate::gfx10::{Fields, Operand};
+use crate::ir::{Exit, Inst, Program, Reg, Value};
+
+/// Where the GS half finds the ES-ring offset of input vertex `n`: the VGPR
+/// and whether it is the high half.
+pub const VERTEX_OFFSETS: [(u8, bool); 4] = [(0, false), (0, true), (1, false), (1, true)];
+
+/// Triangles in.
+pub const MAX_VERTICES: usize = 3;
+
+type Site = (usize, usize);
+
+/// What a value is, as `base * mul + add` in wrapping 32-bit arithmetic.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Base {
+    /// No base: `add` is the whole value.
+    Constant,
+    /// A VGPR as it arrived.
+    Input(u8),
+    /// The low or high 16 bits of an arrived VGPR.
+    Half { reg: u8, high: bool },
+    /// Anything else, named by the value that holds it.
+    Opaque(Value),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Lin {
+    pub base: Base,
+    pub mul: u32,
+    pub add: u32,
+}
+
+impl Lin {
+    fn constant(add: u32) -> Lin {
+        Lin { base: Base::Constant, mul: 0, add }
+    }
+
+    fn of(base: Base) -> Lin {
+        Lin { base, mul: 1, add: 0 }
+    }
+
+    fn is_constant(&self) -> bool {
+        self.base == Base::Constant
+    }
+}
+
+struct Eval<'a> {
+    p: &'a Program,
+    defs: HashMap<Value, Site>,
+    inputs: HashMap<Value, u8>,
+}
+
+impl<'a> Eval<'a> {
+    fn new(p: &'a Program) -> Self {
+        let mut defs = HashMap::new();
+        for (b, block) in p.blocks.iter().enumerate() {
+            for (i, inst) in block.insts.iter().enumerate() {
+                for &(_, v) in &inst.writes {
+                    defs.insert(v, (b, i));
+                }
+            }
+        }
+        let inputs = p
+            .inputs
+            .iter()
+            .filter_map(|&(reg, v)| match reg {
+                Reg::V(r) => Some((v, r)),
+                _ => None,
+            })
+            .collect();
+        Eval { p, defs, inputs }
+    }
+
+    fn value(&self, v: Value, depth: u32) -> Lin {
+        if let Some(&r) = self.inputs.get(&v) {
+            return Lin::of(Base::Input(r));
+        }
+        match self.defs.get(&v) {
+            Some(&(b, i)) if depth < 32 => self.inst(&self.p.blocks[b].insts[i], v, depth),
+            _ => Lin::of(Base::Opaque(v)),
+        }
+    }
+
+    fn operand(&self, inst: &Inst, op: &Operand, depth: u32) -> Option<Lin> {
+        match *op {
+            Operand::Const(c @ 128..=192) => Some(Lin::constant(u32::from(c) - 128)),
+            Operand::Const(c @ 193..=208) => Some(Lin::constant(0u32.wrapping_sub(u32::from(c) - 192))),
+            Operand::Literal(l) => Some(Lin::constant(l)),
+            Operand::Vector { reg, .. } => Some(self.value(inst.read(Reg::V(reg))?, depth + 1)),
+            Operand::Scalar { code, .. } => Some(self.value(inst.read(Reg::S(code))?, depth + 1)),
+            _ => None,
+        }
+    }
+
+    fn inst(&self, inst: &Inst, v: Value, depth: u32) -> Lin {
+        let opaque = Lin::of(Base::Opaque(v));
+        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 c = |l: &Lin| l.is_constant().then_some(l.add);
+        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 {
+                Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: false }),
+                Base::Half { .. } if plain(x) => *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,
+            },
+            ("v_bfe_u32", [x, off, width]) if c(width) == Some(16) && c(off).is_some_and(|o| o % 16 == 0) => {
+                match x.base {
+                    Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: c(off) == Some(16) }),
+                    _ => opaque,
+                }
+            }
+            ("v_lshlrev_b32", [s, x]) if c(s).is_some_and(|s| s < 32) => {
+                if x.is_constant() {
+                    Lin::constant(x.add.wrapping_shl(c(s).unwrap()))
+                } else {
+                    shifted(*x, c(s).unwrap())
+                }
+            }
+            ("v_add_nc_u32" | "v_add_u32" | "v_add_co_u32", [x, y]) => match (c(x), c(y)) {
+                (Some(p), Some(q)) => Lin::constant(p.wrapping_add(q)),
+                (Some(k), None) => Lin { add: y.add.wrapping_add(k), ..*y },
+                (None, Some(k)) => Lin { add: x.add.wrapping_add(k), ..*x },
+                _ => opaque,
+            },
+            ("v_mul_u32_u24", [x, y]) => match (c(x), c(y)) {
+                (Some(p), Some(q)) => Lin::constant(p.wrapping_mul(q)),
+                (None, Some(k)) | (Some(k), None) => {
+                    let x = if c(x).is_some() { y } else { x };
+                    Lin { base: x.base, mul: x.mul.wrapping_mul(k), add: x.add.wrapping_mul(k) }
+                }
+                _ => opaque,
+            },
+            _ => opaque,
+        }
+    }
+}
+
+/// How many dwords an LDS read or write moves, from its name.
+fn width(name: &str) -> Option<u32> {
+    match name {
+        "ds_read_b32" | "ds_write_b32" => Some(1),
+        "ds_read_b64" | "ds_write_b64" => Some(2),
+        "ds_read_b96" | "ds_write_b96" => Some(3),
+        "ds_read_b128" | "ds_write_b128" => Some(4),
+        _ => 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"
+}
+
+fn unsupported(what: &'static str) -> ShaderError {
+    Unsupported { offset: 0, what }
+}
+
+/// A record write of the ES half: VGPRs `reg..reg + count` go to record
+/// dwords `dword..dword + count`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Store {
+    pub site: Site,
+    pub dword: u32,
+    pub count: u32,
+    pub reg: u8,
+}
+
+/// The ES half's record.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct EsRecord {
+    pub stores: Vec<Store>,
+    /// Dwords of the record: past the highest one written.
+    pub dwords: u32,
+    /// An `s_barrier` comes before the handover.
+    pub barrier: bool,
+}
+
+impl EsRecord {
+    /// Whether some store writes record dword `dword`.
+    pub fn writes(&self, dword: u32) -> bool {
+        self.stores.iter().any(|s| (s.dword..s.dword + s.count).contains(&dword))
+    }
+}
+
+/// The records an ES program writes.
+///
+/// Fails when it does not end by handing over to the GS half
+/// (`s_setpc_b64`), touches LDS in any way but whole-dword record writes,
+/// writes at more than one base, or writes nothing.
+pub fn es_record(p: &Program) -> Result<EsRecord, ShaderError> {
+    if !p.blocks.iter().any(|b| b.exit == Exit::Indirect) {
+        return Err(unsupported("an ES half that does not hand over to the GS half"));
+    }
+    let eval = Eval::new(p);
+    let mut stores = Vec::new();
+    let mut at: Option<(Base, u32)> = None;
+    let mut barrier = false;
+    for (b, block) in p.blocks.iter().enumerate() {
+        for (i, inst) in block.insts.iter().enumerate() {
+            barrier |= inst.name() == "s_barrier";

P2 Badge Track barriers along the handoff path

If an ES CFG has s_barrier only in an unreachable block or on a branch that does not reach s_setpc_b64, this assignment still marks EsRecord.barrier true. The returned record then incorrectly says the handoff path is preceded by a barrier; derive the flag from barriers that precede each reachable handoff instead of any barrier in the program.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:08 UTC · [original](https://github.com/fxceless/victory-fork/pull/373#discussion_r4688365641) On `crates/victory-shader/src/handoff.rs` line 244 (outdated): ```diff @@ -0,0 +1,497 @@ +//! The ES to GS handoff of a merged geometry stage ([`crate::merged`]), as +//! the code of the two halves shows it. +//! +//! The ES half fetches a vertex, writes it to LDS as a fixed-size record +//! (`ds_write_b32` .. `ds_write_b128` at one base address and constant +//! offsets), waits at `s_barrier` and leaves through `s_setpc_b64` into the +//! GS half. The GS half reads the records of the vertices of its primitive +//! (`ds_read_b32` .. `ds_read_b128`) at the offset the hardware gives it for +//! each vertex. +//! +//! A host vertex shader has no LDS and a host geometry shader no way to read +//! another stage's memory, so the handoff is modeled, not run: what the ES +//! half writes at record dword k is output k of the vertex, and what the GS +//! half reads at vertex v, record dword k is input k of vertex v. This module +//! finds those writes and reads. Emission is [`crate::emit`]'s. +//! +//! What is assumed (the ISA's convention for a merged stage, not checked +//! against a title program): +//! +//! * The GS half gets the ES-ring offsets of its vertices packed two to a +//! VGPR: vertex 0 in the low half of v0, vertex 1 in its high half, vertex +//! 2 in the low half of v1 ([`VERTEX_OFFSETS`]). A read whose address is +//! such a half (scaled, plus constants) is a read of that vertex's record; +//! a read at any other address is the GS half's own output memory. +//! * The ES half's writes all use one base address (its vertex's slot) and +//! constant offsets, the same units as the GS half's. + +use std::collections::{BTreeSet, HashMap}; + +use crate::ShaderError::{self, Unsupported}; +use crate::gfx10::{Fields, Operand}; +use crate::ir::{Exit, Inst, Program, Reg, Value}; + +/// Where the GS half finds the ES-ring offset of input vertex `n`: the VGPR +/// and whether it is the high half. +pub const VERTEX_OFFSETS: [(u8, bool); 4] = [(0, false), (0, true), (1, false), (1, true)]; + +/// Triangles in. +pub const MAX_VERTICES: usize = 3; + +type Site = (usize, usize); + +/// What a value is, as `base * mul + add` in wrapping 32-bit arithmetic. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Base { + /// No base: `add` is the whole value. + Constant, + /// A VGPR as it arrived. + Input(u8), + /// The low or high 16 bits of an arrived VGPR. + Half { reg: u8, high: bool }, + /// Anything else, named by the value that holds it. + Opaque(Value), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Lin { + pub base: Base, + pub mul: u32, + pub add: u32, +} + +impl Lin { + fn constant(add: u32) -> Lin { + Lin { base: Base::Constant, mul: 0, add } + } + + fn of(base: Base) -> Lin { + Lin { base, mul: 1, add: 0 } + } + + fn is_constant(&self) -> bool { + self.base == Base::Constant + } +} + +struct Eval<'a> { + p: &'a Program, + defs: HashMap<Value, Site>, + inputs: HashMap<Value, u8>, +} + +impl<'a> Eval<'a> { + fn new(p: &'a Program) -> Self { + let mut defs = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs.insert(v, (b, i)); + } + } + } + let inputs = p + .inputs + .iter() + .filter_map(|&(reg, v)| match reg { + Reg::V(r) => Some((v, r)), + _ => None, + }) + .collect(); + Eval { p, defs, inputs } + } + + fn value(&self, v: Value, depth: u32) -> Lin { + if let Some(&r) = self.inputs.get(&v) { + return Lin::of(Base::Input(r)); + } + match self.defs.get(&v) { + Some(&(b, i)) if depth < 32 => self.inst(&self.p.blocks[b].insts[i], v, depth), + _ => Lin::of(Base::Opaque(v)), + } + } + + fn operand(&self, inst: &Inst, op: &Operand, depth: u32) -> Option<Lin> { + match *op { + Operand::Const(c @ 128..=192) => Some(Lin::constant(u32::from(c) - 128)), + Operand::Const(c @ 193..=208) => Some(Lin::constant(0u32.wrapping_sub(u32::from(c) - 192))), + Operand::Literal(l) => Some(Lin::constant(l)), + Operand::Vector { reg, .. } => Some(self.value(inst.read(Reg::V(reg))?, depth + 1)), + Operand::Scalar { code, .. } => Some(self.value(inst.read(Reg::S(code))?, depth + 1)), + _ => None, + } + } + + fn inst(&self, inst: &Inst, v: Value, depth: u32) -> Lin { + let opaque = Lin::of(Base::Opaque(v)); + 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 c = |l: &Lin| l.is_constant().then_some(l.add); + 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 { + Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: false }), + Base::Half { .. } if plain(x) => *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, + }, + ("v_bfe_u32", [x, off, width]) if c(width) == Some(16) && c(off).is_some_and(|o| o % 16 == 0) => { + match x.base { + Base::Input(reg) if plain(x) => Lin::of(Base::Half { reg, high: c(off) == Some(16) }), + _ => opaque, + } + } + ("v_lshlrev_b32", [s, x]) if c(s).is_some_and(|s| s < 32) => { + if x.is_constant() { + Lin::constant(x.add.wrapping_shl(c(s).unwrap())) + } else { + shifted(*x, c(s).unwrap()) + } + } + ("v_add_nc_u32" | "v_add_u32" | "v_add_co_u32", [x, y]) => match (c(x), c(y)) { + (Some(p), Some(q)) => Lin::constant(p.wrapping_add(q)), + (Some(k), None) => Lin { add: y.add.wrapping_add(k), ..*y }, + (None, Some(k)) => Lin { add: x.add.wrapping_add(k), ..*x }, + _ => opaque, + }, + ("v_mul_u32_u24", [x, y]) => match (c(x), c(y)) { + (Some(p), Some(q)) => Lin::constant(p.wrapping_mul(q)), + (None, Some(k)) | (Some(k), None) => { + let x = if c(x).is_some() { y } else { x }; + Lin { base: x.base, mul: x.mul.wrapping_mul(k), add: x.add.wrapping_mul(k) } + } + _ => opaque, + }, + _ => opaque, + } + } +} + +/// How many dwords an LDS read or write moves, from its name. +fn width(name: &str) -> Option<u32> { + match name { + "ds_read_b32" | "ds_write_b32" => Some(1), + "ds_read_b64" | "ds_write_b64" => Some(2), + "ds_read_b96" | "ds_write_b96" => Some(3), + "ds_read_b128" | "ds_write_b128" => Some(4), + _ => 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" +} + +fn unsupported(what: &'static str) -> ShaderError { + Unsupported { offset: 0, what } +} + +/// A record write of the ES half: VGPRs `reg..reg + count` go to record +/// dwords `dword..dword + count`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Store { + pub site: Site, + pub dword: u32, + pub count: u32, + pub reg: u8, +} + +/// The ES half's record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EsRecord { + pub stores: Vec<Store>, + /// Dwords of the record: past the highest one written. + pub dwords: u32, + /// An `s_barrier` comes before the handover. + pub barrier: bool, +} + +impl EsRecord { + /// Whether some store writes record dword `dword`. + pub fn writes(&self, dword: u32) -> bool { + self.stores.iter().any(|s| (s.dword..s.dword + s.count).contains(&dword)) + } +} + +/// The records an ES program writes. +/// +/// Fails when it does not end by handing over to the GS half +/// (`s_setpc_b64`), touches LDS in any way but whole-dword record writes, +/// writes at more than one base, or writes nothing. +pub fn es_record(p: &Program) -> Result<EsRecord, ShaderError> { + if !p.blocks.iter().any(|b| b.exit == Exit::Indirect) { + return Err(unsupported("an ES half that does not hand over to the GS half")); + } + let eval = Eval::new(p); + let mut stores = Vec::new(); + let mut at: Option<(Base, u32)> = None; + let mut barrier = false; + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + barrier |= inst.name() == "s_barrier"; ``` **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Track barriers along the handoff path** If an ES CFG has `s_barrier` only in an unreachable block or on a branch that does not reach `s_setpc_b64`, this assignment still marks `EsRecord.barrier` true. The returned record then incorrectly says the handoff path is preceded by a barrier; derive the flag from barriers that precede each reachable handoff instead of any barrier in the program. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-25 00:08 UTC · original
On apps/victory/src/translate.rs line 450 (outdated):

@@ -404,8 +443,26 @@ fn translate_programs(container: &Container, programs: Vec<NativeProgram>, examp
                 // failure is listed after the resources' and I/O's.
                 let structured = structure::structure(&program);
                 let lanes = structured.as_ref().ok();
-                let res = match resource::track(&program, &p.layout, p.stage, lanes) {
+                let geometry = p.stage == HwStage::Gs;
+                let es = p.stage == HwStage::Es;
+                t.gs_programs += usize::from(geometry);
+                t.es_programs += usize::from(es);
+                if es && let Ok(r) = victory_shader::handoff::es_record(&program) {

P2 Badge Report failed ES record analysis

When es_record rejects an ES program, this if let Ok discards the error. If resource, I/O, and structure checks pass, the later ES-only continue skips emission too, so victory translate leaves the invalid ES half out of t.failed and --list; record the error in the tally.

Useful? React with 👍 / 👎.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-25 00:08 UTC · [original](https://github.com/fxceless/victory-fork/pull/373#discussion_r4688365647) On `apps/victory/src/translate.rs` line 450 (outdated): ```diff @@ -404,8 +443,26 @@ fn translate_programs(container: &Container, programs: Vec<NativeProgram>, examp // failure is listed after the resources' and I/O's. let structured = structure::structure(&program); let lanes = structured.as_ref().ok(); - let res = match resource::track(&program, &p.layout, p.stage, lanes) { + let geometry = p.stage == HwStage::Gs; + let es = p.stage == HwStage::Es; + t.gs_programs += usize::from(geometry); + t.es_programs += usize::from(es); + if es && let Ok(r) = victory_shader::handoff::es_record(&program) { ``` **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Report failed ES record analysis** When `es_record` rejects an ES program, this `if let Ok` discards the error. If resource, I/O, and structure checks pass, the later ES-only `continue` skips emission too, so `victory translate` leaves the invalid ES half out of `t.failed` and `--list`; record the error in the tally. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

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

Merge

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