From 2dd8ffce0dd17b090366c137d3c4def1445eb66e Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 20 Nov 2026 20:25:23 -0800 Subject: [PATCH] Identity domains: a texture atomic's slot is the R32 storage element its resource ID names A texture atomic (atomic_fetch_*, atomic_exchange, atomic_compare_exchange_weak, atomic_load or atomic_store on a texture1d, 1d_array, 2d, 2d_array or 3d of uint or int, access::read_write) declares its slot R32ui or R32i, as Vulkan's image atomics require and as Metal requires an R32Uint or R32Sint texture there. Under the identity domains identity_class refused every storage declaration with a format, so such a kernel was Unsupported{IdentityDomains}. It now admits an R32ui or R32i storage declaration as the class StorageFormatClass::Format(R32_UINT | R32_SINT), whose variable is the storage-image array's (set 1, binding 1, which every storage class aliases; no link or declaration change). The atomic's emission takes the element of that array at the index the slot's pushed resource ID holds (emit::identity_id), as a read or write does; it took the array variable itself before, which no path reached. The default domains are unchanged. Still refused under the identity domains: ulong atomics, texture-buffer atomics and an argument buffer's atomic texture. The CPU interpreter models OpImageTexelPointer (unmodelled before): a pointer to a texel inside its image (Root::Texel), through which an atomic reads and writes the texel's first component, as an atomic of an R32ui / R32i image does. Robustness's atomic outside the image and one on an unmapped texel stay unmodelled. Conformance: swizzled-storage-atomics now makes its pipeline and meets the runtime's Gap::SwizzledReadWrite at its first dispatch (case/RRRR/dispatch), where a read_write slot bound to a swizzled texture is refused; its known-gaps-rt.tsv row moves there and says why: Metal's atomic answers the texel unswizzled, but nothing yet says a slot's reads are atomics alone. Docs: RESOURCE-ID.md's arrays name the R32Uint / R32Sint storage class of a texture atomic; API.md's identity forms name a texture slot's atomics (the paragraph's lines reflowed); CONFORMANCE-COVERAGE.md re-derived for the atomics row's reason (REFUSALS.md re-derives unchanged). Test: engine_identity's a_texture_atomic_is_the_r32_storage_element_its_resource_id_names: a generated texture2d atomic_fetch_add under the identity domains on lavapipe, moltenvk-m3 and moltenvk-m3 without robust image access; each passes L3, its one image class is R32_UINT storage at set 1 binding 1, the guard's size query is there exactly where the device lacks robust image access, and on the CPU interpreter each thread adds 5 to its texel of element 2 (the one the pushed resource ID names), answers the texel it held, and no other element changes. SEMANTICS_VERSION 2233, one above development's (main renumbers at landing): a refusal becomes a module. The old runtime's render descriptor key changes with it (the_old_render_descriptor_key_keeps_its_value), pinned at landing. Verified (potluck; the jobs ran this diff on development 846f7c1428, and this commit is the same diff on 62c563f564, whose eight commits since touch none of its lines but SEMANTICS_VERSION and the API.md paragraph's neighbours): - m3-max-61334 (msi, at the WIP tree e55576964b, this commit's code and test before its ledger row and docs): cargo fmt --check, clippy with all features, with --cfg m2v_gpu and with --cfg m2v_cpu_icd, and Rustdoc -D warnings pass; nextest of metal2vulkan and metal2vulkan-conformance 4363 run, 4362 passed, the one failure the old render descriptor key above; the metal2vulkan-conformance suite under --cfg m2v_cpu_icd on lavapipe 1015 passed. - m3-max-61335 (um790, at e55576964b): conformance replay --cpu swizzled-storage-atomics on lavapipe makes the pipeline and is refused at case/RRRR/dispatch (Gap::SwizzledReadWrite). - m3-max-61438 (msi, llvmpipe LLVM 23.1.1, at the WIP tree ad62594111, this diff but the coverage document): conformance replay --cpu of swizzled-storage-atomics and the 13 read-through cases against the committed Metal answers: 14 refused, "exactly the open gaps known-gaps-rt.tsv expects", exit 0. - scripts/conformance-coverage/coverage.py and scripts/refusal-surface/refusal_surface.py run at this tree (the coverage document's one changed row is in this commit). - The next commit's states-only play over the 36 recorded streams runs this commit's code too. --- .../known-gaps-rt.tsv | 2 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- .../metal2vulkan/src/lower/texture/atomic.rs | 11 +- crates/metal2vulkan/src/lower/texture/slot.rs | 24 ++- crates/metal2vulkan/src/spirv/interp/eval.rs | 2 +- crates/metal2vulkan/src/spirv/interp/image.rs | 37 +++- .../metal2vulkan/src/spirv/interp/memory.rs | 36 ++++ crates/metal2vulkan/src/spirv/interp/value.rs | 4 + .../metal2vulkan/src/tests/engine_identity.rs | 162 +++++++++++++++++- docs/API.md | 15 +- docs/CONFORMANCE-COVERAGE.md | 2 +- docs/RESOURCE-ID.md | 3 +- 12 files changed, 275 insertions(+), 25 deletions(-) diff --git a/crates/metal2vulkan-conformance/known-gaps-rt.tsv b/crates/metal2vulkan-conformance/known-gaps-rt.tsv index a549e0beb..ee0469049 100644 --- a/crates/metal2vulkan-conformance/known-gaps-rt.tsv +++ b/crates/metal2vulkan-conformance/known-gaps-rt.tsv @@ -1900,7 +1900,7 @@ surface-textures-420v-chroma-rg8 NVIDIA refused case/replace-region Err(Error::R surface-textures-420v-luma-r8 NVIDIA refused case/replace-region Err(Error::Refused("the CPU reaches no Private or Memoryless texture")) rt's own gap: this device lays the case's two-plane surface in place under neither the dma-buf nor the opaque fd (53626: 0 in place, 2 copied), so the surface takes the copy form, in which a plane's texture is a texture over a buffer in the exported block, whose memory is Private, and rt refuses the CPU's replaceRegion: of it; Metal's texture over an IOSurface plane takes the CPU's write. The one-plane cases are in place here and compare. Why each handle took the copy form (SurfaceCopy) this run does not record. surface-textures-x420-chroma-rg16 NVIDIA refused case/replace-region Err(Error::Refused("the CPU reaches no Private or Memoryless texture")) rt's own gap: this device lays the case's two-plane surface in place under neither the dma-buf nor the opaque fd (53626: 0 in place, 2 copied), so the surface takes the copy form, in which a plane's texture is a texture over a buffer in the exported block, whose memory is Private, and rt refuses the CPU's replaceRegion: of it; Metal's texture over an IOSurface plane takes the CPU's write. The one-plane cases are in place here and compare. Why each handle took the copy form (SurfaceCopy) this run does not record. surface-textures-x420-luma-r16 NVIDIA refused case/replace-region Err(Error::Refused("the CPU reaches no Private or Memoryless texture")) rt's own gap: this device lays the case's two-plane surface in place under neither the dma-buf nor the opaque fd (53626: 0 in place, 2 copied), so the surface takes the copy form, in which a plane's texture is a texture over a buffer in the exported block, whose memory is Private, and rt refuses the CPU's replaceRegion: of it; Metal's texture over an IOSurface plane takes the CPU's write. The one-plane cases are in place here and compare. Why each handle took the copy form (SurfaceCopy) this run does not record. -swizzled-storage-atomics * refused case/pipeline/rrp_sw_atomic_u Err(Error::Translation("the translator made no pipeline: unsupported: IdentityDomains (texture argument SlotRef { stage: Kernel, class: Texture, index: 0 }: a type the identity arrays hold no element of, or state of the bound texture beyond its resource ID); needs NotImplemented")) refused: no stream uses it yet (states-only play 11-19, m3-max-56371-56373, 56375, player 44668b439f: 32 streams, every render and compute pipeline state made). The translator refuses the state (IdentityDomains: a form the identity domains do not lower); rt README, Known gaps of pipeline states. +swizzled-storage-atomics * refused case/RRRR/dispatch Err(Error::Unsupported("a read_write texture slot 0 bound to a swizzled texture is not built")) Known gap (rt README, Known gaps of textures): a read_write slot bound to a swizzled texture is Gap::SwizzledReadWrite, a texture atomic's slot among them, though Metal's atomic answers the texel unswizzled as the storage element does: the pipeline states nothing that says a slot's reads are atomics alone. swizzled-storage-made-rgba8unorm * refused case/GBAR/texture/parent Err(Error::Refused("a swizzled texture takes no shader-write or render-target usage")) refused: no stream uses it yet (full selector census 11-19, m3-max-53207-53208, 53213, 53217-53221: 26 streams, no texture descriptor of Unknown usage). A swizzled texture of MTLTextureUsageUnknown, which rt takes as every usage and so refuses as it refuses a swizzled texture of shader-write usage. Apple's MTLTextureUsage.unknown page makes Unknown "the most flexible usage option", and The M3 Max (macOS 27.0.1) makes the texture, its API validation layer on as well; the layer stops the case's later write, reading the texture's usage as 0x11. swizzled-storage-r32float * refused case/GRBA/rrp_sw_rwread_f/dispatch Err(Error::Unsupported("a read_write texture slot 0 bound to a swizzled texture is not built")) Known gap (rt README, Known gaps of textures): a read_write slot bound to a swizzled texture is Gap::SwizzledReadWrite, as its read would answer the texel unswizzled where Metal reads it through the swizzle. swizzled-storage-r32uint * refused case/GRBA/rrp_sw_rwread_u/dispatch Err(Error::Unsupported("a read_write texture slot 0 bound to a swizzled texture is not built")) Known gap (rt README, Known gaps of textures): a read_write slot bound to a swizzled texture is Gap::SwizzledReadWrite, as its read would answer the texel unswizzled where Metal reads it through the swizzle. diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 1febb9b3e..1fd1ad86a 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2232; +pub const SEMANTICS_VERSION: u32 = 2233; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/texture/atomic.rs b/crates/metal2vulkan/src/lower/texture/atomic.rs index 1a26db602..e51c804b7 100644 --- a/crates/metal2vulkan/src/lower/texture/atomic.rs +++ b/crates/metal2vulkan/src/lower/texture/atomic.rs @@ -236,7 +236,16 @@ pub(super) fn emit( let (Some(decl), Some((g, _))) = (decl, global) else { return Err(cx.fail(format!("texture slot {index} is not declared"))); }; - let ptr = fb.module().global_value(g)?; + let base = fb.module().global_value(g)?; + // Under the identity domains the slot's image is the element of its class's set-1 array at + // the index its resource ID holds (`emit::identity_id`). + let ptr = match cx.plan.families.access.identity { + true => { + let (element, _) = super::emit::identity_id(cx, fb, index)?; + fb.access_chain(base, &[element])? + } + false => base, + }; let coord = super::emit::coordinate(cx, fb, &decl, &a.at)?; // A texture buffer's parts: the part that holds the texel, at its index there; the guard // tests the texel against the whole width. diff --git a/crates/metal2vulkan/src/lower/texture/slot.rs b/crates/metal2vulkan/src/lower/texture/slot.rs index bded9089b..628237f59 100644 --- a/crates/metal2vulkan/src/lower/texture/slot.rs +++ b/crates/metal2vulkan/src/lower/texture/slot.rs @@ -1787,10 +1787,12 @@ impl SlotPlan { /// Under the identity domains, the class of the set-1 array whose elements texture slot /// declaration `decl` takes: its shape, numeric type and depth comparison, sampled, or a storage -/// image without a format (the floor's `shaderStorageImageWriteWithoutFormat`). `None` for a -/// declaration the identity arrays hold no element of yet: a cube viewed as an array, level views, -/// a texture buffer, its parts or rows, planes, an extended-range, RGBX or `ulong` form, or a -/// storage image with a format or a conversion. +/// image without a format (the floor's `shaderStorageImageWriteWithoutFormat`) or of a texture +/// atomic's `R32ui` / `R32i` ([`atomic_format`]: the format Metal requires of the bound texture +/// there, whose storage element is of that format). `None` for a declaration the identity arrays +/// hold no element of yet: a cube viewed as an array, level views, a texture buffer, its parts or +/// rows, planes, an extended-range, RGBX or `ulong` form, or a storage image with another format +/// or a conversion. pub(crate) fn identity_class(decl: &ImageDecl) -> Option { let plain = !decl.cube_as_array && decl.level_views.is_none() @@ -1810,7 +1812,14 @@ pub(crate) fn identity_class(decl: &ImageDecl) -> Option { _ => return None, }; let storage = decl.usage == ImageUsage::Storage; - if !plain || (storage && decl.format != crate::spv::ImageFormat::Unknown) { + let format = match (storage, decl.format) { + (false, _) => StorageFormatClass::NotStorage, + (true, crate::spv::ImageFormat::Unknown) => StorageFormatClass::Unknown, + (true, crate::spv::ImageFormat::R32ui) => StorageFormatClass::Format(vk::Format::R32_UINT), + (true, crate::spv::ImageFormat::R32i) => StorageFormatClass::Format(vk::Format::R32_SINT), + (true, _) => return None, + }; + if !plain { return None; } Some(ImageHandleClass { @@ -1823,9 +1832,6 @@ pub(crate) fn identity_class(decl: &ImageDecl) -> Option { true => ImageAccess::Storage, false => ImageAccess::Sampled, }, - format: match storage { - true => StorageFormatClass::Unknown, - false => StorageFormatClass::NotStorage, - }, + format, }) } diff --git a/crates/metal2vulkan/src/spirv/interp/eval.rs b/crates/metal2vulkan/src/spirv/interp/eval.rs index a8ef266be..032b35d3f 100644 --- a/crates/metal2vulkan/src/spirv/interp/eval.rs +++ b/crates/metal2vulkan/src/spirv/interp/eval.rs @@ -426,7 +426,6 @@ pub(super) fn exec(p: &Prog<'_>, l: &mut Lane, sh: &mut Shared, node: &InstNode) "a collective instruction reached lane evaluation", )) } - Inst::ImageTexelPointer { .. } => return unmodelled(crate::spv::Op::ImageTexelPointer), Inst::SampledImage { .. } => return unmodelled(crate::spv::Op::SampledImage), // The image half of a loaded combined image sampler is its bound image (`sched`). Inst::Image(x) => match get(l, *x)? { @@ -451,6 +450,7 @@ pub(super) fn exec(p: &Prog<'_>, l: &mut Lane, sh: &mut Shared, node: &InstNode) | Inst::ImageRead { .. } | Inst::ImageSparseTexelsResident(_) | Inst::ImageWrite { .. } + | Inst::ImageTexelPointer { .. } | Inst::ImageQuery { .. } => match super::image::exec(p, l, sh, &node.inst)? { Some(Some(v)) => v, Some(None) => return Ok(Flow::Next), diff --git a/crates/metal2vulkan/src/spirv/interp/image.rs b/crates/metal2vulkan/src/spirv/interp/image.rs index c638da55b..4e454c61b 100644 --- a/crates/metal2vulkan/src/spirv/interp/image.rs +++ b/crates/metal2vulkan/src/spirv/interp/image.rs @@ -1,7 +1,9 @@ //! Images: bound images, texel addressing, and the image instructions the new core emits for //! textures (`OpImageFetch`, `OpImageRead`, `OpImageWrite`, `OpImageQuery*`). A combined image //! sampler binds its image, and `OpImage` of it is that image (a pixel sampler's exact fetch); -//! there is no sampler state, so sampling itself is not modelled. +//! there is no sampler state, so sampling itself is not modelled. `OpImageTexelPointer` points to +//! a texel inside the image (`Root::Texel`): an atomic through it reads and writes the texel's +//! first component, as an atomic of an `R32ui` / `R32i` image does. //! //! **Sparse residency**. An image may leave texels unmapped ([`Image::unmapped`]), as a sparse //! image with unbound memory does. `OpImageSparseFetch` and `OpImageSparseRead` return the struct @@ -36,7 +38,7 @@ use crate::spirv::ir::{Dim, ImageOperands, ImageQuery, ImageType, Inst, Type}; use super::memory::Shared; use super::sched::{Lane, Prog}; -use super::value::{Root, Val}; +use super::value::{Ptr, Root, Val}; use super::{malformed, IResult, TrapKind, Unmodelled}; /// One image bound to a `UniformConstant` image binding (sampled, storage, or texel buffer), or @@ -355,6 +357,37 @@ pub(super) fn exec( } None } + // A pointer to a texel inside the image, an atomic's operand. Robustness's atomic outside + // the image, and one on an unmapped texel, are not modelled. + Inst::ImageTexelPointer { + image, + coord, + sample, + } => { + let unmodelled = || Unmodelled::Opcode(crate::spv::Op::ImageTexelPointer).err(); + let Val::P(Ptr { + root: Root::Image(k), + .. + }) = l.get(p, *image)? + else { + return Err(malformed("a texel pointer into no image")); + }; + let (_, ty) = p.t.pointee(p.t.value_ty(*image)?)?; + let Type::Image(img) = p.t.get(ty)? else { + return Err(malformed("a texel pointer into a pointer to no image")); + }; + let img = *img; + let c = l.get(p, *coord)?.comps()?; + let sample = l.get(p, *sample)?.s()?; + match texel(sh, k, &img, &c, 0, sample)? { + Ok(i) if !bound(sh, k)?.unmapped.contains(&i) => Some(Val::P(Ptr { + root: Root::Texel(k), + off: i as u64, + ms: None, + })), + _ => return Err(unmodelled()), + } + } Inst::ImageQuery { query, image } => { let (k, img) = image_of(p, l, *image)?; let level = match query { diff --git a/crates/metal2vulkan/src/spirv/interp/memory.rs b/crates/metal2vulkan/src/spirv/interp/memory.rs index e1dbe712c..dce49379c 100644 --- a/crates/metal2vulkan/src/spirv/interp/memory.rs +++ b/crates/metal2vulkan/src/spirv/interp/memory.rs @@ -180,6 +180,7 @@ impl Mem<'_> { Root::Buffer(i) => Ok((self.sh.bufs.get_mut(i as usize).ok_or_else(missing)?, off)), Root::Push => Ok((&mut self.sh.push, off)), Root::Image(_) => Err(super::malformed("a byte access to an image")), + Root::Texel(_) => Err(super::malformed("a byte region of a texel")), Root::BufferArray(_) => Err(super::malformed("a byte access to a descriptor array")), Root::Physical => { let hit = self.sh.bufs.iter_mut().find_map(|b| { @@ -200,12 +201,39 @@ impl Mem<'_> { } } + /// The first component of texel `i` of bound image `k` ([`Root::Texel`]), for an access of + /// `len` bytes, which must be the component's 4. + fn texel(&mut self, k: u32, i: u64, len: usize) -> IResult<&mut u32> { + if len != 4 { + return Err(super::malformed( + "a texel access that is not one 32-bit component", + )); + } + let image = self.sh.images.get_mut(k as usize); + let texel = image.and_then(|img| img.texels.get_mut(usize::try_from(i).ok()?)); + let [first, ..] = + texel.ok_or_else(|| super::malformed(format!("texel {i} of image {k}")))?; + Ok(first) + } + pub(super) fn read(&mut self, root: Root, off: u64, out: &mut [u8]) -> IResult<()> { + if let Root::Texel(k) = root { + let t = *self.texel(k, off, out.len())?; + out.copy_from_slice(&t.to_le_bytes()); + return Ok(()); + } let (r, rel) = self.region(root, off, out.len())?; r.read(rel, out) } pub(super) fn write(&mut self, root: Root, off: u64, data: &[u8]) -> IResult<()> { + if let Root::Texel(k) = root { + let t = self.texel(k, off, data.len())?; + let mut bytes = [0u8; 4]; + bytes.copy_from_slice(data); + *t = u32::from_le_bytes(bytes); + return Ok(()); + } let (r, rel) = self.region(root, off, data.len())?; r.write(rel, data) } @@ -218,6 +246,14 @@ impl Mem<'_> { len: usize, f: impl FnOnce(u64, u64) -> IResult<(u64, u64)>, ) -> IResult { + // A texel's component is always defined. + if let Root::Texel(k) = root { + let t = self.texel(k, off, len)?; + let old = u64::from(*t); + let (new, _) = f(old, u64::from(u32::MAX))?; + *t = new as u32; + return Ok(old); + } let (r, rel) = self.region(root, off, len)?; r.atomic(rel, len, f) } diff --git a/crates/metal2vulkan/src/spirv/interp/value.rs b/crates/metal2vulkan/src/spirv/interp/value.rs index f1dc66c31..8fa0f0b10 100644 --- a/crates/metal2vulkan/src/spirv/interp/value.rs +++ b/crates/metal2vulkan/src/spirv/interp/value.rs @@ -83,6 +83,10 @@ pub(super) enum Root { Physical, /// Bound image `n` (`UniformConstant`): loading the variable yields the image itself. Image(u32), + /// A texel of bound image `n` (`OpImageTexelPointer`, an atomic's operand): the offset is the + /// texel's index in its texels, and the pointer reaches the texel's first component, a 32-bit + /// integer. + Texel(u32), } /// A pointer: its memory object, byte offset, and the matrix stride of the matrix (or array of diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index 9bbc0550f..8747fe04b 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -32,6 +32,11 @@ //! the textures there, answers the width and `is_null_texture` by the index (0 for nil), and, //! where the shader checks reads (no `robustImageAccess2`), takes a format's missing alpha out of //! bounds from the word, as `tests/resource_words.tsv` gives it. +//! - A kernel's texture atomic (`ta`, generated: `atomic_fetch_add` on a `texture2d`) declares its slot `R32ui`, a class whose variable is the storage-image +//! array's. It passes L3 and, on the CPU interpreter, adds to the texels of the element its +//! pushed resource ID names and answers the texels they held, guarded by the element's size on +//! a device without robust image access. //! - The same kernel with its textures in an argument buffer (`tex` with `ab`) reads their //! resource IDs from the buffer's members, at its pushed address, and answers the same at the //! same elements, with no handle table and no descriptor; IDs whose indices are 65,536 past @@ -120,7 +125,10 @@ use crate::pipeline::facts::RuntimeFact; use crate::pipeline::interface::PushLoc; use crate::pipeline::layout::BindingSource; use crate::pipeline::link::{link, LinkInputs}; -use crate::pipeline::sym::{Axis, PushField, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage}; +use crate::pipeline::sym::{ + Axis, HandleClass, ImageAccess, PushField, ResourceKind, ResourceSlot, SampledType, SlotClass, + SlotRef, SpecKey, Stage, StorageFormatClass, +}; use crate::pipeline::testing::{ compile, compile_kept, compile_with, engine_dir, link_and_validate, llvm_assemble, profile, typed_module_with, AssembleError, @@ -1623,6 +1631,158 @@ fn textures_at_their_resource_ids(ab: bool) { } } +/// A kernel over a `4 × 2` grid that adds 5 to the texel at its position of `tex` (a +/// `texture2d`, slot 0) by `atomic_fetch_add`, and stores the texel's +/// old first component at word `y · 4 + x` of `out` (buffer 0). +const ATOMIC_KERNEL: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ +target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ +define void @ta(ptr addrspace(1) %tex, ptr addrspace(1) noundef \"air-buffer-no-alias\" %out, <2 x i32> noundef %tid) {\n\ +entry:\n\ + %old = tail call <4 x i32> @air.atomic_fetch_add_explicit_texture_2d.u.v4i32(ptr addrspace(1) %tex, <2 x i32> %tid, <2 x i32> zeroinitializer, <4 x i32> , i32 0, i32 3)\n\ + %x = extractelement <4 x i32> %old, i64 0\n\ + %tx = extractelement <2 x i32> %tid, i64 0\n\ + %ty = extractelement <2 x i32> %tid, i64 1\n\ + %row = mul i32 %ty, 4\n\ + %idx = add i32 %row, %tx\n\ + %e = zext i32 %idx to i64\n\ + %p = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %e\n\ + store i32 %x, ptr addrspace(1) %p, align 4\n\ + ret void\n\ +}\n\n\ +declare <4 x i32> @air.atomic_fetch_add_explicit_texture_2d.u.v4i32(ptr addrspace(1), <2 x i32>, <2 x i32>, <4 x i32>, i32, i32)\n\n\ +!air.kernel = !{!9}\n!air.version = !{!17}\n!air.language_version = !{!18}\n\ +!9 = !{ptr @ta, !10, !11}\n!10 = !{}\n!11 = !{!12, !13, !14}\n\ +!12 = !{i32 0, !\"air.texture\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.arg_type_name\", !\"texture2d\", !\"air.arg_name\", !\"tex\"}\n\ +!13 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"out\"}\n\ +!14 = !{i32 2, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint2\", !\"air.arg_name\", !\"tid\"}\n\ +!17 = !{i32 2, i32 8, i32 0}\n!18 = !{!\"Metal\", i32 4, i32 0, i32 0}\n"; + +/// A texture atomic's slot under the identity domains ([`ATOMIC_KERNEL`]: `atomic_fetch_add` on a +/// `texture2d`) is declared `R32ui`, a class of its own whose variable is +/// the storage-image array's (set 1, binding 1). On the CPU interpreter each thread adds to its +/// texel of the element the slot's pushed resource ID names and answers the texel it held, with the +/// atomic left to the device where it drops one outside the image, and guarded by the image's size +/// where it does not (no `robustImageAccess`); no other element changes. +#[test] +fn a_texture_atomic_is_the_r32_storage_element_its_resource_id_names() { + let Some(bc) = assemble_text("ta", ATOMIC_KERNEL) else { + return; + }; + const L: [u32; 3] = [4, 2, 1]; + // The texture at index 2 of the storage array; the elements below it are other textures. + const TEX: u32 = 2; + let word = vector_word(PixelFormat::R32Uint); + let held = |x: u32, y: u32| [0x100 * (y * 4 + x + 1), 0, 0, 1]; + let filler = |_: u32, _: u32| [0xdead_beef; 4]; + let mut profiles: Vec<(String, DeviceProfile)> = PROFILES + .iter() + .map(|stem| { + let p = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}")); + (stem.to_string(), p) + }) + .collect(); + profiles.push(( + "moltenvk-m3 without robust image access".to_string(), + identity_without( + "moltenvk-m3", + &[VkFeature::RobustImageAccess, VkFeature::RobustImageAccess2], + ), + )); + for (stem, p) in &profiles { + let (a, plan, module) = + compile_kept(&bc, "ta", p).unwrap_or_else(|e| panic!("{stem}: {e}")); + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem}: L3: {e}")); + let linked = link(&[&a], &LinkInputs::standalone(), p).unwrap_or_else(|e| panic!("{e}")); + let classes: Vec<_> = (linked.table.bindings.iter()) + .filter_map(|(slot, at)| match slot.kind { + ResourceKind::Heap(HandleClass::Image(c)) => Some((*slot, c, *at)), + _ => None, + }) + .collect(); + let [(storage, class, at)] = classes[..] else { + panic!("{stem}: {classes:?}"); + }; + assert_eq!( + (class.access, class.sampled_type, class.format, at), + ( + ImageAccess::Storage, + SampledType::Uint, + StorageFormatClass::Format(vk::Format::R32_UINT), + (1, 1) + ), + "{stem}" + ); + // The guard reads the element's size; a device that drops the atomic outside has none. + let queries = (module.functions().iter()) + .flat_map(|f| f.blocks.iter()) + .flat_map(|b| module.blocks()[b.index()].insts.iter()) + .filter(|n| matches!(n.inst, crate::spirv::ir::Inst::ImageQuery { .. })) + .count(); + let guarded = !p.fields().images.robust_image_access; + assert_eq!(queries > 0, guarded, "{stem}: {queries} size queries"); + let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)]; + for field in &plan.push.fields { + let PushLoc::Push { offset } = field.loc else { + panic!("{stem}: {field:?} spilled"); + }; + let o = offset as usize; + let bytes = match field.field { + PushField::SlotGuestBase(s) if s.class == SlotClass::Buffer => slot_word(OUT), + PushField::SlotGuestBase(s) if s.class == SlotClass::Texture => { + resource_id(TEX, word) + } + PushField::DispatchRegion => { + let region = region_bytes([0; 3], L, L).expect("packs"); + push[o..o + 32].copy_from_slice(®ion); + continue; + } + PushField::SlotBounds(_) => { + push[o..o + 8].copy_from_slice(&bounds_word(4 * 8, 0)); + continue; + } + PushField::ZeroAddress => ZERO_UNMAPPED, + _ => panic!("{stem}: unexpected push field {field:?}"), + }; + push[o..o + 8].copy_from_slice(&bytes.to_le_bytes()); + } + let mut images: Vec = (0..TEX) + .map(|e| texture(storage, e, [1, 1], filler, None)) + .collect(); + images.push(texture(storage, TEX, [4, 2], held, None)); + let res = Resources { + buffers: vec![Buffer { + slot: None, + address: Some(OUT), + bytes: vec![0; 4 * 8], + }], + push, + spec: local_size3(L), + }; + let (got, images) = run_with_images(&module, &Config::default(), res, images) + .unwrap_or_else(|e| panic!("{stem}: {e}")); + let texels = || (0..2).flat_map(|y| (0..4).map(move |x| (x, y))); + let old: Vec = texels() + .flat_map(|(x, y)| held(x, y)[0].to_le_bytes()) + .collect(); + assert_eq!(got.buffers[0], old, "{stem}: out"); + let added: Vec<[u32; 4]> = texels() + .map(|(x, y)| { + let [r, g, b, a] = held(x, y); + [r + 5, g, b, a] + }) + .collect(); + assert_eq!(images[TEX as usize].texels, added, "{stem}: the texture"); + for other in &images[..TEX as usize] { + assert_eq!( + other.texels, + [[0xdead_beef; 4]], + "{stem}: element {}", + other.element + ); + } + } +} + /// The read buffers of a kernel of [`many_of`]: with its output, 21 slot addresses of 8 bytes. const READS: u32 = 20; diff --git a/docs/API.md b/docs/API.md index 3f4c4d6f6..394d6485c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -211,13 +211,14 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: through its buffer slots and the device addresses it loads (an argument buffer's pointer member, a stored `gpuAddress`) or makes from integers, and reads, writes, sizes or tests for nil its texture slots and its argument buffers' textures, those of an argument buffer a pointer - member reaches included, and samples its texture slots through its runtime sampler slots and - its constexpr samplers. Any other function is refused as `Unsupported{IdentityDomains}`, - whose symbol names the first such form the function holds: one that samples through an - argument buffer's sampler or an array of samplers or samples an argument buffer's texture, - emulates a sampler's anisotropy, samples a 1D texture or at pixel coordinates through a bicubic - filter, uses a texture buffer, a slot's levels or swizzle, a two-plane, extended-range or - sRGB-twin form, reads an argument buffer's texture + member reaches included, updates its texture slots atomically (a slot declared `R32ui` or + `R32i`, the storage-image array's element at its ID's index), and samples its texture slots + through its runtime sampler slots and its constexpr samplers. Any other function is refused as + `Unsupported{IdentityDomains}`, whose symbol names the first such form the function holds: one + that samples through an argument buffer's sampler or an array of samplers or samples an argument + buffer's texture, emulates a sampler's anisotropy, samples a 1D texture or at pixel coordinates + through a bicubic filter, uses a texture buffer, a slot's levels or swizzle, a two-plane, + extended-range or sRGB-twin form, reads an argument buffer's texture through another numeric type or as raw texels, or uses any other state of a texture or sampler beyond its ID. An argument buffer's texture reads the element at its ID's index masked to its low 16 bits, diff --git a/docs/CONFORMANCE-COVERAGE.md b/docs/CONFORMANCE-COVERAGE.md index 00b95d6df..d94789f7d 100644 --- a/docs/CONFORMANCE-COVERAGE.md +++ b/docs/CONFORMANCE-COVERAGE.md @@ -3939,7 +3939,7 @@ A case whose difference from Metal is recorded rather than compared away. The le | `surface-textures-420v-luma-r8` | rt's own gap: this device lays the case's two-plane surface in place under neither the dma-buf nor the opaque fd (53626: 0 in place, 2 copied), so the surface t… | | `surface-textures-x420-chroma-rg16` | rt's own gap: this device lays the case's two-plane surface in place under neither the dma-buf nor the opaque fd (53626: 0 in place, 2 copied), so the surface t… | | `surface-textures-x420-luma-r16` | rt's own gap: this device lays the case's two-plane surface in place under neither the dma-buf nor the opaque fd (53626: 0 in place, 2 copied), so the surface t… | -| `swizzled-storage-atomics` | refused: no stream uses it yet (states-only play 11-19, m3-max-56371-56373, 56375, player 44668b439f: 32 streams, every render and compute pipeline state made).… | +| `swizzled-storage-atomics` | Known gap (rt README, Known gaps of textures): a read_write slot bound to a swizzled texture is Gap::SwizzledReadWrite, a texture atomic's slot among them, thou… | | `swizzled-storage-made-rgba8unorm` | refused: no stream uses it yet (full selector census 11-19, m3-max-53207-53208, 53213, 53217-53221: 26 streams, no texture descriptor of Unknown usage). A swizz… | | `swizzled-storage-r32float` | Known gap (rt README, Known gaps of textures): a read_write slot bound to a swizzled texture is Gap::SwizzledReadWrite, as its read would answer the texel unswi… | | `swizzled-storage-r32uint` | Known gap (rt README, Known gaps of textures): a read_write slot bound to a swizzled texture is Gap::SwizzledReadWrite, as its read would answer the texel unswi… | diff --git a/docs/RESOURCE-ID.md b/docs/RESOURCE-ID.md index 6ed8d66ab..33c596bdc 100644 --- a/docs/RESOURCE-ID.md +++ b/docs/RESOURCE-ID.md @@ -56,7 +56,8 @@ clamped to the edge; the comparison array's compares with `NEVER`) in each sampl Vulkan has no null sampler, and writes an element back to that once its owner goes. An index nobody owns, nil, freed or stale, reads as nil and cannot reach a destroyed view or sampler. Each texture class a shader declares (its shape, numeric type and depth -comparison, sampled, or storage without a format) is a variable of its descriptor type's binding. +comparison, sampled, or storage without a format, or storage of `R32Uint` or `R32Sint` for a +texture atomic) is a variable of its descriptor type's binding. A shader takes a texture slot's ID from the slot's push field (`PushField::SlotGuestBase`), and an argument buffer's texture's ID from the member's 8 bytes, with no table between. It indexes the