Skip to content

shader,gpu: resolve heap-loaded view addresses and widen native complement masks - #738

Open
powplusplus wants to merge 1 commit into
fxceless:mainfrom
powplusplus:shader/heap-view-addresses
Open

powplusplus wants to merge 1 commit into
fxceless:mainfrom
powplusplus:shader/heap-view-addresses

Conversation

@powplusplus

Copy link
Copy Markdown

Summary

Unlocks the remaining 5 untranslated ray-tracing shadow-mask trace compute programs (bringing all 64 BVH trace programs in the archive from 59/64 to 64/64 emitted and DXIL-validated):

  1. Per-view-heap buffer-address table (SLOT_VIEW_ADDRESSES = 252):
    • The remaining shadow-mask trace shaders load buffer descriptors from the bindless resource heap (or dynamically indexed descriptor tables) and read their 64-bit title GPU virtual address as data (Lower::view_address), which previously only handled static descriptor tables and failed with a descriptor read only as data.
    • HostHeap (crates/victory-gpu/src/descriptor/host.rs) now maintains a companion upload buffer of SLOT_STRIDES_COUNT (lo, hi) dword pairs recording each view heap slot's 64-bit title GPU virtual address in HostHeap::mirror, kept as a root SRV in pipeline/host.rs and bound in draw.rs.
    • Lower::view_address reads (lo, hi) from SLOT_VIEW_ADDRESSES (with clamped heap index) for RootType::ResourceHeap and dynamically indexed RootType::Table descriptor loads.
  2. Sound widening for complement lane masks in native compute shaders:
    • In Lower::mask_dword, native wave32/wave64 compute shaders (MaskData::Console && !local) now check all_lane_blocks(self.x.st) when a mask holds lanes outside EXEC, and call need(made) when written inside a per-lane branch.
    • emit::emit (crates/victory-shader/src/emit/mod.rs) enables widen() on MASK_ELSEWHERE alongside LANE_MASK for compute shaders so the per-lane skip around the mask is promoted wave-wide rather than assuming divergent blocks run all lanes.

Verification

  • Unit tests: cargo test -p victory-shader --lib (173 passed, 0 failed, including new heap_descriptor_address_reads_from_view_address_table and native_wave32_complement_mask_in_all_lanes_block_lowers tests).
  • Windows-target clippy (victory-shader -- -D warnings) and workspace check clean on 8dd30ab.
  • All 64 BVH ray-tracing trace programs (VICTORY_HOST_MAX_WAVE=32, RTX 3080, dxil.dll): 64/64 emitted, 64/64 DXIL-validated (up from 59/64). Combined with the single-latch / pipeline-stack fix, 64/64 create D3D12 pipelines on RTX 3080 with 0 failures and 0 timeouts.
  • Live in-game verification: 893 shaders translated with 0 translation errors and 0 unbound view-address warnings.

…ement masks

Ray-tracing shadow-mask trace programs read 64-bit title buffer addresses
from descriptors loaded out of the bindless resource heap (or dynamically
indexed tables) rather than static descriptor tables. Previously
Lower::view_address only handled static tables, failing those shaders with
'a descriptor read only as data'.

Add a per-view-heap buffer-address table (SLOT_VIEW_ADDRESSES = 252,
SLOT_STRIDES_COUNT pairs of (lo, hi) dwords) maintained in HostHeap::mirror
and bound as a root SRV in victory-gpu, and read it from Lower::view_address
for ResourceHeap and dynamically indexed Table loads.

Also allow native wave32/wave64 compute shaders (MaskData::Console,
!local) to check all_lane_blocks and trigger widen() on MASK_ELSEWHERE
when a complement mask sits inside a per-lane skip, unlocking the final
ray-tracing shadow-mask trace program and bringing all 64 BVH trace
programs to 64/64 emitted and DXIL-validated.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T06:21:02.901649Z ea40c9a PR opened
ℹ️ 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ea40c9a9ca

ℹ️ 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".

Comment on lines +499 to 500
&& (what == lower::LANE_MASK || what == lower::MASK_ELSEWHERE)
&& std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Honor the split-wave widening opt-in in the new retry

On a 32-lane host running a wave64 compute shader, this arm invokes widen() when MASK_ELSEWHERE survives the earlier retries even if VICTORY_WAVE_WIDE is unset. That bypasses the explicit opt-in at emit/mod.rs:404–409, which disables split-wave widening because its group barriers inside branches and loops have caused device hangs. A synthetic 64-thread wave64 shader with a complement defined under an EXEC skip reaches this newly default-enabled path. Restrict the default-on retry to native host waves, and retain the explicit VICTORY_WAVE_WIDE=1 requirement for split wave64 execution.

Useful? React with 👍 / 👎.

Comment on lines +2697 to +2698
if matches!(rp.root, RootType::ResourceHeap | RootType::Table) {
let slot = self.heap_index(site, 0, false).ok()?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve title-slot addresses when descriptor tables are relocated

For a dynamically indexed table containing a CBV, State::tables() relocates the table into dynamic host slots, and bind() substitutes that new base into its user data. Consequently, heap_index() returns a dynamic host slot here, but the address buffer is populated only for title slots through note_buffer(); make_at() and constant_at() never populate the relocated entries. These newly supported shaders therefore read a zero address instead of the buffer's title address and access the wrong memory. Use the original title-table index for this lookup, or populate the address metadata alongside relocated descriptors.

Useful? React with 👍 / 👎.

@Dathinel Dathinel Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Confirmed the relocated CBV case on ea40c9a with a synthetic D3D12 heap. The original slot contained the sentinel title address 0x1_1234_5600, while the dynamic slot's companion-table entry read 0. Passing the original title address separately from the scratch GPU VA to constant_at made the same test pass, including a second binding with a different high dword and clearing the slot to null (1 passed, 0 skipped). This reads the mapped table on the CPU. The SRV null-fallback path and visible output remain unverified.

A related NVIDIA comparison is Marvisak/VIctory#2178. Its RTX 5060 Ti tests exercise raw versus structured descriptor stride. That is a separate variable: for a shader-side regression test here, keep descriptor type and stride fixed and compare original versus relocated slots. That would distinguish an incorrect title address from an incorrect byte offset.

Shader readback on an RTX 3050 Laptop now confirms the SRV case. I registered a 256-byte synthetic buffer, placed a structured SRV with FirstElement=3 and stride=16, and verified that make_at created a backed view. A one-thread HLSL dispatch read three 64-bit entries via t252 with Load2(slot * 8), then copied the UAV output back after a fence. With the make_at metadata write omitted, the original slot returned base+48, the relocated slot 0, and the null control 0. Restoring only that write gave [base+48, base+48, 0]. This isolates the SRV metadata write. The probe does not run a translated game shader or measure frame output.

AI-assisted investigation and synthetic tests.

Comment on lines +3081 to +3082
None => all_lane_blocks(self.x.st)
.is_some_and(|all| all.get(b).copied().unwrap_or(false)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Require a full native wave before balloting complement masks

For a native wave32 group with 16 threads, all_lane_blocks() proves only that every launched lane reaches the block, not that all 32 mask bits have corresponding host invocations. If EXEC is narrowed to 0xff and s_xor_b32 s2, exec_lo, -1 is subsequently read as data, this new check accepts it, but the emitted ballot returns 0x0000ff00 rather than the console result 0xffffff00: lanes 16–31 cannot vote. The parent rejected this case. Require complete native waves for this shortcut, or explicitly reconstruct the mask bits belonging to unlaunched lanes.

Useful? React with 👍 / 👎.

@Dathinel Dathinel Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Confirmed on an RTX 3050 Laptop at PR head ea40c9a. One detail for the regression fixture: the word 0x8802_C17E in native_wave32_complement_mask_in_all_lanes_block_lowers decodes as s_or_b32, although the comment says XOR. The XOR word is 0x8902_C17E (SOP2 opcode 0x12).

With EXEC narrowed to the low eight bits, I read the scalar result back through lane 0. With the XOR word, a full 32-thread group returned the reference 0xffffff00; a 16-thread group returned 0x0000ff00. With the original OR word the respective outputs were 0xffffffff and 0x0000ffff. A local full-wave guard and corrected fixture preserved the XOR result for 32- and 64-thread groups (native wave32) and rejected the partial groups of 16 and 48 at lowering. Both focused tests passed. This is a synthetic readback; it does not establish which of the five title programs use partial groups. AI-assisted.

Follow-up on the partial group: a narrow alternative to refusing this specific shader pattern is to ballot the bounded input and then invert the scalar. When the original EXEC is narrowed by AND-saveexec, unlaunched lanes have zero input bits. Inverting the resulting 32-bit scalar restores their ones. The candidate below applies only to native wave32, the direct narrowing of entry EXEC, and an XOR with inline -1 in a block reached by the whole wave. Other partial complement shapes still refuse.

RTX 3050 Laptop: 24 single-group readbacks across sizes 16/32/48/64, then eight groups per dispatch, each writing a different expected word. Group g enabled the first g lanes of the selected wave; its last launched thread stored the result after EXEC was restored. All 48 group/wave results matched 0xffffffff << g, including the second, partial wave of each 48-thread group. For a scalar select reading SCC from this same XOR, the incremental change below compares the reconstructed dword with zero. On the RTX 3050, 36 flag readbacks matched, including when EXEC was restored and the destination SGPR overwritten before the select. A partial-group OR control still refused. This exercises a direct scalar select; it does not cover arbitrary SCC consumers. No claim about title visuals.

Candidate emitter diff against ea40c9a (includes corrected XOR test word)
diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs
index 995624f..bfb6928 100644
--- a/crates/victory-shader/src/emit/lower.rs
+++ b/crates/victory-shader/src/emit/lower.rs
@@ -3061,6 +3061,27 @@ impl<'a> Lower<'a> {
         Ok(())
     }
 
+    /// A native wave32 complement of the entry EXEC narrowed by AND-saveexec.
+    /// Unlaunched lanes have zero input bits, hence one output bit.
+    fn narrowed_exec_complement(&self, v: Value) -> Option<Value> {
+        let writer = |value| {
+            let block = *self.def_block.get(&value)?;
+            self.x.p.blocks[block].insts.iter().find(|i| i.writes.iter().any(|w| w.1 == value))
+        };
+        let xor = writer(v)?;
+        let Fields::Sop { src, .. } = &xor.fields else { return None };
+        if xor.name() != "s_xor_b32" || !matches!(src.as_slice(),
+            [Operand::Scalar { code: EXEC, .. }, Operand::Const(193)]
+            | [Operand::Const(193), Operand::Scalar { code: EXEC, .. }]) {
+            return None;
+        }
+        let exec = xor.read(Reg::S(EXEC))?;
+        let and = writer(exec)?;
+        let input = and.read(Reg::S(EXEC))?;
+        (and.name() == "s_and_saveexec_b32" && self.x.p.inputs.contains(&(Reg::S(EXEC), input))
+            && self.x.st.active.contains(&exec)).then_some(exec)
+    }
+
     /// A dword of a lane mask as a number: the ballot of the lanes' bits,
     /// taken in the block that writes the mask (see [`MaskData`]).
     fn mask_dword(&mut self, v: Value) -> Result<V, Why> {
@@ -3074,6 +3095,10 @@ impl<'a> Lower<'a> {
         // the wave runs that block.
         if !self.x.st.active.contains(&lo) {
             let made = self.def_block.get(&lo).copied();
+            let lanes = if self.x.p.wave64 { 64 } else { 32 };
+            let full = self.s.threads.is_some_and(|t| {
+                t.into_iter().try_fold(1u32, u32::checked_mul).is_some_and(|n| n.is_multiple_of(lanes))
+            });
             let whole = self.mask_data == MaskData::Console
                 && !self.local
                 && made.is_none_or(|b| match &self.exchange {
@@ -3081,7 +3106,14 @@ impl<'a> Lower<'a> {
                     None => all_lane_blocks(self.x.st)
                         .is_some_and(|all| all.get(b).copied().unwrap_or(false)),
                 });
-            if !whole {
+            if whole && !full && !self.x.p.wave64 && self.exchange.is_none()
+                && let Some(exec) = self.narrowed_exec_complement(lo)
+            {
+                let bits = self.mask_dword(exec)?;
+                let ones = self.s.m.i32(u32::MAX);
+                return Ok(self.s.m.bin(self.cur, Bin::Xor, bits, ones));
+            }
+            if !whole || !full {
                 if self.mask_data == MaskData::Console && !self.local {
                     need(made.unwrap_or(0));
                 }
@@ -5405,9 +5437,20 @@ impl<'a> Lower<'a> {
 
     fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> {
         let v = inst.read(Reg::Scc).ok_or("an unread SCC")?;
-        match self.get(v)? {
-            Val::Bit(x) => Ok(x),
-            _ => Err("SCC without a value"),
+        match self.get(v) {
+            Ok(Val::Bit(x)) => Ok(x),
+            Err(LANE_MASK) if self.mask_ok && !self.x.p.wave64 && !self.local && self.exchange.is_none() => {
+                let block = *self.def_block.get(&v).ok_or(LANE_MASK)?;
+                let writer = self.x.p.blocks[block].insts.iter()
+                    .find(|op| op.write(Reg::Scc) == Some(v)).ok_or(LANE_MASK)?;
+                let dst = writer.writes.iter().find_map(|(reg, value)| matches!(reg, Reg::S(_)).then_some(*value))
+                    .filter(|&dst| self.narrowed_exec_complement(dst).is_some()).ok_or(LANE_MASK)?;
+                let bits = self.mask_dword(dst)?;
+                let zero = self.s.m.i32(0);
+                Ok(self.s.m.cmp(self.cur, pred::NE, bits, zero))
+            }
+            Err(why) => Err(why),
+            Ok(_) => Err("SCC without a value"),
         }
     }
 
@@ -11792,7 +11835,7 @@ mod tests {
         // A complement of EXEC holds lanes outside EXEC, but in an all-lanes
         // block of a native wave32 compute shader every lane runs the ballot.
         let words = [
-            0x8802_C17E, // s_xor_b32 s2, exec_lo, -1
+            0x8902_C17E, // s_xor_b32 s2, exec_lo, -1
             0x7E02_0202, // v_mov_b32 v1, s2
             0xD834_0000,
             0x0000_0100, // ds_write_b32 v0, v1

e4glevlr pushed a commit to e4glevlr/victory-fork that referenced this pull request Nov 25, 2026
…dress

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 41a3892)

Port notes: SLOT_VIEWS is t250 here: t252 is this fork's SLOT_VIEW_MARKS (fxceless#738 and this PR both took 252). The host heap keeps the view-mark table beside the view-address table. New lower tests go in emit/lower_tests.rs.
e4glevlr pushed a commit to e4glevlr/victory-fork that referenced this pull request Nov 25, 2026
…ograms

Ported in part from ea40c9a (fxceless#738).

A mask that holds lanes outside EXEC where it is written is the ballot
of every lane where every lane of the wave runs that block. That was
known only for two exchanging host waves; a native compute program's
wave is the console's, so its lane branches (all_lane_blocks) tell too.
A compute program refused with MASK_ELSEWHERE is now retried wide, as
one refused with LANE_MASK is.

Port notes: only the mask part of fxceless#738 is taken. Its buffer-address
table (SLOT_VIEW_ADDRESSES, t252) does what fxceless#749's SLOT_VIEWS does, which
this branch has, and t252 is this fork's SLOT_VIEW_MARKS.
e4glevlr added a commit to e4glevlr/victory-fork that referenced this pull request Nov 25, 2026
…s its address from SLOT_VIEWS

fxceless#738's case (the ray-tracing shadow-mask programs), which fxceless#749's view
table covers on this branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e4glevlr pushed a commit to e4glevlr/victory-fork that referenced this pull request Nov 25, 2026
A lane mask that holds lanes outside EXEC where it is written (the
complement of a ballot, `s_not` of a compare, or `s_orn2` against EXEC)
has bits no ballot in that block can give: the lanes they stand for do
not run there. Read as a number (a bit count, a store) in a block where
not every lane runs, mask_dword refused it with MASK_ELSEWHERE. In a
console wave32 compute program, which has no exchanging host waves, the
ballot path for such a mask never applied, so the pipeline was refused
and its dispatch dropped; only the wave64-on-32 retry forms could help
the others.

With console lanes (MaskData::Console, not a half-wave lowered on its
own), mask_dword now tries Lower::mask_number first: the scalar
operation writing the mask (s_mov, s_not, s_cselect, s_and, s_or, s_xor,
s_andn2, s_orn2, s_nand, s_nor, s_xnor, _b32 or _b64 by the console's
wave size) applied, dword by dword, to its operands' numbers, placed in
the block that writes it. Those operands are read as numbers in turn
(their ballots, exchanged halves, or the same rule again), so the
result is the console's mask bit for bit. Any other writer, or an
operand without a number, still refuses as before.

(ported in part from upstream commit 8af0472)

Port notes: only upstream's mask_number is taken, folded into the
fork's MASK_ELSEWHERE branch of mask_dword instead of upstream's
"lanes elsewhere" check; the 64-bit and f16 whole-wave section changes,
the s_mov_b64 split (the fork moves each dword by itself already) and
the diff-test case are left out. Differences from upstream: it returns
an Option and any failure falls back to the old refusal, unchanged (the
blocks its operands' exchanges asked for are dropped from the
widen-retry needs again); it is guarded by `balloting` against a mask
whose number needs itself; it is skipped under local half-waves; a
Bit-valued operand is refused rather than widened at the current block
(which need not dominate the writing block); a 64-bit operation does
not take float inline constants (they would be doubles). The phi check
is not needed: no instruction writes a phi, so it refuses anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit b54714d)

Port notes: on top of fxceless#738's mask part (all-lane blocks of native compute programs): a mask neither covers is its scalar op's number; the widening request stays for console lanes.

@BradRoland BradRoland left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I tested the lifetime of the new root SRV with two descriptor heaps on a single list. The second heap's buffer address can outlive the list's reference to its backing buffer.

let host = heap.host()?;
let gpu = host.addresses_gpu()?;
const ONCE: usize = usize::MAX - 0x5f;
if list.first_use(ONCE)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This key is shared by every heap on the list. If the list binds heap A, then B, then A again, the second call returns B’s GPU address while only A’s address buffer has been retained. The native descriptor heap and this separately allocated upload buffer have independent lifetimes. The title can release B before the GPU consumes that root SRV.

I reproduced this through State::bind with the PR’s synthetic shader on an RTX 4080. At list close and after synchronous submission, the list held A’s address table once and B’s zero times. Retaining each distinct table produced one reference to each. Reset released both. This checks ownership without dispatching against a freed buffer.

I put the correction and a focused regression in a single commit based on this exact PR head. The regression passed on WARP, and all 139 enabled tests passed in the hardware GPU suite. Cherry-pickable correction

PiloteCode pushed a commit to PiloteCode/victory-fork that referenced this pull request Nov 25, 2026
Allow native wave32/wave64 compute shaders (MaskData::Console, !local) to
check all_lane_blocks and trigger widen() on MASK_ELSEWHERE when a
complement mask sits inside a per-lane skip, unlocking the final
ray-tracing shadow-mask trace program.

Taken from fxceless#738 (ea40c9a, "shader,gpu: resolve
heap-loaded view addresses and widen native complement masks"): its
per-view-heap buffer-address table is already in this tree (e5eaaf2,
SLOT_VIEW_ADDRESSES), so only the mask widening and its test are taken.
PiloteCode added a commit to PiloteCode/victory-fork that referenced this pull request Nov 25, 2026
…am: 25,953 of 25,953), fxceless#196 loop exits with the host wave, fxceless#262 execz skips over loops, fxceless#213 a missing child is a miss, fxceless#788, fxceless#806, fxceless#748, fxceless#817 translate --hashes and translate-diff, fxceless#820, fxceless#694 one queue per test host
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants