Skip to content

Shaders: image atomics on a handle of their own element type - #1756

Open
paulomatias97-create wants to merge 2 commits into
Marvisak:mainfrom
paulomatias97-create:shader/atomic64-u64-handle
Open

paulomatias97-create wants to merge 2 commits into
Marvisak:mainfrom
paulomatias97-create:shader/atomic64-u64-handle

Conversation

@paulomatias97-create

Copy link
Copy Markdown

Image atomics run on a handle annotated with the wrong elements. The handle cache is keyed by the first word of the resource properties only, so an image atomic after the image's size query reuses that query's handle, RWTexture2D<4xF32>. Separately, 64-bit atomics asked for U32 elements; DXC annotates a texture of 64-bit integers as U64.

  • Commit 1 keys the cache by both property words (the 32-bit atomics get U32 again).
  • Commit 2 annotates 64-bit atomics as U64 and adds a cross-platform test (64-bit umax, cmpswap with glc, swap of the returned value) that checks the module's 64-bit atomic features.

Verified

  • dxc -dumpbin on the test's module: before, the atomics use a RWTexture2D<4xF32> handle; after, RWTexture2D<U64>. Both versions pass dxv (DXC built from source), so the validator does not catch this.
  • cargo test -p victory-shader: 119 passed. cargo clippy -p victory-shader --all-targets --all-features --target x86_64-pc-windows-msvc -- -D warnings is clean.

Not verified

  • Not run on a GPU or with the title. Whether drivers read the annotation for typed atomics is unknown to me; DXC's output is the reference here.

🤖 Generated with Claude Code

https://claude.ai/code/session_01CL4QZxTrzfn3nkthzLyAtV

paulomatias97-create and others added 2 commits November 24, 2026 21:53
The handle cache was keyed by the properties' first word (kind and
flags) only, so an access wanting other element properties on a
descriptor already used took the earlier handle: an image atomic after a
size query annotated its texture as four floats. The key is now both
words.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CL4QZxTrzfn3nkthzLyAtV
The 64-bit image atomics annotated their texture's elements as U32, one
component, as the 32-bit ones do; DXC annotates a texture of 64-bit
integers as U64. A test lowers a program with 64-bit max, compare-
exchange and swap on any platform and checks the module's 64-bit atomic
features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CL4QZxTrzfn3nkthzLyAtV
@0xKaji

0xKaji commented Nov 24, 2026

Copy link
Copy Markdown

Verified ab3c38d on Linux + Wine 11.22 + vkd3d-proton 3.2.0 (GE-Proton11-14) + NVIDIA RTX 3060 8 GB (Ampere, driver 620.73.04), cross-built with cargo xwin (x86_64-pc-windows-msvc, VKD3D_DISABLE_EXTENSIONS=VK_NV_raw_access_chains).

Tests

  • Linux cargo test -p victory-shader --offline: 119 passed, 0 failed, 1 ignored.
  • Wine GPU test (emit::tests::a_64_bit_image_atomic_is_a_64_bit_atomic --test-threads=1): 1 passed, 0 failed (0.00s).

Live title A/B on 70564ae (diag build, VICTORY_D3D12_DRED=1)

  • 70564ae (baseline): crashed at +4 s (before frame 16) with err:vulkan:vkCreateComputePipelines Exception 0xc0000005 in Unix call.
  • 70564ae + PR Shaders: image atomics on a handle of their own element type #1756 (ab3c38d): 0 vkCreateComputePipelines exceptions; boots cleanly through menus into Stage (e) world rendering (frame=1024 presented with draws=5117 drawn=5117 dispatches=1116 dispatched=1116, reaching frame=1127 at +55 s before hitting the 8 GB VRAM ceiling on vkAllocateMemory), 0 GPU Xids.

@catminou4 catminou4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tested locally on macOS arm64 (rustc 1.98.1): PR head merged cleanly into current main (70564ae), cargo test -p victory-shader --locked → 119 passed, 0 failed. Hardware/valu/waterfall execution tests are #[cfg(all(test, windows))] and run only on Windows.

Image atomics on a handle of their own element type: image_atomic_64_cs builds the program and a_64_bit_image_atomic_is_a_64_bit_atomic checks the 64-bit atomic lowering. +23 macOS tests vs previous main baseline (new main added tests).

Marvisak commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

This pull request no longer merges cleanly into main (conflicts in crates/victory-shader/src/emit/lower.rs). It will be reviewed once it is rebased onto the current main. The earlier verdict (merge candidate) was for an older state of main.


Generated by Claude Code

@axknxla

axknxla commented Nov 25, 2026

Copy link
Copy Markdown

What

Thanks for the original fix. I prepared a local port of paulomatias97-create’s 32-bit cache-key commit onto upstream 67e8ae14. That base has block-local, entry-block, and control-flow join caches. The port includes both resource-property words in each key so a size query and an image atomic on the same descriptor get correctly typed handles.

The synthetic tests adapt acleofe’s size-query/atomic fixture from #1036 and cover all three cache paths. The diff is below if it helps with rebasing #1756.

Tested

  • Rust 1.98.1 on x86-64 Linux. The shader suite passed 161 tests, with 2 ignored. That run used temporary Windows guards for three existing validator calls.
  • All three new tests passed in an x86_64-pc-windows-gnullvm test binary under GE-Proton 11-14. Reverting each cache-key change individually made its matching synthetic test fail.
  • DXC disassembly of the synthetic outputs confirmed that the baseline atomic consumes the same float handle as the size query. With the port, the size query keeps its float handle and the atomic takes a separate U32 handle in all three cases. The DXIL validator accepted both builds.
  • The patch applies cleanly to 67e8ae14, passes git diff --check, and cargo xtask policy passed. Verification covers synthetic compiler output. GPU execution and the separate 64-bit commit remain untested here.

Codex assisted with the port, synthetic tests, and verification.

Source and synthetic test diff against 67e8ae1
diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs
index d61239c..d641ba4 100644
--- a/crates/victory-shader/src/emit/lower.rs
+++ b/crates/victory-shader/src/emit/lower.rs
@@ -60,6 +60,9 @@ pub(crate) struct Lowered {
     /// Heap handles written.
     #[cfg(test)]
     pub heap_handles: u32,
+    /// Properties of the annotated heap handles, in lowering order.
+    #[cfg(test)]
+    pub heap_props: Vec<(u32, u32)>,
     /// Whether the program uses wave operations.
     #[cfg(test)]
     pub wave_ops: bool,
@@ -208,15 +211,17 @@ struct Lower<'a> {
     scalar: HashMap<Site, Address>,
     exports: HashMap<Site, &'a Export>,
     interps: HashMap<Site, &'a Interp>,
-    handles: HashMap<(usize, Site, u8, bool, u32), V>,
+    // Handles with the same resource kind can still have different
+    // element types or structure strides. Cache by both property words.
+    handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>,
     /// Handles made in the entry block for descriptors at addresses the
     /// root parameters alone give (table and heap loads with no other
     /// term), by base value, byte offset, dword, offset register, sampler
     /// heap and properties ([`Lower::entry_address`]).
-    entry_handles: HashMap<(EntryAddress, u8, bool, u32), V>,
+    entry_handles: HashMap<(EntryAddress, u8, bool, (u32, u32)), V>,
     /// Handles of descriptors chosen by control flow, made in their join
     /// block, by the choice (its `Debug` text), sampler heap and properties.
-    join_handles: HashMap<(String, bool, u32), V>,
+    join_handles: HashMap<(String, bool, (u32, u32)), V>,
     /// Blocks splitting the edge from one IR block to another.
     edges: HashMap<(usize, usize), usize>,
     /// Per IR block: a `done` export is behind every lane entering it.
@@ -1382,6 +1387,8 @@ impl<'a> Lower<'a> {
             #[cfg(test)]
             heap_handles: self.s.m.written_calls("dx.op.createHandleFromHeap") as u32,
             #[cfg(test)]
+            heap_props: std::mem::take(&mut self.s.heap_props),
+            #[cfg(test)]
             wave_ops: self.s.flags & flags::WAVE_OPS != 0,
             #[cfg(test)]
             rovs: self.s.flags & flags::ROVS != 0,
@@ -5129,7 +5136,7 @@ impl<'a> Lower<'a> {
                 // compiler reloads one before every use rather than keep it
                 // (ActivateRays: 2,399 loads of one), and one handle made in
                 // the entry block serves them all.
-                let key = (address, *first, sampler, props.0);
+                let key = (address, *first, sampler, props);
                 if let Some(&h) = self.entry_handles.get(&key) {
                     return Ok(h);
                 }
@@ -5142,7 +5149,7 @@ impl<'a> Lower<'a> {
                 Ok(h)
             }
             Source::Loaded { load, first } => {
-                let key = (self.cur, *load, *first, sampler, props.0);
+                let key = (self.cur, *load, *first, sampler, props);
                 if let Some(&h) = self.handles.get(&key) {
                     return Ok(h);
                 }
@@ -5251,7 +5258,7 @@ impl<'a> Lower<'a> {
                 // One handle at the join for every access the choice reaches
                 // (each is in a block the join dominates).
                 let _ = site;
-                let key = (format!("{src:?}"), sampler, props.0);
+                let key = (format!("{src:?}"), sampler, props);
                 if let Some(&h) = self.join_handles.get(&key) {
                     return Ok(h);
                 }
@@ -11274,6 +11281,87 @@ mod tests {
         }
     }
 
+    fn check_image_atomic_after_size_query(load: &[u32]) {
+        let mut words = vec![
+            0xBE84_0300, // s_mov_b32 s4, s0
+            0xBE85_0380, // s_mov_b32 s5, 0
+        ];
+        words.extend_from_slice(load);
+        words.extend([
+            0x7E04_0300, // v_mov_b32 v2, v0
+            0x7E06_0300, // v_mov_b32 v3, v0
+            0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0)
+            0xF038_0F08,
+            0x0002_0400, // image_get_resinfo v[4:7], v0, s[8:15] dmask:0xf dim:2D
+            0xBF8C_3F70, // s_waitcnt vmcnt(0)
+            0xF044_0108,
+            0x0002_0402, // image_atomic_add v4, v[2:3], s[8:15] dmask:0x1 dim:2D
+            S_ENDPGM,
+        ]);
+        let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)];
+        let used = [0, 8]
+            .into_iter()
+            .map(|table_offset_dwords| UsedResource {
+                kind: ResourceType::Uav,
+                root: RootType::Table,
+                table_offset_dwords,
+                lower_bound: 0,
+                stride: 0,
+                dwords: 8,
+                user_data: 0,
+                slot: 0,
+            })
+            .collect();
+        let l = lower_with(&words, layout, used).unwrap();
+        // The size query uses float elements and the atomic uses u32.
+        assert!(
+            l.heap_props.contains(&(2 | 0x1000, 0x409)),
+            "{:?}",
+            l.heap_props
+        );
+        assert!(
+            l.heap_props.contains(&(2 | 0x1000, 0x105)),
+            "{:?}",
+            l.heap_props
+        );
+        assert!(l.heap_handles >= 2, "{}", l.heap_handles);
+    }
+
+    #[test]
+    fn image_atomic_after_size_query_at_a_fixed_table_offset_uses_u32() {
+        check_image_atomic_after_size_query(&[
+            0xF40C_0202,
+            0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0
+        ]);
+    }
+
+    #[test]
+    fn image_atomic_after_size_query_at_a_dynamic_table_offset_uses_u32() {
+        check_image_atomic_after_size_query(&[
+            0x7E28_0500, // v_readfirstlane_b32 s20, v0
+            0xF40C_0202,
+            0x2800_0000, // s_load_dwordx8 s[8:15], s[4:5], s20
+        ]);
+    }
+
+    #[test]
+    fn image_atomic_after_size_query_of_a_joined_descriptor_uses_u32() {
+        check_image_atomic_after_size_query(&[
+            0xBF06_8001, // s_cmp_eq_u32 s1, 0
+            0xBF84_0003, // s_cbranch_scc0 -> inner if
+            0xF40C_0202,
+            0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0
+            0xBF82_0008, // s_branch -> join
+            0xBF06_8101, // s_cmp_eq_u32 s1, 1
+            0xBF84_0003, // s_cbranch_scc0 -> inner else
+            0xF40C_0202,
+            0xFA00_0020, // s_load_dwordx8 s[8:15], s[4:5], 0x20
+            0xBF82_0002, // s_branch -> join
+            0xF40C_0202,
+            0xFA00_0000, // s_load_dwordx8 s[8:15], s[4:5], 0
+        ]);
+    }
+
     #[test]
     fn scalar_bit_tests_lower() {
         // Each tests one bit of a constant into SCC and branches on it (only
diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs
index 441dae7..1276e18 100644
--- a/crates/victory-shader/src/emit/shader.rs
+++ b/crates/victory-shader/src/emit/shader.rs
@@ -140,6 +140,9 @@ pub(crate) struct Shader {
     pub flags: u64,
     /// Heap handles made with a non-uniform index.
     pub nonuniform_handles: u32,
+    /// Resource properties used to annotate each heap handle.
+    #[cfg(test)]
+    pub heap_props: Vec<(u32, u32)>,
     /// A compute shader with this thread-group size.
     pub threads: Option<[u32; 3]>,
     /// The wave size a compute shader requires (`WaveSize`).
@@ -205,6 +208,8 @@ impl Shader {
             texture_reads: Vec::new(),
             flags: 0,
             nonuniform_handles: 0,
+            #[cfg(test)]
+            heap_props: Vec::new(),
             threads: None,
             wave_size: None,
             lds_dwords: 0,
@@ -540,6 +545,8 @@ impl Shader {
             flags::RESOURCE_HEAP
         };
         self.nonuniform_handles += u32::from(nonuniform);
+        #[cfg(test)]
+        self.heap_props.push(props);
         // An index past the host's heap faults the device (a console shader
         // reads whatever memory follows its heap): the last slot instead.
         let last = self.m.i32(if sampler { HEAP_SAMPLERS } else { HEAP_VIEWS } - 1);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants