diff --git a/crates/metal2vulkan-conformance/known-gaps.tsv b/crates/metal2vulkan-conformance/known-gaps.tsv index 6ada86da4..15ca8ce3e 100644 --- a/crates/metal2vulkan-conformance/known-gaps.tsv +++ b/crates/metal2vulkan-conformance/known-gaps.tsv @@ -87,10 +87,6 @@ discard-quad-sum-placement llvmpipe (LLVM 21.1.8, 128 bits) divergent case/count argb8-targets-destination-alpha * refused case/pipeline/argb8 Err(Error::Unsupported("unsupported: Unsupported { feature: Format, needs: NotImplemented, location: Some(RenderPipeline at Color(0)), symbol: None }")) Plain Metal on this M3 Max makes and runs a render pipeline whose ARGB8Unorm colour attachment blends with DestinationAlpha and OneMinusDestinationAlpha in the COLOUR factors, and stores every texel as the RGBA8Unorm leg's bytes rotated (recorded here over 3 runs, 8,192 texels, zero mismatches; Metal's own API validation let it run). The runtime refuses the pipeline Unsupported(Format, NotImplemented) at colour attachment 0, so the refusal is of something plain Metal does. The cause is structural rather than a policy: the runtime holds ARGB8Unorm in an R8G8B8A8_UNORM image of the rotated bytes, so the image's alpha channel carries Metal's BLUE and a colour factor that must read Metal's destination alpha would have to read the image's red. Vulkan has no such blend factor. The alpha-factor direction is already solved -- a second pipeline output of copies of Metal's source alpha (pipeline::rotated_blend) -- but that trick does not reach a DESTINATION channel, which only the framebuffer holds. The exact forms are a pass that keeps the rotated image's channels in Metal's order behind a swizzled view, or reading the destination in the fragment where the device offers programmable blending. Neither is built. Fix belongs in metal2vulkan's pipeline (rotated_blend) and the runtime's ARGB8Unorm image layout. On the orchestrator's todo list as runtime work. binary-archive-mesh-adder * refused case/program Err({refused: Unavailable({call: "addMeshRenderPipelineFunctionsWithDescriptor"}), step: 1 (0x1)}) `BinaryArchive` has three of Metal's four pipeline adders: `addMeshRenderPipelineFunctionsWithDescriptor:error:` has no counterpart at all. Metal takes the call, takes it a second time with the same descriptor, and then serialises the archive to a file that exists and holds bytes (measured on this M3 Max, macOS 27.0.1, from this case's own committed recording over three runs, plain Metal and under its API validation, which let the case run). Ours cannot be asked: crates/metal2vulkan-runtime/src/binary_archive/mod.rs declares `add_compute_pipeline_functions` (:138), `add_render_pipeline_functions` (:161) and `add_tile_render_pipeline_functions` (:194) and no mesh form, and the module's own documentation lists the three as if they were all of them. The pieces for the fourth are already there: `metal2vulkan::pipeline::MeshPipelineDescriptor` exists and the runtime creates mesh states from it (crates/metal2vulkan-runtime/src/pipeline/render.rs:629), and the add's own shape is the render one -- create the state with `Some(&used)`, then keep what it used under the descriptor's archive keys -- so what is missing is the key function beside `metal_key::render` (crates/metal2vulkan-runtime/src/binary_archive/metal_key.rs:185) for an object-plus-mesh-plus-fragment triple, and the `check` arm that refuses a mesh creation on a miss (`binary_archive::check` is already called for the mesh path at crates/metal2vulkan-runtime/src/pipeline/render.rs:1579, where the comment says outright that no archive holds a mesh render pipeline). It is deliberately NOT done here: adding `BinaryArchive::add_mesh_render_pipeline_functions` adds an item to a published crate's public surface and a new archive key form to its container, which needs docs/REFUSALS.md regenerated and the `api_surface` table updated, and this stream took no evidence for either. Every venue's: the gap is in the runtime's own API, before any Vulkan call. Open: for whoever takes the runtime's archive surface. binary-archive-sources * divergent case/program/from-a-metallib/refused Metal false, ours true Metal accepts a **metallib** as a binary archive and we refuse it. Measured on this M3 Max (macOS 27.0.1) from this case's own committed recording over three runs: `newBinaryArchiveWithDescriptor:error:` with the descriptor's `url` set to a metallib of the case's own shader answers an archive, where the same call over a text file, an empty file, a missing path and a directory each answers `MTLBinaryArchiveDomain` code 1 (the four rows this case compares beside it, all four of which we match exactly). What Metal does with such an archive is not measured here -- whether it holds anything, or is simply an empty archive that happens to have read a container it recognises -- and that is the first thing the fix needs. Ours refuses at `container::read` (crates/metal2vulkan-runtime/src/binary_archive/container.rs:183), which reads the file whole and hands it to `decode`, whose first act is to check the suite-private magic `M2VBARCH` and a version word (container.rs:116, the magic at :37); a metallib starts `MTLB`, so `decode` answers `None` and the creation becomes `BinaryArchive(InvalidFile)` (container.rs:240). By the owner's standing rule that what Metal allows we must allow, the refusal is the bug. The fix is to decide what a non-archive container means and say so: either accept a file that parses as a metallib as an archive that holds no entry (which is what Metal's answer is consistent with, and which `Library::from_metallib` can already tell), or keep refusing and record an accepted difference in docs/API.md section 10. The first changes a published crate's documented refusal surface -- `Device::new_binary_archive`'s own doc comment states that a file that is missing or not an archive is `BinaryArchive(InvalidFile)` 'as Metal answers for a missing, empty, garbage or text file and for a directory', a list measured on an M3 Max and an M4 that is correct as far as it goes and simply never asked about a metallib -- so it is not this stream's call. Every venue's: the refusal is in the container reader, before any Vulkan call. Open: for whoever takes the runtime's archive surface. -attribute-stride-buffer * divergent case/nine-strides 7 elements differ (U32), the largest difference 16 Metal's `MTLAttributeStrideStatic` on a `[[stage_in]]` layout of `MTLBufferLayoutStrideDynamic` is not "read at stride 0"; it fetches the element at the bind offset for the FIRST element and hands every element past it ZERO. Measured on this M3 Max (macOS 27.0.1) from these cases' own committed recordings: a dynamic layout over a buffer holding `0x10 + e` at element `e`, eight threads stepping by thread position in x at rate 1, bound with the constant, answered `0x110` and then `0x100` seven times (the fixture writes the attribute plus `0x100`), while a bind at stride 0 answered `0x110` eight times -- so the two are different answers and Metal's validation stops neither. The same shape at a bind offset of 8 answered `0x112` and then `0x100` seven times, which says the bind offset still reaches the first element. Ours answers the stride-0 reading: `attribute_stride` (crates/metal2vulkan-runtime/src/argument_table.rs:377) maps the constant to `None`, `None` removes the index's entry from `ArgumentTable::attribute_strides`, and every reader of that map takes a missing entry as 0 -- the binder's push constant `PushField::StageInStride` (crates/metal2vulkan/src/lower/stage_io/stage_in.rs:179, whose own module note at line 28 says "as 0 for a buffer bound without one") and the reach check (crates/metal2vulkan-runtime/src/fetch_reach.rs:112). So the fetch walks elements at stride 0 and every thread reads element 0, which is a silently wrong answer rather than a refusal. The runtime already knows the real behaviour for ONE of the four setters: `ComputeCommandEncoder::set_bytes_with_stride` (crates/metal2vulkan-runtime/src/compute.rs:607) documents "an M4 read element 0 of the bytes and zeros past it" and refuses that combination `NotImplemented(KernelStageIn)` rather than emulating it -- this oracle shows the buffer forms behave the same way, so the note on the buffer forms (argument_table.rs:377 and compute.rs:509, "one bound without a stride reads at stride 0") is what is wrong, not the inline-bytes one. The fix belongs in the fetch, not in the table: `PushField::StageInStride` needs to be able to say "the constant was bound" apart from "stride 0" -- a sentinel value or a flag beside it -- and the pulled read in crates/metal2vulkan/src/lower/stage_io/stage_in.rs must then select the element at the bind offset where the element index is 0 and a zero of the attribute's form otherwise, which is the same predicate the inline-bytes form would need and would let that refusal be dropped too. It is deliberately NOT done here: this stream's target is the conformance suite, the change is to a published crate's shader lowering and its push-constant ABI (so it moves `SEMANTICS_VERSION` and every stage-in recording), and it needs release-mode evidence this stream has not taken. Scoped to every venue because the gap is in the push constant and the fetch's own arithmetic, before any device behaviour -- measured on this M3 Max alone, so every other venue is expected and unaudited. Open: for whoever takes the runtime's stage-in fetch. -attribute-stride-plural-buffers * divergent case/nine-strides 7 elements differ (U32), the largest difference 16 Metal's `MTLAttributeStrideStatic` on a `[[stage_in]]` layout of `MTLBufferLayoutStrideDynamic` is not "read at stride 0"; it fetches the element at the bind offset for the FIRST element and hands every element past it ZERO. Measured on this M3 Max (macOS 27.0.1) from these cases' own committed recordings: a dynamic layout over a buffer holding `0x10 + e` at element `e`, eight threads stepping by thread position in x at rate 1, bound with the constant, answered `0x110` and then `0x100` seven times (the fixture writes the attribute plus `0x100`), while a bind at stride 0 answered `0x110` eight times -- so the two are different answers and Metal's validation stops neither. The same shape at a bind offset of 8 answered `0x112` and then `0x100` seven times, which says the bind offset still reaches the first element. Ours answers the stride-0 reading: `attribute_stride` (crates/metal2vulkan-runtime/src/argument_table.rs:377) maps the constant to `None`, `None` removes the index's entry from `ArgumentTable::attribute_strides`, and every reader of that map takes a missing entry as 0 -- the binder's push constant `PushField::StageInStride` (crates/metal2vulkan/src/lower/stage_io/stage_in.rs:179, whose own module note at line 28 says "as 0 for a buffer bound without one") and the reach check (crates/metal2vulkan-runtime/src/fetch_reach.rs:112). So the fetch walks elements at stride 0 and every thread reads element 0, which is a silently wrong answer rather than a refusal. The runtime already knows the real behaviour for ONE of the four setters: `ComputeCommandEncoder::set_bytes_with_stride` (crates/metal2vulkan-runtime/src/compute.rs:607) documents "an M4 read element 0 of the bytes and zeros past it" and refuses that combination `NotImplemented(KernelStageIn)` rather than emulating it -- this oracle shows the buffer forms behave the same way, so the note on the buffer forms (argument_table.rs:377 and compute.rs:509, "one bound without a stride reads at stride 0") is what is wrong, not the inline-bytes one. The fix belongs in the fetch, not in the table: `PushField::StageInStride` needs to be able to say "the constant was bound" apart from "stride 0" -- a sentinel value or a flag beside it -- and the pulled read in crates/metal2vulkan/src/lower/stage_io/stage_in.rs must then select the element at the bind offset where the element index is 0 and a zero of the attribute's form otherwise, which is the same predicate the inline-bytes form would need and would let that refusal be dropped too. It is deliberately NOT done here: this stream's target is the conformance suite, the change is to a published crate's shader lowering and its push-constant ABI (so it moves `SEMANTICS_VERSION` and every stage-in recording), and it needs release-mode evidence this stream has not taken. Scoped to every venue because the gap is in the push constant and the fetch's own arithmetic, before any device behaviour -- measured on this M3 Max alone, so every other venue is expected and unaudited. Open: for whoever takes the runtime's stage-in fetch. -attribute-stride-buffer-offset * divergent case/nine-strides-and-two-offsets 14 elements differ (U32), the largest difference 18 Metal's `MTLAttributeStrideStatic` on a `[[stage_in]]` layout of `MTLBufferLayoutStrideDynamic` is not "read at stride 0"; it fetches the element at the bind offset for the FIRST element and hands every element past it ZERO. Measured on this M3 Max (macOS 27.0.1) from these cases' own committed recordings: a dynamic layout over a buffer holding `0x10 + e` at element `e`, eight threads stepping by thread position in x at rate 1, bound with the constant, answered `0x110` and then `0x100` seven times (the fixture writes the attribute plus `0x100`), while a bind at stride 0 answered `0x110` eight times -- so the two are different answers and Metal's validation stops neither. The same shape at a bind offset of 8 answered `0x112` and then `0x100` seven times, which says the bind offset still reaches the first element. Ours answers the stride-0 reading: `attribute_stride` (crates/metal2vulkan-runtime/src/argument_table.rs:377) maps the constant to `None`, `None` removes the index's entry from `ArgumentTable::attribute_strides`, and every reader of that map takes a missing entry as 0 -- the binder's push constant `PushField::StageInStride` (crates/metal2vulkan/src/lower/stage_io/stage_in.rs:179, whose own module note at line 28 says "as 0 for a buffer bound without one") and the reach check (crates/metal2vulkan-runtime/src/fetch_reach.rs:112). So the fetch walks elements at stride 0 and every thread reads element 0, which is a silently wrong answer rather than a refusal. The runtime already knows the real behaviour for ONE of the four setters: `ComputeCommandEncoder::set_bytes_with_stride` (crates/metal2vulkan-runtime/src/compute.rs:607) documents "an M4 read element 0 of the bytes and zeros past it" and refuses that combination `NotImplemented(KernelStageIn)` rather than emulating it -- this oracle shows the buffer forms behave the same way, so the note on the buffer forms (argument_table.rs:377 and compute.rs:509, "one bound without a stride reads at stride 0") is what is wrong, not the inline-bytes one. The fix belongs in the fetch, not in the table: `PushField::StageInStride` needs to be able to say "the constant was bound" apart from "stride 0" -- a sentinel value or a flag beside it -- and the pulled read in crates/metal2vulkan/src/lower/stage_io/stage_in.rs must then select the element at the bind offset where the element index is 0 and a zero of the attribute's form otherwise, which is the same predicate the inline-bytes form would need and would let that refusal be dropped too. It is deliberately NOT done here: this stream's target is the conformance suite, the change is to a published crate's shader lowering and its push-constant ABI (so it moves `SEMANTICS_VERSION` and every stage-in recording), and it needs release-mode evidence this stream has not taken. Scoped to every venue because the gap is in the push constant and the fetch's own arithmetic, before any device behaviour -- measured on this M3 Max alone, so every other venue is expected and unaudited. Open: for whoever takes the runtime's stage-in fetch. -attribute-stride-inline-bytes * refused case/outcome/step/16/dispatchThreadgroups Err(Error::Bind("the bind state was refused: Unsupported(Unsupported { feature: KernelStageIn, needs: NotImplemented, location: None, symbol: None })")) The runtime refuses a kernel's `[[stage_in]]` fetch of INLINE BYTES bound with `MTLAttributeStrideStatic`, where plain Metal answers. Measured on this M3 Max (macOS 27.0.1) from this case's own committed recording: `setBytes:length:attributeStride:atIndex:` of the source bytes with the constant, under a dynamic-stride layout, answered `0x110` and then `0x100` seven times -- the element at the bind offset for the first element and zero past it -- and the command buffer completed. Ours refuses at the dispatch, `Unsupported(KernelStageIn)`, from the bind state; `ComputeCommandEncoder::set_bytes_with_stride` (crates/metal2vulkan-runtime/src/compute.rs:607) documents exactly that refusal and exactly that measured Metal answer, saying the fetch does not emulate it. By the owner's standing rule that what Metal allows we must allow, the refusal is a gap and not a settled difference. It is the same gap as the three `attribute-stride-*` divergences beside it and has the same fix -- teach `PushField::StageInStride` to say "the constant was bound" apart from "stride 0" and have the pulled read in crates/metal2vulkan/src/lower/stage_io/stage_in.rs select the first element and zeros past it -- after which this refusal can be dropped. The buffer forms answer the wrong value instead of refusing, which is the worse half of the same bug; this form at least fails visibly. Scoped to every venue because the refusal is in the encoder's bind state, before any Vulkan call. Open: for whoever takes the runtime's stage-in fetch. format-footprints-plain-stragglers * refused case/MTLPixelFormatARGB8Unorm_sRGB/Type2D/64x64x1/levels-1/samples-1/slices-1/usage-0x1/shared/makes-texture Err(Error::Unsupported("unsupported: Unsupported { feature: Format, needs: NotImplemented, location: None, symbol: Some(\"MTLPixelFormatARGB8Unorm_sRGB\") }")) Plain Metal makes a texture of `ARGB8Unorm_sRGB` in all eight non-multisample texture types and takes a host `replaceRegion:`/`getBytes:` round trip through each (an Apple M3 Max under macOS 27.0.1, in a throwaway process forked per (format, texture type); the whole of its answer is in this case's recording). The runtime refuses `newTextureWithDescriptor:` `Unsupported(Format, NotImplemented)` out of the translator's format table (crates/metal2vulkan/src/metal/format/mod.rs, the `formats_named_not_held!` pattern, whose `repr` is `NotImplemented`; the refusal reaches this site through `image_error` in crates/metal2vulkan-runtime/src/texture.rs). The cause is NOT that the bytes have no Vulkan format: they are `ARGB8Unorm`'s (alpha in byte 0, then red, green and blue), which this crate holds in `R8G8B8A8_UNORM` read through a rotating view, and `fill_value.rs` already states this format's own layout as a linear alpha byte and three sRGB bytes. It is that no Vulkan format applies the sRGB transfer function to the three channels Metal's does: every Vulkan `_SRGB` format encodes the word's low three components and leaves the fourth linear, so the function would land on Metal's alpha and miss Metal's blue. A view's component mapping cannot move it, because format conversion runs before the component swizzle, so `R8G8B8A8_SRGB` under `ARGB8Unorm`'s rotation would read Metal's alpha sRGB-decoded and Metal's blue linear -- two channels of four wrong, which is not a near-equivalent a precision note could carry. The exact form is the one a device that cannot sample an 8-bit sRGB format already takes: hold the codes in a UNORM image (here `ARGB8Unorm`'s `R8G8B8A8_UNORM` image through its rotating view) and decode them in the shader through Metal's twelve-bit table (`metal::format::srgb_raw_twin`, `metal::texel_format::srgb_twin_on`, `RuntimeFact::SrgbTexture`, `lower::arith::srgb`), here as the only read of the format on every device, since no view of this image decodes it, so a clear, a blit and a colour attachment of it must take the same route. That is not built. Open: translator and runtime work, in metal2vulkan's format table and the UNORM twin's format map with the runtime's image plan and binder. Its sibling straggler `BGRA4Unorm` is held, which is why the case reaches this format. Scoped `*` and not to a venue: the refusal is decided by the format table before any device is consulted, so no device can change it; verified on MoltenVK over this M3 Max (2026-10-25), unverified elsewhere by execution. format-footprints-one-plane-ycbcr * refused case/MTLPixelFormatYCBCR8_422_1P/Type2D/64x64x1/levels-1/samples-1/slices-1/usage-0x1/shared/makes-texture Err(Error::Unsupported("unsupported: Unsupported { feature: Format, needs: NotImplemented, location: None, symbol: Some(\"MTLPixelFormatYCBCR8_422_1P\") }")) The runtime answers Metal's heap footprint for Apple's nine one-plane YCbCr formats, which is arithmetic over a descriptor, but holds no image of any of them, so `newTextureWithDescriptor:` is refused `Unsupported(Format, NotImplemented)` out of the translator's format table (crates/metal2vulkan/src/metal/format/mod.rs, the `formats_named_not_held!` pattern, whose `repr` is `NotImplemented`; the refusal reaches this site through `image_error` in crates/metal2vulkan-runtime/src/texture.rs). Measured on an Apple M3 Max under macOS 27.0.1, plain Metal, in a throwaway process forked per (format, texture type): Metal answers a size and an alignment for every descriptor of this case, makes a texture of every format in every texture type bar the ones the case's own module records, and takes a host round trip through each. The whole of Metal's answer is in this case's recording, which is what an implementation will be held to. The case STOPS at this first refusal by design: the runtime holds no image of any of the 33 formats of the family, so recording a refusal per site and going on would print some 2900 `Refused` rows and need a ledger row for each. So this one row stands for the family, and the open work -- an image for each format -- is on the orchestrator's todo list with the measurements. Scoped `*` and not to a venue: the refusal is decided by the format table before any device is consulted, so no device can change it; verified on MoltenVK over this M3 Max (2026-10-25), unverified elsewhere by execution. format-footprints-padded-wide-channels * refused case/MTLPixelFormatRGB10A2Unorm_PQ/Type2D/64x64x1/levels-1/samples-1/slices-1/usage-0x1/shared/makes-texture Err(Error::Unsupported("unsupported: Unsupported { feature: Format, needs: NotImplemented, location: None, symbol: Some(\"MTLPixelFormatRGB10A2Unorm_PQ\") }")) The runtime answers Metal's heap footprint for the ten padded 10- and 12-bit display formats, which is arithmetic over a descriptor, but holds no image of any of them, so `newTextureWithDescriptor:` is refused `Unsupported(Format, NotImplemented)` out of the translator's format table (crates/metal2vulkan/src/metal/format/mod.rs, the `formats_named_not_held!` pattern, whose `repr` is `NotImplemented`; the refusal reaches this site through `image_error` in crates/metal2vulkan-runtime/src/texture.rs). Measured on an Apple M3 Max under macOS 27.0.1, plain Metal, in a throwaway process forked per (format, texture type): Metal answers a size and an alignment for every descriptor of this case, makes a texture of every format in every texture type bar the ones the case's own module records, and takes a host round trip through each. The whole of Metal's answer is in this case's recording, which is what an implementation will be held to. The case STOPS at this first refusal by design: the runtime holds no image of any of the 33 formats of the family, so recording a refusal per site and going on would print some 2900 `Refused` rows and need a ledger row for each. So this one row stands for the family, and the open work -- an image for each format -- is on the orchestrator's todo list with the measurements. Scoped `*` and not to a venue: the refusal is decided by the format table before any device is consulted, so no device can change it; verified on MoltenVK over this M3 Max (2026-10-25), unverified elsewhere by execution. diff --git a/crates/metal2vulkan-conformance/src/cases/attribute_strides.rs b/crates/metal2vulkan-conformance/src/cases/attribute_strides.rs index e0b2d803a..7be0d0960 100644 --- a/crates/metal2vulkan-conformance/src/cases/attribute_strides.rs +++ b/crates/metal2vulkan-conformance/src/cases/attribute_strides.rs @@ -29,14 +29,12 @@ //! | `2^33 + 4` | as `4`, by the truncation | //! | `2^63 + 8` | as `8`, by the truncation | //! -//! **The constant's row is measured, not predicted, and it is not what the runtime's prose said.** -//! A dynamic layout bound with `MTLAttributeStrideStatic` was expected to read at stride 0, the way -//! a buffer bound by the plain setters does. Metal does something else: it fetches the element at -//! the bind offset for the first thread and hands every later thread zeros. The runtime documents -//! exactly that for the **inline-bytes** form (`set_bytes_with_stride`, measured on an M4) and -//! stride 0 for the buffer forms; this oracle answers the inline-bytes behaviour for all four -//! setters. The recordings are the claim, and a reader who trusted the buffer forms' note would -//! have written the wrong expectation. +//! **The constant's row is measured, not predicted.** A dynamic layout bound with +//! `MTLAttributeStrideStatic` does not read at stride 0, the way a buffer bound by the plain +//! setters does: it fetches the element at the bind offset for the first thread and hands every +//! later thread zeros, in all four setters. That is a fetch at the constant's low 32 bits, +//! `2^32 - 1`, by the same truncation as every other row: element 1 lies that many bytes on, past +//! the buffer. The recordings are the claim. //! //! **Which values are indistinguishable by construction, and why.** Nine values gave **five** //! distinct answers, so four values duplicate another's and the groups are named rather than left diff --git a/crates/metal2vulkan-runtime/src/argument_table.rs b/crates/metal2vulkan-runtime/src/argument_table.rs index 944bc68a9..8a1121ebf 100644 --- a/crates/metal2vulkan-runtime/src/argument_table.rs +++ b/crates/metal2vulkan-runtime/src/argument_table.rs @@ -25,11 +25,13 @@ //! core, whichever slot binds it: a bind before each draw, and a draw that binds objects an //! earlier draw of the encoder bound, retain nothing of their own. //! -//! A compute encoder's table differs in one answer, as plain Metal's compute encoder gave it on an -//! M4 where its API validation asserts: it holds a buffer bound past its length, which a dispatch +//! A compute encoder's table differs in two answers. As plain Metal's compute encoder gave it on an +//! M4 where its API validation asserts, it holds a buffer bound past its length, which a dispatch //! refuses only where the kernel reads the slot (a read there is past the buffer: memory decides -//! it). A render stage's table refuses that at the call, as Metal's validation does; plain Metal's -//! render form is not measured. +//! it); a render stage's table refuses that at the call, as Metal's validation does, and plain +//! Metal's render form is not measured. And its stride forms hold `MTLAttributeStrideStatic` as +//! the stride its low 32 bits name, `2^32 - 1`, where a render stage's table holds no stride for +//! it ([`per_bind_stride`]). //! //! An offset set at an index with no buffer bound is no change in either, as plain Metal's render //! and compute encoders both take it ([`ArgumentTable::take_buffer_offset`]). @@ -68,8 +70,9 @@ pub(super) const BUFFER_SLOTS: u32 = 31; pub(super) const TEXTURE_SLOTS: u32 = 128; /// Entries of a sampler table (`setSamplerState:atIndex:` and its stage forms). pub(super) const SAMPLER_SLOTS: u32 = 16; -/// `MTLAttributeStrideStatic`: the stride argument that sets no per-bind stride, so the buffer -/// is read at its layout's own stride, as by the plain setters. +/// `MTLAttributeStrideStatic`: the stride argument of the stride forms that a render stage's +/// table holds as no per-bind stride, as the plain setters bind, and a compute table as the +/// stride `2^32 - 1` ([`per_bind_stride`]). pub(super) const ATTRIBUTE_STRIDE_STATIC: u64 = u64::MAX; /// The most bytes one `setBytes:length:atIndex:` (or a stage form) takes: Metal's documented /// limit for inline bytes, 4 KiB. @@ -152,9 +155,9 @@ pub(super) struct ArgumentTable { /// Neither `buffers` nor `function_tables` holds them. pub(super) null_tables: BTreeSet, /// The per-bind attribute strides of buffers in `buffers`, by index - /// (`setBuffer:offset:attributeStride:atIndex:` and its forms): a layout of - /// `MTLBufferLayoutStrideDynamic` reads its buffer at this stride. The plain setters bind - /// with `MTLAttributeStrideStatic`, which sets none. + /// (`setBuffer:offset:attributeStride:atIndex:` and its forms, [`per_bind_stride`]): a layout + /// of `MTLBufferLayoutStrideDynamic` reads its buffer at this stride. The plain setters set + /// none, which such a layout reads at stride 0. pub(super) attribute_strides: BTreeMap, pub(super) textures: BTreeMap, /// The indices of `textures` that hold a memoryless texture, a texture buffer's too: none, @@ -450,13 +453,23 @@ pub(super) fn check_bound_buffer( Ok(()) } -/// The per-bind stride `stride` names: none for `MTLAttributeStrideStatic`, else its low 32 -/// bits. Plain Metal reads a stride past 32 bits so, and its validation takes it (an M4 under macOS -/// 27.0.1 and an M3 Max under 26.7, compute stage-in and vertex fetch, both binding forms: `2^32 + -/// 8` and `2^63 + 8` read at 8, `2^33 + 4` at 4, `2^32` at 0). -fn attribute_stride(stride: u64) -> Option { +/// The per-bind stride a stride form's `stride` names in a compute table (`compute`) or a render +/// stage's: its low 32 bits. Plain Metal reads a stride past 32 bits so, and its validation takes +/// it (an M4 under macOS 27.0.1 and an M3 Max under 26.7, compute stage-in and vertex fetch, both +/// binding forms: `2^32 + 8` and `2^63 + 8` read at 8, `2^33 + 4` at 4, `2^32` at 0). +/// +/// `MTLAttributeStrideStatic` (`u64::MAX`) is no exception in a compute table: its low 32 bits, +/// `2^32 - 1`, are the stride a kernel's stage-in layout of `MTLBufferLayoutStrideDynamic` reads. +/// Plain Metal on an Apple M3 Max under macOS 27.0.1 answered each of the four stride forms bound +/// so with the element at the bind offset for the first element and zero for every element past +/// it, the bind offset reaching the first (`metal2vulkan-conformance`'s `attribute-stride-*` +/// recordings, a buffer of 512 bytes), which is a fetch at that stride: element 1 lies `2^32 - 1` +/// bytes on, past the buffer (an indirect command buffer's command read the byte there in a buffer +/// that holds it, `RuntimeGap::IndirectCommandUnstridedBuffer`). A render stage's table holds no +/// stride for it, as the plain setters bind (`render/vertex_strides.rs`). +pub(super) fn per_bind_stride(stride: u64, compute: bool) -> Option { // Truncation is the measured answer. - (stride != ATTRIBUTE_STRIDE_STATIC).then_some(stride as u32) + (compute || stride != ATTRIBUTE_STRIDE_STATIC).then_some(stride as u32) } /// Bind `value` at `index` of `table`, or unbind the index when `value` is `None`: what was @@ -666,9 +679,9 @@ impl ArgumentTable { check_bound_buffer(core.device(), call, (buffer, offset), self.compute) } - /// `setBuffer:offset:atIndex:` (`None` unbinds the index) in an encoder of `core`: the - /// stride form with `MTLAttributeStrideStatic`. Refused: an index past the table, a buffer of - /// another device, and in a render stage's table an offset past the buffer's length. + /// `setBuffer:offset:atIndex:` (`None` unbinds the index) in an encoder of `core`, with no + /// per-bind stride. Refused: an index past the table, a buffer of another device, and in a + /// render stage's table an offset past the buffer's length. pub(super) fn set_buffer( &mut self, core: &mut EncoderCore, @@ -677,11 +690,11 @@ impl ArgumentTable { offset: u64, index: u32, ) -> Result<(), Error> { - self.set_buffer_with_stride(core, call, buffer, offset, ATTRIBUTE_STRIDE_STATIC, index) + self.bind_buffer(core, call, buffer, offset, None, index) } /// `setBuffer:offset:attributeStride:atIndex:` (`None` unbinds the index) in an encoder of - /// `core`, a stride past 32 bits taken modulo `2^32`. Refused as + /// `core`, at the per-bind stride `stride` names ([`per_bind_stride`]). Refused as /// [`set_buffer`](Self::set_buffer) is. pub(super) fn set_buffer_with_stride( &mut self, @@ -691,11 +704,25 @@ impl ArgumentTable { offset: u64, stride: u64, index: u32, + ) -> Result<(), Error> { + let stride = per_bind_stride(stride, self.compute); + self.bind_buffer(core, call, buffer, offset, stride, index) + } + + /// [`set_buffer_with_stride`](Self::set_buffer_with_stride) at the per-bind stride `stride`, + /// none for the plain setter. + fn bind_buffer( + &mut self, + core: &mut EncoderCore, + call: &'static str, + buffer: Option<&Buffer>, + offset: u64, + stride: Option, + index: u32, ) -> Result<(), Error> { let same = buffer.is_some_and(|buffer| self.binds_buffer(index, buffer)); self.changed_as(SlotClass::Buffer, index..index.saturating_add(1), same); check_index(call, index, BUFFER_SLOTS)?; - let stride = attribute_stride(stride); if let Some(buffer) = buffer { self.check_buffer(core, call, buffer, offset)?; self.note_bound(core, Bound::Buffer(buffer)); @@ -712,7 +739,7 @@ impl ArgumentTable { } /// `setBuffers:offsets:withRange:`: `buffers[i]` at offset `offsets[i]` at index `first + i`, - /// every stride `MTLAttributeStrideStatic`. Refused as [`set_buffer`](Self::set_buffer) is, + /// with no per-bind stride. Refused as [`set_buffer`](Self::set_buffer) is, /// and when the slices' lengths differ; a refusal binds none of them. pub(super) fn set_buffers( &mut self, @@ -726,8 +753,8 @@ impl ArgumentTable { } /// `setBuffers:offsets:attributeStrides:withRange:`: as [`set_buffers`](Self::set_buffers), - /// each buffer at stride `strides[i]` (modulo `2^32`) where `strides` is given. Refused as - /// `set_buffers` is. + /// each buffer at the per-bind stride `strides[i]` names ([`per_bind_stride`]) where `strides` + /// is given. Refused as `set_buffers` is. pub(super) fn set_buffers_with_strides( &mut self, core: &mut EncoderCore, @@ -747,7 +774,9 @@ impl ArgumentTable { self.check_buffer(core, call, buffer, offset)?; } } - let strides = (0..buffers.len()).map(|i| strides.and_then(|s| attribute_stride(s[i]))); + let compute = self.compute; + let strides = + (0..buffers.len()).map(|i| strides.and_then(|s| per_bind_stride(s[i], compute))); for (((buffer, &offset), stride), index) in buffers.iter().zip(offsets).zip(strides).zip(first..) { @@ -766,8 +795,9 @@ impl ArgumentTable { Ok(()) } - /// `setBufferOffset:atIndex:`: the stride form with `MTLAttributeStrideStatic`, so it clears - /// the index's stride, as the plain buffer setters do. Measured for the vertex form on an M4: + /// `setBufferOffset:atIndex:`: it clears the index's stride, as the plain buffer setters do, + /// and as the stride form with `MTLAttributeStrideStatic` does in a render stage's table. + /// Measured for the vertex form on an M4: /// after a stride form, Metal's validation stops the draw for "providing /// `MTLAttributeStrideStatic` to `attributeStride` when stride at buffer-layout index 0 is /// dynamic", and Metal without it reads the buffer at stride 0. Every stage's form sets this @@ -787,12 +817,12 @@ impl ArgumentTable { offset: u64, index: u32, ) -> Result<(), Error> { - self.set_buffer_offset_with_stride(core, call, offset, ATTRIBUTE_STRIDE_STATIC, index) + self.move_buffer_offset(core, call, offset, None, index) } - /// `setBufferOffset:attributeStride:atIndex:` with `stride` (`MTLAttributeStrideStatic` - /// clears the index's stride; a stride past 32 bits is taken modulo `2^32`). Refused as - /// [`set_buffer_offset`](Self::set_buffer_offset) is. + /// `setBufferOffset:attributeStride:atIndex:` with the per-bind stride `stride` names + /// ([`per_bind_stride`]: `MTLAttributeStrideStatic` clears the index's stride in a render + /// stage's table). Refused as [`set_buffer_offset`](Self::set_buffer_offset) is. pub(super) fn set_buffer_offset_with_stride( &mut self, core: &mut EncoderCore, @@ -800,6 +830,20 @@ impl ArgumentTable { offset: u64, stride: u64, index: u32, + ) -> Result<(), Error> { + let stride = per_bind_stride(stride, self.compute); + self.move_buffer_offset(core, call, offset, stride, index) + } + + /// [`set_buffer_offset_with_stride`](Self::set_buffer_offset_with_stride) at the per-bind + /// stride `stride`, none for the plain setter. + fn move_buffer_offset( + &mut self, + core: &mut EncoderCore, + call: &'static str, + offset: u64, + stride: Option, + index: u32, ) -> Result<(), Error> { // A buffer bound there keeps being bound, at another offset; inline bytes and a // visible-function table are another change. @@ -808,7 +852,6 @@ impl ArgumentTable { && self.buffers.contains_key(&index); self.changed_as(SlotClass::Buffer, index..index.saturating_add(1), same); check_index(call, index, BUFFER_SLOTS)?; - let stride = attribute_stride(stride); if let Some(len) = self.bytes.get(&index).map(|bytes| bytes.len) { // Inline bytes then read as zeros, at any offset, until the index is bound again: // plain Metal on an M4 read 64 zero bytes after `setBytes` of 64 then an offset of diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index d52eb9a09..28a0ed9c2 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -508,12 +508,14 @@ impl ComputeCommandEncoder { } /// `setBuffer:offset:attributeStride:atIndex:`: as [`set_buffer`](Self::set_buffer), the - /// buffer read at `stride` by a kernel's stage-in layout of `MTLBufferLayoutStrideDynamic`; - /// `MTLAttributeStrideStatic` (`u64::MAX`) sets no stride, as `set_buffer` does. Only such a - /// layout reads a stride, and one bound without a stride reads at stride 0; a layout of a - /// fixed stride reads its own whatever the bind's (as an M4 reads them). A stride past 32 bits - /// other than `MTLAttributeStrideStatic` is taken modulo `2^32`, as plain Metal reads it and - /// its validation takes it (an M4 and an M3 Max). Refused as `set_buffer` is. + /// buffer read at `stride` by a kernel's stage-in layout of `MTLBufferLayoutStrideDynamic`. + /// Only such a layout reads a stride, and one bound without a stride (`set_buffer`) reads at + /// stride 0; a layout of a fixed stride reads its own whatever the bind's (as an M4 reads + /// them). A stride past 32 bits is taken modulo `2^32`, as plain Metal reads it and its + /// validation takes it (an M4 and an M3 Max), and `MTLAttributeStrideStatic` (`u64::MAX`) with + /// it: such a layout reads the element at the bind offset for the first element and zero for + /// every element past it, which lies `2^32 - 1` bytes on, past the buffer, as plain Metal on an + /// M3 Max under macOS 27.0.1 answered it. Refused as `set_buffer` is. pub fn set_buffer_with_stride( &mut self, buffer: Option<&Buffer>, @@ -567,8 +569,8 @@ impl ComputeCommandEncoder { /// `setBufferOffset:attributeStride:atIndex:`: as [`set_buffer_offset`](Self::set_buffer_offset), /// with the index's stride set as [`set_buffer_with_stride`](Self::set_buffer_with_stride) - /// sets it. `set_buffer_offset` clears the stride, as the stride form with - /// `MTLAttributeStrideStatic` does. Refused as both are. + /// sets it, `MTLAttributeStrideStatic` included. `set_buffer_offset` clears the stride. + /// Refused as both are. pub fn set_buffer_offset_with_stride( &mut self, offset: u64, @@ -609,9 +611,9 @@ impl ComputeCommandEncoder { /// `setBytes:length:attributeStride:atIndex:`: as [`set_bytes`](Self::set_bytes), the /// bytes read at `stride`, its low 32 bits, by a kernel's stage-in layout of - /// `MTLBufferLayoutStrideDynamic`. At `MTLAttributeStrideStatic` (`u64::MAX`) such a layout is - /// refused at the dispatch (`NotImplemented(KernelStageIn)`): an M4 read element 0 of the - /// bytes and zeros past it there, which the fetch does not emulate. Refused as `set_bytes` is. + /// `MTLBufferLayoutStrideDynamic`, as [`set_buffer_with_stride`](Self::set_buffer_with_stride) + /// reads a buffer: at `MTLAttributeStrideStatic` (`u64::MAX`) such a layout reads element 0 of + /// the bytes and zero past it, as an M4 and an M3 Max read them. Refused as `set_bytes` is. pub fn set_bytes_with_stride( &mut self, bytes: &[u8], diff --git a/crates/metal2vulkan-runtime/src/fetch_reach.rs b/crates/metal2vulkan-runtime/src/fetch_reach.rs index 78d154439..184a2d7ff 100644 --- a/crates/metal2vulkan-runtime/src/fetch_reach.rs +++ b/crates/metal2vulkan-runtime/src/fetch_reach.rs @@ -3,10 +3,10 @@ //! //! - **What differs.** Metal fetches an attribute at the displacement `element · stride + //! offset` from its buffer's bind offset in 64 bits. The compile layer fetches a vertex attribute -//! it pulls, and every kernel stage-in attribute, at that displacement in wrapping 32-bit -//! arithmetic, each byte at the displacement plus its place (`lower::stage_io::fetch`). So where -//! the buffer holds more than `2^32` bytes past its bind offset, a byte past `2^32` reads another -//! place of the buffer than Metal's, silently. +//! it pulls at that displacement in wrapping 32-bit arithmetic, each byte at the displacement +//! plus its place, and a kernel stage-in attribute whose bytes lie past `2^32` as zero bytes +//! (`lower::stage_io::fetch`). So where the buffer holds more than `2^32` bytes past its bind +//! offset, a byte past `2^32` reads another place of the buffer than Metal's, or zero, silently. //! - **The refusal.** Until the fetch takes 64-bit displacements, a fetch that may read past `2^32` //! bytes of its buffer's bind offset, inside a buffer that runs past them, is refused, naming the //! buffer index and the furthest byte it may read; one that may not runs as before, and so does @@ -108,7 +108,7 @@ pub(crate) fn check_stage_in_reach( continue; } // A layout of `MTLBufferLayoutStrideDynamic` reads the bound stride, 0 for a buffer bound - // without one. + // without one (`MTLAttributeStrideStatic`'s is `2^32 - 1`). let stride = layout.stride.unwrap_or_else(|| { table .attribute_strides diff --git a/crates/metal2vulkan-runtime/src/tests/argument_table.rs b/crates/metal2vulkan-runtime/src/tests/argument_table.rs index 804713846..8d66d6e20 100644 --- a/crates/metal2vulkan-runtime/src/tests/argument_table.rs +++ b/crates/metal2vulkan-runtime/src/tests/argument_table.rs @@ -3,9 +3,37 @@ //! without printing it (`same_as_printed`); and the offset a table takes at an index with no //! buffer bound, which a render stage's table answers as a compute one does. -use super::super::argument_table::{same_as_printed, ArgumentTable}; +use super::super::argument_table::{per_bind_stride, same_as_printed, ArgumentTable}; use metal2vulkan::bind::{BoundSampler, SamplerDescriptor, StageTable}; +/// A stride form's stride is its low 32 bits in both tables, and `MTLAttributeStrideStatic`'s +/// (`u64::MAX`) too in a compute table, where a kernel's stage-in layout of +/// `MTLBufferLayoutStrideDynamic` reads `2^32 - 1` and so the element at the bind offset and zero +/// past it, as plain Metal on an Apple M3 Max under macOS 27.0.1 answered all four compute stride +/// forms (`metal2vulkan-conformance`'s `attribute-stride-*` recordings). A render stage's table +/// holds no stride for it, as the plain setters bind. +#[test] +fn the_static_constant_is_a_compute_tables_widest_stride() { + for compute in [false, true] { + for (stride, held) in [ + (0u64, 0u32), + (8, 8), + (1 << 32, 0), + ((1 << 32) + 8, 8), + ((1 << 63) + 8, 8), + (u64::from(u32::MAX), u32::MAX), + ] { + assert_eq!( + per_bind_stride(stride, compute), + Some(held), + "{stride} {compute}" + ); + } + } + assert_eq!(per_bind_stride(u64::MAX, true), Some(u32::MAX)); + assert_eq!(per_bind_stride(u64::MAX, false), None); +} + /// `setBufferOffset:atIndex:`, and its stride form, at an index with no buffer bound: a render /// stage's table answers exactly as a compute one does, and neither keeps anything /// (`ArgumentTable::take_buffer_offset`). Plain Metal keeps no offset there and the draw reads diff --git a/crates/metal2vulkan/src/bind/dispatch.rs b/crates/metal2vulkan/src/bind/dispatch.rs index b3b3116f4..db942bb86 100644 --- a/crates/metal2vulkan/src/bind/dispatch.rs +++ b/crates/metal2vulkan/src/bind/dispatch.rs @@ -938,23 +938,16 @@ fn instantiate( PushField::StageInRegion => stage_in_region_bytes(region.ok_or_else(|| { internal("a stage-in region push field without the region's fact") })?), - // The stride the encoder bound the stage-in buffer with, 0 without one, as Metal - // reads a dynamic layout; inline bytes' alike, but at `MTLAttributeStrideStatic`, whose - // answer is not measured. + // The stride the encoder bound the stage-in buffer or inline bytes with, 0 without + // one, as Metal reads a dynamic layout: `MTLAttributeStrideStatic`'s is its low 32 + // bits, whose elements past the first the fetch reads past the bind offset's 2^32 + // bytes (`lower::stage_io::fetch`). PushField::StageInStride(index) => { let stride = match state .stages .get(&Stage::Kernel) .and_then(|k| k.buffers.get(&index)) { - Some(&BoundBuffer::Bytes { - attribute_stride: Some(u32::MAX), - .. - }) => { - return Err(BindError::Unsupported(Unsupported::not_implemented( - Feature::KernelStageIn, - ))) - } Some( &BoundBuffer::Buffer { attribute_stride: Some(s), diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 898b439bb..47a60a9e4 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -1330,10 +1330,10 @@ pub enum BoundBuffer { /// `MTLBufferLayoutStrideDynamic` reads the bytes at; `None` for the plain setters, which /// such a layout reads at stride 0, as plain Metal reads them. /// `MTLAttributeStrideStatic` is `Some(u32::MAX)`, its low 32 bits: an M4 read element 0 - /// of inline bytes bound so and zeros past it, where a buffer bound so reads stride 0; - /// the binder refuses a layout that reads inline bytes at that stride - /// ([`BindError::MissingVertexStride`](crate::error::BindError::MissingVertexStride), and - /// a kernel's stage-in `NotImplemented(KernelStageIn)`). + /// of inline bytes bound so and zeros past it, which a kernel's stage-in fetch reads at + /// that stride (every element past the first lies past the bytes); the binder refuses a + /// vertex layout that reads inline bytes at it + /// ([`BindError::MissingVertexStride`](crate::error::BindError::MissingVertexStride)). #[cfg_attr(feature = "serde", serde(default))] attribute_stride: Option, }, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 4d4386a7b..00249d1a3 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,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 = 1980; +pub const SEMANTICS_VERSION: u32 = 1981; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 490; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1786; +pub const RUNTIME_VERSION: u32 = 1784; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/lower/access/pulled.rs b/crates/metal2vulkan/src/lower/access/pulled.rs index 7e2808ea5..72c34a98d 100644 --- a/crates/metal2vulkan/src/lower/access/pulled.rs +++ b/crates/metal2vulkan/src/lower/access/pulled.rs @@ -198,6 +198,17 @@ pub fn view_read( n: u32, ) -> BResult { let off = fb.binary(BinOp::IAdd, residual, m)?; + view_read_at(fb, view, check, off, n) +} + +/// [`view_read`] at the view's own byte offset `off`. +fn view_read_at( + fb: &mut FunctionBuilder<'_>, + view: View, + check: Check, + off: SValue, + n: u32, +) -> BResult { let inb = match check { Check::None => None, Check::InShader => match views::storage_bytes(fb, view)? { @@ -249,6 +260,80 @@ pub fn prepare( n: u32, check: Check, ) -> BResult { + match source(cx, fb, buffer)? { + Source::View { view, residual } => view_read(fb, view, check, residual, m, n), + Source::Psb { + table, + start, + contained, + } => psb_read(fb, table, buffer, m, start, n, contained), + } +} + +/// [`prepare`] of a read whose `u32` Metal displacement `m` is Metal's own only where `fits` (a +/// bool) holds, the read's `n` bytes then lying in the first `2^32` bytes from the bind offset. +/// Where it does not, and in a view where the bind residual plus `m` and its `n` bytes run past +/// `2^32` (the view's own offset would wrap), the read lies past the first `2^32` bytes of the +/// slot: outside every buffer a command that may read past them is not refused for (the +/// runtime's `StageInFetchPast4GiB`), and outside every view's range. It then reads at the bind +/// offset and yields zero bytes, Metal's answer for a fetch outside its buffer there, on every +/// device, its robustness aside: a wrapped offset could land inside the buffer. +pub fn prepare_within( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + buffer: u32, + m: SValue, + fits: SValue, + n: u32, + check: Check, +) -> BResult { + let (read, fits) = match source(cx, fb, buffer)? { + Source::View { view, residual } => { + // `residual + m + n <= 2^32`: the sum did not wrap, and its end fits. + let off = fb.binary(BinOp::IAdd, residual, m)?; + let kept = fb.binary(BinOp::UGreaterThanEqual, off, residual)?; + let room = k32(fb, u32::MAX - n.saturating_sub(1))?; + let ends = fb.binary(BinOp::ULessThanEqual, off, room)?; + let view_fits = fb.binary(BinOp::LogicalAnd, kept, ends)?; + let fits = fb.binary(BinOp::LogicalAnd, fits, view_fits)?; + let off = fb.select(fits, off, residual)?; + (view_read_at(fb, view, check, off, n)?, fits) + } + Source::Psb { + table, + start, + contained, + } => { + let zero = k32(fb, 0)?; + let m = fb.select(fits, m, zero)?; + (psb_read(fb, table, buffer, m, start, n, contained)?, fits) + } + }; + let inb = match read.inb { + Some(inb) => fb.binary(BinOp::LogicalAnd, inb, fits)?, + None => fits, + }; + Ok(SourceRead { + inb: Some(inb), + ..read + }) +} + +/// Where source buffer `buffer` is read, in the form [`super::finish_slots`] chose. +enum Source { + /// Its storage view, at the bind residual. + View { view: View, residual: SValue }, + /// Its device address, through the root table at `table`, in a slot whose window starts at + /// `start`, contained when `contained`. + Psb { + table: SValue, + start: i64, + contained: bool, + }, +} + +/// The form source buffer `buffer` is read in. +fn source(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, buffer: u32) -> BResult { let access = &cx.plan.families.access; let slot = fetch::slot(cx.plan.stage, buffer); let reach = access @@ -273,12 +358,16 @@ pub fn prepare( match (lowering, view) { (Some(SlotLowering::View(ViewKind::Storage)), Some(view)) => { let residual = cx.push_field(fb, PushField::SlotBindOffset(slot))?; - view_read(fb, view, check, residual, m, n) + Ok(Source::View { view, residual }) } (Some(SlotLowering::Psb { start }), _) => { let table = cx.push_field(fb, PushField::RootTableAddress)?; let contained = cx.plan.families.access.psb_contained; - psb_read(fb, table, buffer, m, start, n, contained) + Ok(Source::Psb { + table, + start, + contained, + }) } _ => Err(cx.fail(format!( "source buffer {slot:?} is neither a declared storage view nor a device address" diff --git a/crates/metal2vulkan/src/lower/stage_io/fetch.rs b/crates/metal2vulkan/src/lower/stage_io/fetch.rs index 66019f64f..ce9cdf778 100644 --- a/crates/metal2vulkan/src/lower/stage_io/fetch.rs +++ b/crates/metal2vulkan/src/lower/stage_io/fetch.rs @@ -60,7 +60,15 @@ //! descriptor names, at `element · stride + offset` with the layout's stride: a fixed one compiled //! in, or for a layout of `MTLBufferLayoutStrideDynamic` the one the encoder binds the buffer with, //! from `PushField::StageInStride(buffer_index)`, where `element` is the step's ([`Step::Grid`], -//! [`Step::Indexed`], [`Step::Constant`]; `super::stage_in` plans them). +//! [`Step::Indexed`], [`Step::Constant`]; `super::stage_in` plans them). Metal places an element in +//! 64 bits, so where an element's bytes run past the first `2^32` bytes from the bind offset +//! (`e · stride + offset + size > 2^32`, decided exactly, where the `u32` displacement would wrap +//! back into the buffer) the read lies outside the buffer and yields zero bytes on every device +//! (`within_reach`, `access::pulled::prepare_within`): the runtime refuses a dispatch that may +//! fetch there from a buffer that holds those bytes. A dynamic layout bound with +//! `MTLAttributeStrideStatic` reads at its low 32 bits, `2^32 - 1`, so its first element is the +//! one at the bind offset and every element past it reads zero, as plain Metal on an M3 Max +//! answers it. //! //! **Source buffers**. This family records which Metal buffer indices the fetch reads //! ([`super::StageIoPlan::buffers`]); their slots are the access family's (`lower::access::pulled`, @@ -90,7 +98,9 @@ use crate::pipeline::sym::{PushField, SlotClass, SlotRef, Stage}; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::{BResult, BuildError, Dangling}; use crate::spirv::ids::Value as SValue; -use crate::spirv::ir::{BinOp, Contraction, ConvOp, GlslOp, IoDir, MemAccess}; +use crate::spirv::ir::{ + BinOp, ConstBits, Constant, Contraction, ConvOp, GlslOp, IoDir, MemAccess, Type, +}; use super::plan::{builtin, Shape}; @@ -430,9 +440,9 @@ impl PulledRead { // to the stage-in region, reads its index the way it reads the attribute, and adds the // region's origin. let element = match self.step { - Step::Grid { .. } => GRID_POSITION_WORDS + REGION_AXIS_WORDS + 16, + Step::Grid { .. } => GRID_POSITION_WORDS + REGION_AXIS_WORDS + REACH_WORDS + 16, Step::Indexed { index, .. } => { - GRID_POSITION_WORDS + REGION_AXIS_WORDS + index.leaf().cost() + 176 + GRID_POSITION_WORDS + REGION_AXIS_WORDS + REACH_WORDS + index.leaf().cost() + 176 } // The index read is the plan's, counted once (`super::CAPTURED_INDEX_WORDS`). Step::PerVertex { .. } @@ -449,6 +459,11 @@ impl PulledRead { /// threadgroup, unflattened in the flattened tiers (`dispatch::KernelDecl::value`). const GRID_POSITION_WORDS: u32 = 400; +/// An upper bound of the words of a kernel stage-in read's reach (`within_reach` and +/// `pulled::prepare_within`): the division, the comparisons and their conjunctions, the +/// selects, and their constants. +const REACH_WORDS: u32 = 96; + /// An upper bound of the words of a step's clamp to the stage-in region (`region_axis`): the /// region's push-field read, its origin and size, the size less 1, the `UMin`, and the origin's /// add, with their constants. @@ -992,11 +1007,67 @@ pub(super) fn emit( (Some(e), Stride::Static(s)) => Some((e, k32(fb, s)?)), (None, _) => None, }; + let n = r.encoding.bytes(); + // A kernel stage-in element reads Metal's 64-bit displacement, which the `u32` one below + // wraps. + let fits = match (r.step, element) { + (Step::Grid { .. } | Step::Indexed { .. }, Some((e, s))) => { + within_reach(fb, e, s, r.stride, r.offset, n)? + } + _ => None, + }; let m = displacement(fb, element, r.offset)?; - let read = pulled::prepare(cx, fb, r.buffer, m, r.encoding.bytes(), r.check)?; + let read = match fits { + Some(fits) => pulled::prepare_within(cx, fb, r.buffer, m, fits, n, r.check)?, + None => pulled::prepare(cx, fb, r.buffer, m, n, r.check)?, + }; fetch_from(fb, read, r.encoding, r.form) } +/// Whether the `n` bytes of a kernel stage-in read at element `e` of stride `s` (the value of +/// `stride`) and attribute offset `offset` lie in the first `2^32` bytes from the bind offset, +/// as Metal's 64-bit displacement `e · s + offset` places them: `e · s + offset + n <= 2^32`, +/// exactly, which the `u32` displacement's wrap cannot say. `None` where every element's do (a +/// fixed stride of 0). +fn within_reach( + fb: &mut FunctionBuilder<'_>, + e: SValue, + s: SValue, + stride: Stride, + offset: u32, + n: u32, +) -> BResult> { + // `e · s` may take `room` bytes; an offset and size past `2^32` leave none, so no element fits. + let Some(room) = (1u64 << 32).checked_sub(u64::from(offset) + u64::from(n)) else { + let ty = fb.module().ty(Type::Bool)?; + let c = fb.module().constant(Constant::Scalar { + ty, + bits: ConstBits(0), + })?; + return fb.module().const_value(c).map(Some); + }; + // At most `2^32 - 1`: a format takes at least one byte. + let room = room as u32; + match stride { + Stride::Static(0) => Ok(None), + // `e · s <= room` exactly when `e <= floor(room / s)`. + Stride::Static(s) => { + let most = k32(fb, room / s)?; + fb.binary(BinOp::ULessThanEqual, e, most).map(Some) + } + Stride::Push(_) => { + let zero = k32(fb, 0)?; + let one = k32(fb, 1)?; + let none = fb.binary(BinOp::IEqual, s, zero)?; + let by = fb.select(none, one, s)?; + let room = k32(fb, room)?; + let most = fb.binary(BinOp::UDiv, room, by)?; + let within = fb.binary(BinOp::ULessThanEqual, e, most)?; + fb.binary(BinOp::LogicalOr, none, within).map(Some) + } + } +} + /// A reference decoder for the tests: the component values the decode answers for `bytes` of /// `encoding` (missing ones `(0, 0, 0, 1)`), each as an `f64` for a float format or the /// sign-extended `u32` bits for an integer one. They are Metal's but a normalized field's, which diff --git a/crates/metal2vulkan/src/lower/stage_io/stage_in.rs b/crates/metal2vulkan/src/lower/stage_io/stage_in.rs index 2fb9a9281..8160579d6 100644 --- a/crates/metal2vulkan/src/lower/stage_io/stage_in.rs +++ b/crates/metal2vulkan/src/lower/stage_io/stage_in.rs @@ -26,7 +26,10 @@ //! the buffer with: Metal reads a bound stride only for a layout of //! `MTLBufferLayoutStrideDynamic` (an M4 read a fixed 16 under a bound 8). //! Such a layout (`StageInputLayoutDescriptor::stride` `None`) reads the bound one from -//! `PushField::StageInStride`, which the binder writes, as 0 for a buffer bound without one. +//! `PushField::StageInStride`, which the binder writes, as 0 for a buffer bound without one; an +//! element whose bytes lie past the first `2^32` bytes from the bind offset reads zero +//! (`fetch::within_reach`), which is what `MTLAttributeStrideStatic`'s `2^32 - 1` gives every +//! element past the first. //! //! **Formats** decode as a vertex format of the same raw value (`MTLAttributeFormat` and //! `MTLVertexFormat` list the same formats), and they meet the attribute's numeric class exactly diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 9048e48c3..39fc130c7 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -106,7 +106,7 @@ pub enum RuntimeFact { /// `layout` at the stride the encoder binds it with (`setBuffer:offset:attributeStride: /// atIndex:` and its forms), its stage-input layout being `MTLBufferLayoutStrideDynamic`: the /// binder writes the bound stride into `PushField::StageInStride`, or 0 for a buffer bound - /// without one, as Metal reads it. A layout of a fixed stride reads its own, compiled in, + /// without one, as Metal reads it (`MTLAttributeStrideStatic` is its low 32 bits). A layout of a fixed stride reads its own, compiled in, /// whatever the bind's, and records nothing. StageInStride { layout: u32 }, /// A read-only slot that Profile F's per-stage storage-buffer fallback may read through a diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 5a9edbab5..7d2ef8aae 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -1037,8 +1037,9 @@ pub enum PushField { /// (`BindState::line_band`). LineBand, /// The stride (`u32`) the compute encoder binds the kernel buffer at this Metal index with - /// (`setBuffer:offset:attributeStride:atIndex:` and its forms), 0 where it binds none, which - /// a `[[stage_in]]` layout of `MTLBufferLayoutStrideDynamic` fetches at + /// (`setBuffer:offset:attributeStride:atIndex:` and its forms, its low 32 bits, + /// `MTLAttributeStrideStatic`'s `2^32 - 1` included), 0 where it binds none, which a + /// `[[stage_in]]` layout of `MTLBufferLayoutStrideDynamic` fetches at /// (`RuntimeFact::StageInStride`). StageInStride(u32), /// The draw's viewport compensation for a vertex function compiled under diff --git a/crates/metal2vulkan/src/tests/engine_kernel_stage_in.rs b/crates/metal2vulkan/src/tests/engine_kernel_stage_in.rs index 27284f300..581f4261e 100644 --- a/crates/metal2vulkan/src/tests/engine_kernel_stage_in.rs +++ b/crates/metal2vulkan/src/tests/engine_kernel_stage_in.rs @@ -1076,10 +1076,43 @@ fn expected_at(a1: usize, a2: usize, t: u32) -> [u32; 12] { ] } +/// [`expected_at`] where layout 1's or layout 2's element lies past the first `2^32` bytes from its +/// bind offset (`None`): that layout's attributes read zero bytes, and the float3's missing +/// component 1. +fn expected_reaching(a1: Option, a2: Option, t: u32) -> [u32; 12] { + let mut out = expected_at(a1.unwrap_or(0), a2.unwrap_or(0), t); + if a1.is_none() { + out[0..3].copy_from_slice(&[0; 3]); + out[9..11].copy_from_slice(&[0; 2]); + } + if a2.is_none() { + out[4..8].copy_from_slice(&[0; 4]); + } + out +} + /// Run the fetch kernel under `d` (layout 1 stepping by x, layout 2 by y, both at rate 1) with /// the source buffers bound at `strides`, on every device, and compare every thread's report /// with the bytes at `s1 · x` of layout 1 and `s2 · y` of layout 2. fn run_strided(bc: &[u8], d: &StageInputDescriptor, strides: &[(u32, u32)], s1: u32, s2: u32) { + run_reaching( + bc, + d, + strides, + |gx| Some((s1 * gx) as usize), + |gy| Some((s2 * gy) as usize), + ); +} + +/// [`run_strided`] where `at1(x)` and `at2(y)` name the byte each thread reads layout 1 and +/// layout 2 at, `None` where its element lies past the first `2^32` bytes and reads zero. +fn run_reaching( + bc: &[u8], + d: &StageInputDescriptor, + strides: &[(u32, u32)], + at1: impl Fn(u32) -> Option, + at2: impl Fn(u32) -> Option, +) { let mut ran = 0; for (what, dev, _) in devices() { let Some(pipe) = compiled(&what, pipeline(&dev, bc, "stage_in_fetch", Some(d))) else { @@ -1097,10 +1130,9 @@ fn run_strided(bc: &[u8], d: &StageInputDescriptor, strides: &[(u32, u32)], s1: for gx in 0..W { let t = gy * W + gx; let at = (12 * t) as usize; - let (a1, a2) = ((s1 * gx) as usize, (s2 * gy) as usize); assert_eq!( out[at..at + 12], - expected_at(a1, a2, t), + expected_reaching(at1(gx), at2(gy), t), "{what} {strides:?}: thread ({gx}, {gy})" ); } @@ -1170,6 +1202,38 @@ fn a_dynamic_layout_reads_the_bound_stride() { run_strided(&bc, &d, &[], 0, 0); } +/// An element whose bytes lie past the first `2^32` bytes from the bind offset reads zero bytes, +/// on every device: Metal places an element at `e · stride + offset` in 64 bits, past every buffer +/// the runtime does not refuse the dispatch for, where the `u32` displacement wraps back into the +/// buffer. A dynamic layout bound with `MTLAttributeStrideStatic` reads at its low 32 bits, +/// `2^32 - 1`, so its first element is the one at the bind offset and every element past it reads +/// zero, as plain Metal on an Apple M3 Max under macOS 27.0.1 answered each of the four stride +/// forms (`metal2vulkan-conformance`'s `attribute-stride-*`). Without the reach check element 1 of +/// layout 1 reads its float3 at byte `2^32 - 1 + 4`, which wraps to byte 3. +#[test] +fn an_element_past_four_gigabytes_reads_zero() { + let Some(bc) = fixture() else { return }; + let mut d = fetch_descriptor( + (StepFunction::ThreadPositionInGridX, 1), + (StepFunction::ThreadPositionInGridY, 1), + IndexType::UInt16, + ); + for layout in [1, 2] { + d.layouts.get_mut(&layout).expect("layout").stride = None; + } + let first = |e: u32| (e == 0).then_some(0); + // `MTLAttributeStrideStatic` on both layouts, and on one beside a stride of its own. + run_reaching(&bc, &d, &[(1, u32::MAX), (2, u32::MAX)], first, first); + run_reaching(&bc, &d, &[(1, u32::MAX), (2, 8)], first, |gy| { + Some((8 * gy) as usize) + }); + // Element 1 of layout 1 ends 8 bytes past `2^32` (its float3's 12 bytes at 4 + `2^32 - 8`), + // and element 2's `2^33 - 16` wraps to `2^32 - 16` in 32 bits: both read zero. + run_reaching(&bc, &d, &[(1, u32::MAX - 7), (2, 8)], first, |gy| { + Some((8 * gy) as usize) + }); +} + /// A source buffer's bind offset moves the fetch with it (the range and the residual), and without /// buffer robustness one bound too short reads zero bytes past its end through the in-shader check /// (the interpreter traps any access a robust device would contain, so it does not model the robust diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 555d9b20f..472bb975d 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -123,7 +123,7 @@ Columns: | `PixelCoverageAtSampleRate` | The pixel's coverage (`[[sample_mask]]` read) in a fragment function that runs once per sample | drivers with a defect; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/lower/fragment/coverage.rs (finish)`, `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)` (+1) | `rare`: coverage read at sample rate | | `InterfaceComponents` | Too many interface components or locations | devices short of a device limit the site names; devices without VkLimit::MaxColorAttachments; devices without VkLimit::MaxVertexInputAttributes | `device` | 4: `crates/metal2vulkan/src/pipeline/compile/color_group.rs (refusal)`, `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)` (+2) | `rare`: too many varyings or attachments for a device | | `UnmatchedVarying` | A fragment input without a vertex producer (a Metal link error) | every device (no Vulkan mechanism) | `device` | 3: `crates/metal2vulkan/src/pipeline/link/varyings.rs (mesh_fragment)`, `crates/metal2vulkan/src/pipeline/link/varyings.rs (varyings, 2 sites)` | `none`: a Metal link error | -| `KernelStageIn` | Kernel `[[stage_in]]` | every device (not implemented) | `ours` | 3: `crates/metal2vulkan-runtime/src/indirect_execute.rs (dispatch)`, `crates/metal2vulkan/src/bind/dispatch.rs (instantiate)` (+1) | `rare`: kernel stage-in combinations Metal leaves unestablished | +| `KernelStageIn` | Kernel `[[stage_in]]` | every device (not implemented) | `ours` | 2: `crates/metal2vulkan-runtime/src/indirect_execute.rs (dispatch)`, `crates/metal2vulkan/src/lower/stage_io/stage_in.rs (select)` | `rare`: kernel stage-in combinations Metal leaves unestablished | | `Tessellation` | Tessellation | devices without VkLimit::MaxStorageBufferRange; devices without VkLimit::MaxTessellationGenerationLevel; every device (not implemented) | `ours` | 12: `crates/metal2vulkan-air/src/canon/mod.rs (post_check, 2 sites)`, `crates/metal2vulkan/src/bind/graphics.rs (tessellation_dispatch)` (+9) | `rare`: tessellation | | `MeshShading` | | devices short of a device limit the site names; devices without VkLimit::MaxMeshOutputLayers; devices without VkLimit::MaxTaskPayloadSize; devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 7: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`, `crates/metal2vulkan/src/bind/graphics.rs (plan)` (+4) | `rare`: mesh pipelines | | `TileShading` | | devices without VkLimit::MaxStorageBufferRange; devices without a format's usage; every device (not implemented) | `ours` | 5: `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs (scratch)`, `crates/metal2vulkan/src/bind/plan/compute.rs (tile_memory)` (+3) | `rare`: tile shaders (Apple GPU families) | @@ -635,7 +635,7 @@ Each refusal's sites, with the function that builds it. - `feature::PixelCoverageAtSampleRate`: `crates/metal2vulkan/src/lower/fragment/coverage.rs (finish)`; `crates/metal2vulkan/src/lower/simd/mod.rs (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (sample_invocations)` - `feature::InterfaceComponents`: `crates/metal2vulkan/src/pipeline/compile/color_group.rs (refusal)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (assign)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (limit_error)` - `feature::UnmatchedVarying`: `crates/metal2vulkan/src/pipeline/link/varyings.rs (mesh_fragment)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (varyings, 2 sites)` -- `feature::KernelStageIn`: `crates/metal2vulkan-runtime/src/indirect_execute.rs (dispatch)`; `crates/metal2vulkan/src/bind/dispatch.rs (instantiate)`; `crates/metal2vulkan/src/lower/stage_io/stage_in.rs (select)` +- `feature::KernelStageIn`: `crates/metal2vulkan-runtime/src/indirect_execute.rs (dispatch)`; `crates/metal2vulkan/src/lower/stage_io/stage_in.rs (select)` - `feature::Tessellation`: `crates/metal2vulkan-air/src/canon/mod.rs (post_check, 2 sites)`; `crates/metal2vulkan/src/bind/graphics.rs (tessellation_dispatch)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs (select)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (input_builtin)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (primitive_id_output)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (not_implemented)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (plan_entry)`; `crates/metal2vulkan/src/metal/vertex.rs (fetch_as)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (check_fragment)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (control_plan)` - `feature::MeshShading`: `crates/metal2vulkan/src/bind/graphics.rs (mesh_limit)`; `crates/metal2vulkan/src/bind/graphics.rs (plan)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (check_payload)`; `crates/metal2vulkan/src/lower/mesh/mod.rs (plan_entry, 2 sites)`; `crates/metal2vulkan/src/memory/plan.rs (reprs)`; `crates/metal2vulkan/src/pipeline/link/mesh.rs (records)` - `feature::TileShading`: `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs (scratch)`; `crates/metal2vulkan/src/bind/plan/compute.rs (tile_memory)`; `crates/metal2vulkan/src/lower/access/tile.rs (not_implemented)`; `crates/metal2vulkan/src/lower/sync/barrier.rs (tile_shading)`; `crates/metal2vulkan/src/pipeline/compile/api.rs (tile_pipeline)`