2137a20004e2b5658aedd0bdfdafc99e043606ce
1530
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
13b279df1b |
Squash 11203 commits of translator, runtime, and validation work
Rolls up everything since
|
||
|
|
43c46ac8a2 |
Squash 680 commits of translator, validation, and corpus work
Rolls up everything since
|
||
|
|
9e0e99a41d |
Report only the constexpr samplers the module binds
`StaticSampler` is a descriptor translation invents. Nothing in Metal's API puts one there, so the only reason a consumer creates a `VkSampler` at that binding is that this reflection asked for one. Reflection named one per `!air.sampler_states` entry -- every constexpr sampler state the source wrote -- and the interface pass gives each the same binding in the same order. But a state no sample reads leaves a variable nothing references, and the module drops it, so reflection went on describing a sampler that is not there. Over the 2880-source sample: 112 such bindings in 60 modules. `StaticSampler` was the last translator-invented kind still reported without the module's agreement; `reconcile_buffer_address_table` and `report_synthesized_placeholders` already close the same gap for the other three. Sweeping all four kinds over the sample now finds none. Nothing moves. The interface pass allocates a binding per global before the unused ones are dropped, so the states that survive are still on the bindings that carry them -- confirmed by a reflection A/B over the sample, where 60 modules lose exactly those 112 entries, nothing is added, and no other field of any binding changes. The new fixture is three constexpr samplers with two samples, which reports a ghost at binding 161 on HEAD~. `assert_invented_descriptors_are_declared` now runs over every public fixture as well: it is the direction `assert_reflection_covers_declarations` does not check, and for a resource the translator invented the module is the only thing that can say a consumer has to bind it. `REFLECTION_VERSION` is now 41. |
||
|
|
b6e10bf14c |
Read a color attachment's Location from the operand after its marker
`!"air.render_target", ptr addrspace(2) @loc, i32 0` states the Location as a function-constant global and the dual-source index after it. When the global was one this module does not initialize, the decode fell through to "the next `i32` after the marker" and answered with that index -- which is `0` in all 3213 literal-form corpus declarations, so every such output landed on attachment 0 whatever the constant said. For a multi-target shader that is every color output on one attachment. 103 of 3316 corpus `air.render_target` declarations spell the Location as a global. The operands after a slot describe something else, so none of them is an answer to "which slot". The parameter or member ordinal stands in instead, which is at least unique per member. This is the same defect `air.location_index` had, so the two are now one decoder: `meta::declared_slot` reads the FIRST operand after a given marker and resolves it through the static initializers, and `meta::marker_operands` is the one positional reader behind both. The last scan-forward `@` helper went with it. The census that found this is in the doc comment: for every `air.*` key, compare "the next `i32`" against the operand actually at position 0. A/B over the 2880-source sample: 0 byte changes. Full-corpus status over all 14579: 0 changes. Pinned by a fragment whose second render target names a function constant, asserted both when the module initializes it and when it does not; the second case reports Location 0 on HEAD~. |
||
|
|
4c28bcc233 |
Order constexpr samplers by one key that cannot tie
Two independent scans put the module's `__air_sampler_state` globals in a sequence and then pair them off by position: the interface pass, which collects them from the SPIR-V `OpName`s and hands each the next free sampler binding, and reflection, which collects them from the `!air.sampler_states` root and reports the decoded state at each of those bindings. Each sorted with its own copy of a key that read the name suffix as a single integer. That key TIES. LLVM uniques a repeated `__air_sampler_state` by appending `.N`, and re-uniques an already uniqued name by appending again -- `__air_sampler_state.161.1606` -- which the single-integer parse fails on, as it does on the unsuffixed original, so both land on 0. A tie leaves the order to input order, and the two scans have different ones. Both sides then agree on WHICH sampler bindings exist while describing each as the other, so every sample reaches a real sampler carrying another one's filter, address modes and compare function, in a module that validates and binds cleanly. 14 of the 5499 sampler-state globals across 14579 local corpus sources carry the doubled form, and 10 modules hold one beside the original. The key now orders by the whole dot-separated suffix with the name last, which cannot tie -- a name is unique within a module -- and it lives in one place, `meta::static_sampler_name_order`, with the prefix predicate beside it so neither side spells `__air_sampler_state` for itself. The existing constexpr-sampler test checked only which bindings exist, which is the half that was already right. It now also checks that the state reported at each binding is the state the sample reading that binding was written with, over both the uniquely suffixed spelling and the re-uniqued one. The re-uniqued fixture fails on HEAD~ with the two states swapped. A/B over the 2880-source sample: 0 status changes; 1 module changes, one surviving constexpr sampler moving from binding 162 to 161 as its state moves to the position the shared order gives it. |
||
|
|
e84ea3fa48 |
Read the descriptor count the ABI states beside a location index
`air.location_index` always carries TWO operands: the resource's Metal slot and how many descriptors the argument occupies there. Nothing read the second one. An `array<sampler, 8>` therefore bound as a single sampler. Its element loads then resolved to nothing, so the sample fell back to the synthesized read sampler -- the shader's chosen filter, address modes and compare function dropped without trace, in a module that validates, binds and reflects as though one sampler at that slot were the whole story. There is no sampler descriptor-array lowering, so this is now a FALLBACK naming the parameter and the count. Two of 14579 local corpus sources declare one. The same count is what makes the texture-array length checkable. AIR states that length twice -- as this operand and inside `array<texture..., N>` -- and all 76 corpus declarations agree, so a name the ABI contradicts, or a count above one on a name that is not an array at all, is refused rather than silently sized from the name alone. It costs nothing today and fails the moment the parse drifts. Reading the pair also has to be POSITIONAL. Either operand may be a literal or a pointer to a function-constant global, and all four combinations occur -- 112946 `(i32, i32)`, 3404 `(ptr, i32)`, 1447 `(ptr, ptr)`, 439 `(i32, ptr)`, and no other shape. The slot decode looked for the first global after the marker, which IS the count whenever the slot is a literal: a texture at `[[texture(1)]]` with a function-constant array extent could bind at the extent's value. 69 corpus texture nodes are that shape. The buffer half of it was already dodged by a type-name special case for `array_ref<void>` -- whose comment describes exactly this confusion -- and the positional read makes that case unnecessary, so it is gone. Latent today: no corpus module resolves the count global. Full-corpus A/B over all 14579 sources: 0 status changes. The two sampler-array sources already fell back for unrelated reasons, so the hole is pinned by an authored fixture instead, which translates cleanly at HEAD~ and refuses here. Both new must-FALLBACK cases carry their positive control, so the boundary is what is pinned rather than one side of it. |
||
|
|
a1ffb61707 |
Count a descriptor array as the one binding it occupies
`bindings_reflection_reports` expanded a `DescriptorLocation`'s `count` into `count` consecutive `(set, binding)` pairs, but a descriptor array occupies ONE binding holding `count` descriptors -- it maps to a single `VkDescriptorSetLayoutBinding`. The expansion let one array vouch for every binding above it: a runtime texture-handle array at 480 with a count of 128 "reported" the whole storage-texture band, so a module variable decorated anywhere in 480..608 satisfied a check reflection had never made. Nothing was masked -- the fixtures pass either way, and sweeping the same oracle over the 2880-source sample finds 0 modules with a decorated binding reflection omits -- but the assertion now means what its name says. |
||
|
|
35f8b8bfce |
Bind a fixed texture array at the length AIR declares
`array<texture2d<half, sample>, 32>` states its length twice -- in the type
name and as the second `air.location_index` operand -- and the decoded
`TextureShape` already carried it. The interface pass still emitted
`OpTypeArray` of 128 and reflection still reported `count: 128` for every
handle array, fixed or runtime, so one `ResourceBinding` contradicted itself:
`texture_shape.array_length` said 8 while `descriptor.count` said 128, and a
consumer following the reflection had to supply 128 valid descriptors (or
`descriptorBindingPartiallyBound`) for an array of 8.
Both sides now derive from `TextureShape::descriptor_count`, the only reader of
the capacity constant. Only a runtime `array_ref`, whose length is a function
constant rather than part of the type name, still reports it. 40 of 14579 local
corpus sources declare a fixed array, lengths 2, 3, 4, 8, 32 and 80; every one
of the 76 declarations agrees with its `air.location_index` count operand.
The same unification fixes a depth-texture array bound as a single image. The
interface pass asked `contains("array<texture")` while the shared type-name
decoder asked about `array<depth` too, so `array<depth2d<float, sample>, 2>`
was not recognised as a handle array at all: the module declared one `depth2d`
where the shader indexes two, while reflection reported a `TextureArray` of 128
at that binding. There is now one predicate, `TextureShape::array_ref`, and one
scan behind it -- "is this an array" and "how long is it" can no longer be
answered by two different rules.
`tests/reflection_covers_declared_bindings.rs` now requires the reported count
to EQUAL the array the module declares rather than merely cover it, which is
what makes over-reporting detectable; the runtime fixture cannot catch it,
since its declared capacity IS the ceiling. Two fixed fixtures are added, one
of them spelled over `depth2d`, because a handle-array test that only ever says
`texture` cannot tell whether the emitter recognised the depth spelling.
Reverting either half of the fix fails them.
A/B over the 2880-source sample: 0 status changes; 8 modules change, each only
an `OpTypeArray` length 128 -> 2/8/32/80 and the ids that renumber behind it.
`REFLECTION_VERSION` is now 40.
|
||
|
|
798b526fa7 |
Report the threadgroup ceiling this translator enforces
Translation refuses a `kernel_local_size` whose product exceeds the entry's `[[max_total_threads_per_threadgroup(N)]]`. A bound a consumer has no way to read leaves it guessing at the dispatch shape until it hits the refusal, so `ShaderReflection` now reports `max_work_group_size`. Reflection reports it and does not enforce it: discovering the bound is the reason to call it, and refusing the call that asks would be circular. The authored test drives both halves off the one declaration -- it reads the ceiling out of reflection, then dispatches exactly that many threads and one more -- so the number reported and the number enforced cannot drift apart. A kernel that declares no ceiling reports `None` and bounds nothing. `REFLECTION_VERSION` is now 39; `docs/REFLECTION.md` documents the field. Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan` in debug and release, `cargo test -p metal2vulkan-validation`. Dropping the field back to `None` fails the new test and no other. A/B against the previous commit over 2880 corpus sources: 0 status changes and 0 SPIR-V byte changes. |
||
|
|
9db8b14645 |
Refuse an imageblock that is really the framebuffer
An explicit `[[imageblock]]` is tile-local scratch, undefined on entry, and the interface gives it a `Private` array. That is an honest refinement of undefined storage. `air.alias_implicit_imageblock`, on the same node beside the ordinary `explicit` qualifier, states the opposite: the storage *is* the implicit imageblock -- the render targets the rasterizer has already written. The kernel's first read is of framebuffer content and its writes have to land back there. The marker was unread. `resolveTileMemoryKernel_ColorBlockSimple`, whose body begins by loading a `<4 x half>` out of the imageblock and ends by writing the resolve to a texture, was emitted reading `%_ptr_Private__arr_v4half_uint_2` -- an uninitialized per-invocation array. It validated, and neither the module nor its reflection carried any descriptor for the framebuffer that a consumer could have noticed was missing. 30 of 14579 local corpus sources carry the marker. Vulkan has no compute stage inside a render pass to alias against, so the answer is a refusal naming the parameter. The 124 non-aliased explicit imageblocks keep the Private-scratch lowering exactly as it was; the authored test drives both arms off one template, since the aliased and unaliased nodes differ only in that one string. Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan` in debug and release, `cargo test -p metal2vulkan-validation`. Suppressing the decode fails the new test and no other. A/B against the previous commit over 2880 corpus sources: 0 SPIR-V byte changes, and exactly the nine sources carrying the marker move from OK to FALLBACK. |
||
|
|
66c7e7d42b |
Refuse the command buffer this translator cannot encode
`air.set_pipeline_state_compute_command`, `air.set_kernel_buffer_compute_command`, `air.draw_primitives_render_command` and their siblings write commands into a Metal indirect command buffer the shader received as an argument. They were lowered to `Ok(vec![])` -- dropped -- with the comment that "the current conformance compute runner observes buffer bytes only, so preserve translation validity without claiming command-buffer side-effect emulation". What that preserves is the appearance of translation. The module validates, binds and reflects exactly like the original and performs none of the encoding; `ICB_Inherit_None_Kernel`, whose body is nothing but encoding, came out as a 35KB module that does nothing and reported success. That is emitting wrong-but-valid SPIR-V to silence a gate, which is the one thing this tree's honesty contract names outright. Vulkan has no equivalent to encode into -- its device-generated-command extensions describe a different, driver-defined layout that no sequence of SPIR-V instructions can produce from these operands -- so the answer is a refusal naming the family. `AirIntrinsicDisposition::NoVulkanEquivalent` separates a family the translator has modelled and refuses from one nothing has modelled yet, so the refusal reads as a decision rather than as an unrecognised symbol. Validation reported the `IndirectCommandBuffer` tooling requirement from `!"air.indirect_command_buffer"`, a metadata string that appears in 0 of 14579 local corpus sources. What an encoder actually carries is a call into one of these families and an `air.command_buffer` argument-buffer member -- 17 sources carry the latter. The requirement is now derived from `is_command_encoder_helper`, the same definition translation refuses on, so the boundary is stated once. Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan` in debug and release, `cargo test -p metal2vulkan-validation`. A/B against the previous commit over 2880 corpus sources: 0 SPIR-V byte changes, and exactly the two sources that encode commands move from OK to FALLBACK, each naming the family it could not lower. Twelve of the 14579 local sources reach it. |
||
|
|
c5570b5235 |
Encode a half constant one way
The native emitter and the passes layer each carried their own `f32` -> IEEE-754 binary16 conversion. They did not agree. The passes copy rounded half-away-from-zero rather than to even, and combined the rounded significand into the encoding with `|` instead of `+` -- so a value whose rounding carries out of the ten significand bits kept the exponent it started with whenever that exponent was odd, because the carry bit it needed was already set. That is not theoretical. `air.convert` from a `half` source to a narrow integer clamps in the source type first, and the clamp bounds go through this encoder. The `32767.0` upper bound of a 16-bit signed convert encoded as `16384.0`, and the `8191.0` bound of a 14-bit one as `4096.0`. The lower bounds are powers of two and rounded exactly, so the clamp came out asymmetric: `[-32768, 16384]` where it should read `[-32768, 32768]`. Every `half` above the halved bound saturated to it instead of to the destination's maximum, in a module that validates. Six of 2880 corpus sources emit exactly that clamp. The correct encoder now lives in `crate::float16` and is the only one. Its test walks every rounding boundary the format has: for each pair of adjacent finite halves, the exact midpoint (representable in `f32`, so the test does no rounding of its own) must land on the even one, and the two neighbouring `f32` values must land on their own side. Round-tripping representable halves, which is what the emitter's own test did, cannot see any of this -- widening is exact, so it never asks the encoder to round. Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan` in debug and release, `cargo test -p metal2vulkan-validation`. Substituting the old passes-layer encoder into the new module fails three of its five tests, including the boundary walk. A/B against the previous commit over 2880 corpus sources: 0 status changes and 6 SPIR-V changes, each of them the clamp constant above. |
||
|
|
c75c1c9a5f |
Read every attribute a stage root carries
All three AIR stage roots -- `!air.kernel`, `!air.vertex`, `!air.fragment` -- state their per-entry attributes in the same place: extra operands past the `(function, outputs, inputs)` triple. They do not state them in the same form. `air.patch` and `air.max_work_group_size` are references to a keyed node; `early_fragment_tests` is a bare string operand on the root itself. Only the vertex decode read that tail, and only for `air.patch`, so a stage could not tell "no attribute" from "an attribute nobody taught me to see". Two were being dropped in that silence. `[[early_fragment_tests]]` -- 51 of 14579 local corpus sources -- now reaches SPIR-V as `OpExecutionMode ... EarlyFragmentTests`. It is not a hint: under early testing a fragment the depth test rejects executes none of the body's stores, while under Vulkan's default late test the same shader performs every buffer, texture and imageblock write and only its color output is discarded. Both modules validate, bind and reflect identically, which is why nothing caught it. A fragment that declares it and also writes `air.depth` or `air.stencil` is refused: the test runs before the value it compares exists, and Metal rejects the pair outright. `[[max_total_threads_per_threadgroup(N)]]` (`air.max_work_group_size`, 439 of the same sources) states the largest threadgroup the body was compiled to run. A caller-requested `LocalSize` past it is refused instead of emitted as a module that validates and runs a shape the source ruled out. The duplicated non-zero `LocalSize` check in `transform_with_options_and_sidecar` now calls `validate_kernel_dispatch_options` rather than restating it. The structural half is `meta::stage_root_attributes`: one decoder for the whole tail, recognising each attribute by its own ABI marker rather than by position, carrying anything it cannot model out through `unmodelled_stage_attributes` so the stage-input pass refuses by name. A node with no operands states nothing and is skipped -- there is nothing in it to drop. Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan` in debug and release, `cargo test -p metal2vulkan-validation`. The six authored cases in `tests/stage_root_attributes.rs` were checked against five mutations (drop the execution mode, drop the decode, ignore unmodelled attributes, drop the ceiling check, read only the first tail operand); each mutation fails at least one. A/B over 2880 corpus sources: 0 status changes, and the only SPIR-V byte changes are the ten fragments declaring `early_fragment_tests`, each gaining exactly the one execution-mode line and still passing spirv-val. |
||
|
|
386bbd2823 |
Sweep the descriptor ABI on a layout that is not the default
The descriptor ABI is written twice. The stage passes decorate the module from the selected `DescriptorLayout`; reflection computes the same numbers for itself. `reflection_covers_declared_bindings.rs` already checks that the two close over each other -- but every case ran at the default layout, where a band whose reflection forgot the selection and used the default constant is right anyway. The corpus cannot help: it only ever translates at the default. So the public-fixture sweep now runs a second time on a layout with the default's band widths, none of its numbers, and a different set. Coverage still has to hold, and one invariant more: no binding the module declares or reflection reports may fall outside a selected band or on another set. A default-layout number surviving the shift lands in neither. Replacing one `descriptor_layout.buffer_binding` call with the default-layout `buffer_resource_binding` fails the new sweep and passes all seven older tests. The sampler band needed a case of its own. A `constexpr sampler` has no Metal argument index -- it is a module-scope constant whose binding is allocated from the band rather than projected from an index -- so it exercises an allocator the projected kinds do not, and none of the 21 public fixtures carries one. The authored fragment samples one texture through two of them, checked on both layouts; pointing reflection's allocator at the default band fails it. Tests only; no product code changes. |
||
|
|
49fdfa0d65 |
Ask the emitter whether a kernel needs its address table
Whether a module carries a buffer-address table is a property of the pointer graph the emitter constructs, and the emitter decides it with `requires_device_address_model` over the parsed source. Metadata-only reflection has to answer the same question, and answered it separately: a scan of the AIR text for lines beginning `inttoptr` or `load ptr addrspace(1)`. Two derivations of one fact, and the second was much the worse. Over 2880 corpus sources the scan disagrees with the finished module 63 times. 49 of those report a binding no module declares, which costs a consumer a descriptor slot. The other 13 report none for a module that does declare one, which costs a consumer a binding the shader reads -- and the scan cannot be fixed into seeing them, because they are modules with no device pointer written anywhere in the AIR at all: the address model is chosen for them during construction. Asking the emitter's predicate leaves 8 disagreements, four in each direction, and the remainder are the same kind -- decisions made after the pointer graph is parsed. It costs a parse: metadata-only reflection goes from about 1.6 ms to about 13 ms per shader, against 39 ms to translate one, so the path stays the cheap one it is there to be. The authored case for this was previously a bare `inttoptr` with nothing reading it. That is precisely what the scan over-reports, so it now loads through the pointer, and its dead twin is pinned beside it as the case that must report no table. A second case loads a device pointer out of a struct member, which no line-prefix scan can see and the pointer graph reads directly. No module's SPIR-V changes and reflected translation is untouched, since it reads the table off the module either way. `REFLECTION_VERSION` is 38. |
||
|
|
f5b7d060ea |
Hold both sources of sampler state to one rule
Vulkan has no unnormalized-coordinate sampler with Metal's semantics, so a `coord::pixel` sampler is emulated with shader-side fetches at level zero. Anything the fetch cannot express has to fail translation rather than be silently dropped -- the module would sample the right texture with the wrong filter, anisotropy or border, and validate either way. Sampler state reaches that lowering from two places, and only one of them checked. `RuntimeSamplerState::validate` refused caller-supplied state it could not reproduce; AIR's constexpr encoding went straight to the lowering unchecked. Two copies of a rule drift, and the copy that existed was wrong: it demanded both LOD clamps be exactly zero. Only the minimum can matter. The fetch reads level zero, so a minimum above zero excludes the level the emulation reads, while a maximum cannot -- validation already requires it to be at least the minimum. Metal's default maximum is 65504, the half-precision limit AIR encodes "unclamped" as, and 531 of the 535 pixel-coordinate static samplers over 2880 corpus sources carry exactly that. A caller passing the state its own shaders use got a FALLBACK; the AIR path took the identical state without a word. The constraints now live on `StaticSamplerState`, which is what the lowering actually consumes, and both paths call them. Over the corpus every pixel sampler passes -- all 535 are nearest, unmipped, unaniso, unbiased, weighted average, minimum clamp zero -- so no module changes status and none changes by a byte. |
||
|
|
d5e2aaa052 |
Refuse a tessellation patch this translator cannot read
`air.patch` is what makes a vertex function a post-tessellation evaluation shader: it names the domain and, with `air.patch_control_point`, the number of control points a patch carries. The decoder read it as an `and_then` chain that answered `None` for anything it did not recognise, and `None` is also the answer for a function that has no patch node at all. The two are not the same fact. A function whose patch node did not decode came out as an ordinary vertex shader. Gone with it: the `Quads` / `Triangles` / `Isolines` execution mode Vulkan requires of a tessellation evaluation stage, `SpacingEqual`, `VertexOrderCcw`, and every per-patch input the pipeline has to wire. Nothing downstream can notice -- the module validates, binds and reflects, and draws the wrong geometry. `VertMeta::undecoded_patch_shape` carries the failure out and the stage-input pass refuses on it, beside the entry-parameter role guard that exists for the same reason. The node is now found by the `air.patch` marker it carries rather than by sitting third in the vertex root. Position is not the fact, and reading position alone cannot tell a patch node from whatever else a root might grow -- the authored case that pins this caught the first version of the search, which took the third entry before checking what it was. Over 2880 corpus sources 45 functions carry a patch node, 44 `quad` and one `triangle`, every one at the third entry and every one decoding as before: no module changes status and no module's SPIR-V changes by a byte. |
||
|
|
72a1bfb660 |
Separate a buffer with no members from one whose members disagree
`record_air_struct_offsets` matches AIR's declared member layout against the struct the emitter produced for a buffer parameter, and reported one status -- `EmittedShapeMismatch` -- whenever it could not. Over 2880 corpus sources that fired 1805 times, and reading it as written says the translator disagrees with the compiler about 1805 buffer layouts. It does not. A buffer whose accesses are byte-addressed is emitted as its raw contents: a pointer straight to a word, or the block Vulkan requires of a storage buffer wrapping a runtime array of one. There are no members there for the declared offsets to land on, so no comparison was made and none failed. That is 1733 of the 1805. `EmittedIsUntypedBuffer` names it, and what is left is 72 parameters across 70 modules where two structural descriptions of the same memory really do differ -- a list small enough to read. Deciding it needs the same idea the comparison needs: the block is Vulkan's packaging, not Metal's layout, so `emitted_carries_members` steps through the wrapper and the array before asking whether anything has members at all. The distinction also sharpens the authored cases. Calling a `uchar3` member a `float3` widens it to sixteen bytes and runs it over the two members after it, and overlapping members are what pushes a buffer to a raw view in the first place -- so that case now proves no comparison was possible, and a second case declaring a member's type wrong without overlapping proves one was made and failed. No module changes status and no module's SPIR-V changes by a byte. |
||
|
|
eebedc3994 |
Size a buffer member AIR names but never describes
`air.struct_type_info` gives each member an offset, a byte size, an array
length, and a type name. When the member is a user struct or class the name is
all the metadata says about its interior -- `Espresso::padding_params_t`,
`VFX_RE_C_LightSpot`, `vfx_light::(unnamed)` -- and there is no nested node to
recurse into. The decoder answered `float` for every one of those, which states
a type AIR never stated and sizes the member at four bytes no matter what it
declared. Over 2880 corpus sources 2513 such members appear across 817 modules,
and 2357 of them declare a size other than four; the largest understates a
408-byte member by 404.
`AirType::Opaque { size }` makes the case representable, so the decoder can say
what AIR said and nothing more. Every consumer that needs a concrete type still
gets one -- the same size-derived storage shape that argument-buffer handles and
non-strict nested structs already use -- but the two consumers that need the
truth now get it. `air_metadata_extent` bounds a decoded layout against
`air.arg_type_size`, so understating a member let a layout that over-runs its
argument pass the check; with true sizes every corpus layout still fits, which
is the corroboration the old numbers could not give. And the emitter's member
matcher no longer demands a shape the metadata never stated: an emitted member
occupying exactly the declared bytes is the member AIR meant, where a float leaf
matched nothing and threw away the declared offsets for the entire buffer.
Making the variant explicit also forces the question at every site: four
exhaustive matches on `AirType` had to decide, rather than silently inheriting
`float`. Over the corpus no module changes status and no module's SPIR-V changes
by a byte. `REFLECTION_VERSION` is now 37 because reflected `type_layout`
reports the new variant.
|
||
|
|
fed00f1e18 |
Stop a fragment demanding features for a parameter it does not have
A `[[function_constant(x)]]` entry parameter exists only when the pipeline supplies `x` as true, and nothing supplies function-constant values here -- so a gated parameter is absent and its uses are statically dead. The vertex and kernel decodes already treat one that way: their role reader collapses a gated argument back to the wrapper unless it is a promoted resource. The fragment reader looked past the wrapper unconditionally, and wired the builtin anyway. For a resource that distinction does not matter, and must not: the descriptor stays in the pipeline layout the application binds against either way. For a system value it does. A builtin declared for an absent parameter puts a variable in the entry point interface, and `[[viewport_array_index]]` and `[[render_target_array_index]]` put `ShaderViewportIndex` / `ShaderLayer` in the module -- device features the shader never reads, narrowing which devices can create the pipeline. Over 2880 corpus sources, 25 modules change and none changes status: 47 capabilities, 51 Input variables with their loads and conversions, and 98 decorations go away, and nothing is added but the undef values those absent parameters already bind elsewhere. spirv-val clean throughout. |
||
|
|
1a7920a8e1 |
Read the coverage a fragment is handed
`[[sample_mask]]` on an argument is the coverage the rasterizer produced for this fragment; AIR spells it `air.sample_mask_in` to tell it apart from the return member of the same name. It had no lowering, so a shader that intersects its own mask with the incoming one read zero coverage and intersected everything away. SPIR-V uses one builtin in two storage classes, so a shader that declares both directions produces two `SampleMask` variables -- an Input read through element zero and an Output written through it. `LoadVarComponent` already loads a composite and extracts a component, which is the same shape for a `uint[1]` array as for a builtin vector. A gated-off argument stays absent: declaring its builtin would put a variable in the entry point interface for a value the shader cannot read. That is 13 corpus modules, and with the gate no module's SPIR-V changes by a byte. |
||
|
|
74c0054375 |
Reject a builtin parameter the emitter cannot wire
`position`, `point_coord` and `front_facing` each declare a SPIR-V builtin of a fixed shape, and a parameter of any other shape was bound to a zero. That put every fragment of a mistyped `[[position]]` at the origin and called every triangle of a mistyped `[[front_facing]]` back-facing -- in a module that validated, bound the same descriptors and reflected as though the builtin were connected. The branch is unreachable on real AIR: Metal fixes each attribute's type, and over 2880 corpus sources nothing changes by a byte. It rejects now so the silent zero cannot come back. One authored fixture declared `[[position]]` as a scalar `float` while testing something else entirely; it now says `float4`, which is what AIR would say. |
||
|
|
bbd66ec226 |
Give a dispatch its threadgroup size under either Metal spelling
`[[dispatch_threads_per_threadgroup]]` had no lowering, so the parameter read a zero -- and every shader that used it divided or indexed by that zero. Since the guard two commits ago it FALLBACKs; now it translates. Metal distinguishes it from `[[threads_per_threadgroup]]` only under `dispatchThreads:`, where a final partial threadgroup reports a smaller actual size than the dispatch asked for. `vkCmdDispatch` issues whole workgroups only, so in this translation the two denote the same value and share one role. Over 2880 corpus sources: 2 modules go from FALLBACK to a spirv-val-clean translate, and no other module's SPIR-V changes by a byte. |
||
|
|
a72afbe1db |
Read the barycentric weights a fragment asks for
`[[barycentric_coord]]` gives a fragment the three weights of the covering primitive's vertices. It had no lowering, so the parameter read a zero -- a degenerate barycentric that names no vertex, in a module that validated and reflected normally. Since the previous commit it FALLBACKs instead; now it translates. Vulkan spells the perspective-correct and screen-space forms as two builtins rather than as a builtin plus a decoration, so the marker AIR states on the argument picks `BaryCoordKHR` or `BaryCoordNoPerspKHR`. Both come from `SPV_KHR_fragment_shader_barycentric`, which `module_cleanup` now requests from the decoration alongside the capability -- through a `require_extension` helper that replaces the three copies of the same idempotent push. A function-constant-gated argument that is off by default is absent, and is left zero-bound: materializing its builtin would make the module require the extension for a value nothing reads, narrowing the devices that can create the pipeline. A parameter that is not a float3 has no honest lowering and rejects. Over 2880 corpus sources: 2 modules go from FALLBACK to a spirv-val-clean translate, and no other module's SPIR-V changes by a byte. |
||
|
|
7c33f4f197 |
Reject an entry parameter nothing knows how to read
An unrecognised entry parameter is bound to a zero value so the body stays well formed. That is right for a function-constant-disabled resource, which Metal itself defines as absent, and wrong for a system value the emitter does not model: the shader reads zero where the hardware would have supplied a barycentric coordinate or a simdgroup index, in a module that validates, binds and reflects exactly as if nothing were missing. Each stage now carries the roles it models as an inventory and records the parameters it cannot place; emission rejects on the first one, naming it. The role is read with `declared_role`, which reports none for a bare `air.function_constant` parameter -- there is no role behind the wrapper, and reading past it lands on the node's own `air.arg_type_name`. Over 2880 corpus sources, 8 modules move from a silently wrong translate to a FALLBACK naming the role -- barycentric_coord (2), amplification_id (3), dispatch_threads_per_threadgroup (2), thread_index_in_simdgroup (1) -- and no other module's SPIR-V changes by a byte. Each of those four is a lowering that can be written; until it is, the rejection is what says so. |
||
|
|
547ac579e1 | Reject a stage output nothing knows how to write | ||
|
|
0a6ebea88c | Write the coverage mask a fragment returns | ||
|
|
48b12decd1 | Carry a position's invariance guarantee into the module | ||
|
|
55bb249b8b | Interpolate a fragment input the way AIR asked | ||
|
|
f8af350514 | Read a static initializer from the section AIR marks it with | ||
|
|
f5c56ecbc8 | Pin both sides of the function-constant-gated indirect call | ||
|
|
e92509f71e |
State which AIR sampler bits are decoded and which are not
`from_air_words` returns `Err` for an unrecognized code in a field it reads -- inventing a filter or an address mode would silently change how the shader samples -- but says nothing about the bits it never looks at, which a reader can only find by diffing the shifts against 64. Write the whole bit map down and pin it with a test that asserts both halves: the decoded fields, each given a value distinct from its neighbours so a swapped shift cannot pass, and the ignored ranges, whose every bit set changes nothing but `raw_words`. The ignored ranges are worth stating because one of them is not empty. Bit 63 of `words[0]` is set on 151 of the 1084 static samplers in a 2880-source corpus, with no correlate among the decoded fields -- the same filter, coordinate, compare and clamp combinations appear with it and without it. Nothing here says what it selects, so nothing here acts on it; `words[0]` bits 24-31 and 60-62 and `words[1]` bits 16-63 are zero throughout that corpus. `raw_words` is what a consumer that learns bit 63's meaning would read. No behavior change. |
||
|
|
9f0123eb41 |
Reject a member layout that reaches past its argument
AIR states a buffer argument's size (`air.arg_type_size`) and the member layout inside it (`air.struct_type_info`) as two independent facts, and reflection reconstructs them independently. When the reconstruction over-runs the declared size, some member's storage was mistaken and every member after it names an offset the shader never reads. Nothing else catches that. A consumer packs its upload at the reported offsets, so the disagreement is silent data corruption rather than anything a driver reports, and the emitted SPIR-V does not settle it either -- a buffer whose reconstruction is that far off is represented as raw bytes and declares no struct type to compare against. `validate_descriptor_abi`, which both reflection paths run, now rejects it, so the class that produced the previous commit becomes a translation error rather than a number a consumer has to re-derive. Reaching short stays valid: the declared size is a `sizeof` and carries tail padding. Over 2880 corpus sources 1340 reported layouts legitimately stop short and none over-run, so the gate rejects nothing that translates today. The bound needs `air_metadata_extent`, not `air_metadata_size_align`. The latter answers a different question -- the stride a pointee type needs -- and rounds to alignment, which over-runs the declared size for 96 corpus buffers whose layout is correct. It also inflates an array of `packed_half3` from six-byte to eight-byte elements, since the memcpy rule floors array alignment at four, whereas AIR states the per-element size in the member tuple itself. |
||
|
|
dd04f204e1 |
Report an argument-buffer handle at the size it occupies
Metal spells a resource-handle member of an argument buffer with the type it points AT -- `char` for a `device char *`, `float4x3` for a `device float4x3 *`, `texture2d<half, sample>` for a texture, an opaque class name for a `device Foo *` -- while the member itself stores an eight-byte handle. Reading that name as the member's storage put a 64-byte matrix where the buffer holds an address, and shifted the meaning of every member after it. `MTLGenericBVHData` reported a 120-byte member layout for its 72-byte argument, with eight of its nine members mistyped. The member's `air.indirect_argument` node already says which it is, and nothing read it: `air.indirect_constant` is the one role that means "stored inline"; `air.buffer`, `air.texture`, `air.sampler`, `air.indirect_buffer`, and the pipeline-state / command-buffer roles are all references. `parse_struct_info` walked past that suffix to find the next member; it now binds it to the member it trails, exactly as `embedded::embedded_argument_members` does, and lets the role decide. An unrecognized role is treated as a reference, since the declared size describes the bytes either way while a handle mistaken for its pointee corrupts the rest of the layout. Over 2880 corpus sources the split is clean: 63,137 members carry no suffix or an `air.indirect_constant` one and every single one of them agrees with its name; 2,762 carry a resource role and every single one of them declares eight bytes. 1,736 of those were mis-sized before -- 795 named a primitive of the wrong width across 9 type names, 941 named a type AIR never defines, which silently became a four-byte float. This is not only a reporting fix. Twenty-one modules' SPIR-V changes, because `infer_metadata_buffer_pointees` types a buffer from the same reconstruction: they declared four-byte floats at eight-byte member offsets and now declare the addresses AIR does. No corpus source changes status, and spirv-val is clean over all 2880. Reflection schema v36. |
||
|
|
8f9b185908 |
Report the access a buffer's descriptor is actually used with
`ResourceAccess` is what a consumer reads to decide whether a buffer's contents have to be staged, whether results have to be read back, and which barriers the resource needs. It came from AIR metadata, tightened by the specialized entry's parameter attributes -- neither of which is the module. AIR's declared access is not a guarantee about the body: over 2880 corpus sources, 20 buffers reflected `ReadOnly` are stored through, 9 reflected `WriteOnly` are loaded from, and 3 reflected `Unused` are both. `ReadOnly` on a buffer the shader writes is not a lost optimization; it is a missing barrier, and a write into memory a consumer may have placed as read-only. The footprint analyzer already resolves each load and store to the descriptor it belongs to -- through access chains, copies, phis, and function parameters -- so the direction is one more field on the access it already collects, not a second walk. `MemoryAccess` gains it, `analyze` returns the per-descriptor union alongside the footprints, and `attach_buffer_footprints` widens the reported access to cover it. It only ever widens. The walk follows the pointer graph it can attribute, so finding no write is not proof there is none -- an access through a device address it cannot attribute would be missed -- and narrowing on that basis would turn a conservative answer into a wrong one. `OpCopyMemory` needed the direction to belong to the access rather than the instruction: it has a reading pointer and a writing one. Atomics are classified read-modify-write, which is conservative for the two that only read. Verified over 2880 corpus sources: SPIR-V bytes identical, failure count unchanged at 204, and 34 modules' reflection changed -- the 32 the access sweep named plus two the sweep's per-class conditions did not separate. The sweep now reports 0. New `tests/reflection_access_covers_the_module.rs`: an authored kernel that contradicts both of its declared accesses -- `air.read` stored through, `air.write` loaded from -- plus the same check over every public fixture. Verified as a detector: dropping the widening fails the fixture test. `REFLECTION_VERSION` 34 -> 35, `docs/REFLECTION.md` follows, and `reflect_sanitized`'s doc comment now lists all three per-binding fields that are the declaration rather than the module when no module is built. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
ff227d77ea |
Check the descriptor count a consumer is told to allocate
`docs/REFLECTION.md` tells a consumer to group reflected entries by `(set, binding, descriptor type)` and take the largest `count`. That number is what sizes `VkDescriptorSetLayoutBinding::descriptorCount`, so if it does not reach the largest array the module declares at that binding, the layout is smaller than the array the shader indexes into. The rule was documented and untested. `assert_counts_cover_declared_arrays` reads the largest `OpTypeArray` behind each decorated binding out of the module and requires the grouped maximum to cover it. An authored `array_ref<texture2d<float, sample>>` kernel is the case with a real array -- it declares the descriptor-ABI capacity, 128 -- and the fixture sweep runs the same check. Verified as a detector: reporting one fewer descriptor for a `TextureArray` fails both. Measured over 2880 corpus sources first, since a test that only ever passes is not evidence: 0 bindings where the module's array outruns the grouped maximum. The naive comparison -- each entry's own `count` against the module -- reports 193 across the function-constant-gated modules, where one binding legitimately carries both a scalar and a 128-element variable and reflection reports an entry for each. That is the case the grouping rule exists for. The same sweep compared `local_size` against `OpExecutionMode LocalSize`: 0 disagreements over 2880 sources, so no check was needed there. No product change. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
b8fcc4cd44 |
Let only sampling decide a texture's binding class
AIR declares each texture argument's access, and reflection reports a write-capable one as a storage image at `STORAGE_TEXTURE_BINDING_BASE + n`, which is where a consumer writes its descriptor. The emitter chose the binding class from what the BODY does instead, and a size query counted as a sampled-image use. So a `texture2d<float, write>` whose body only calls `get_width()` bound at `TEXTURE_BINDING_BASE + n`: the consumer wrote its descriptor somewhere the shader does not read. Only sampling can decide this -- `OpSampledImage` is what requires `Sampled` 1. Everything else AIR does to a texture has a form for either class: `read_texture` is `OpImageRead` on a storage image and `OpImageFetch` on a sampled one, size and sample-count queries have an opcode each, `get_num_mip_levels` folds to one level on a storage image, and `is_null_texture` folds to a constant. The rule took two pieces before, and the gap was between them: `texture_dims` skips the read and query uses of a texture the body WRITES, and `storage_texel_read_operands` restored the ones a texel read had otherwise disqualified. A texture AIR declares write-capable but the body never writes fell through both. `sampled_binding_required_operands` replaces the pair with the one question that matters, and `storage_texel_read_operands` is gone. `air.gather_*` is not in the set, preserving what this classification has always done: a gathered AND written texture would need one descriptor to be both `Sampled` 1 and `Sampled` 2, the read-write-with-format case `write_texture_dims` documents as out of scope, and adding it converts those shaders into a write-lowering failure instead of resolving anything. I tried it: one corpus module regressed that way. Whether a gathered storage image reaches a correct lowering is unaudited and stated as such. Verified over 2880 corpus sources: bytes identical, reflection identical, failure count unchanged at 204. The gap needs a texture AIR declares writable that the body never writes, which no corpus shader does. New `native_write_declared_texture_binds_as_storage_even_if_the_body_only_queries_it` checks the module against the binding reflection reports, and is verified as a detector. `native_kernel_helper_wrapped_write_texture_query_resolves_loaded_image` was pinning the old behavior with an incidental `OpImageQuerySizeLod` assertion; its subject is that the query resolves to the wrapped texture, so it now expects the LOD-less form a storage image takes. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
a0995c4b3e |
Stop two callers sharing one scratch directory from failing each other
`spirv_val_bytes` wrote its input to `tmp/a2v_val.spv` and `air_to_sanitized_ll` wrote `llvm-dis` output to `tmp/k.ll`. `tmp` is caller-supplied and callers do share one: parallel tests, a sweep's worker threads, and separate processes pointed at the same directory. A fixed name there is shared mutable state -- one caller overwrites another's input and then deletes it, and the external tool reports on a file that is not the one the caller asked about, or on no file at all. It surfaces as a validation failure in a module that is fine, which is a false alarm the reader cannot tell from a real one. I hit it: `constructed_shapes_are_ valid_spirv` failed once, in a run where another `cargo test` process was validating into the same fixed directory, and passed every time after. One `scratch_file` names the file after the process and the call, so both callers stop sharing rather than every caller having to remember to pass a private directory. `cfg_testkit`'s deliberately fixed `m2v_cfg_testkit_val` is now safe as written; the relooper and reloop-nest helpers already made per-process directories. New `concurrent_validations_sharing_one_scratch_directory_do_not_collide`: eight threads validating one module into one directory, 16 times each. Verified as a detector -- with the fixed name restored it fails on all three of three runs. Verified: 2880 corpus sources byte-identical, reflection included, failure count unchanged at 204. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
de0ffdaa53 |
State once which images can carry a LOD in a size query
SPIR-V allows `OpImageQuerySizeLod` only on an image whose `Dim` is 1D, 2D, 3D, or Cube, whose `MS` is 0, and whose `Sampled` operand is not 2. Two lowerings emit a size query and each carried its own idea of that rule: `lower_image_size_query` handled storage and multisample images, `query_image_size` handled only storage, and neither handled `Dim Buffer`. So `texture_buffer::get_width()` -- ordinary Metal -- emitted `OpImageQuerySizeLod` on a buffer image. The owned-module check caught it and the whole translation fell back, which is honest but wrong: the shader is expressible, with the LOD-less `OpImageQuerySize`. One `image_size_query_op` now states the rule, and both lowerings ask it. A new `image_value_dim` reads the `Dim` from the pass-side record when there is one and from the emitted `OpTypeImage` otherwise, matching how the storage and multisample predicates beside it already work. New `native_buffer_texture_size_query_uses_query_size_without_lod`, verified as a detector: at the parent commit it fails with the fallback. It names the two existing cases that cover the other arms rather than restating them, since all three now go through the one predicate. Verified: 2880 corpus sources are byte-identical, reflection included, and the failure count is unchanged at 204 -- no corpus shader queried a buffer texture's size, so this is coverage the corpus does not reach. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
9d629a3e9f |
Reflect the image the module binds, not the one the type name implies
`ShaderReflection::texture_shape` is what a consumer feeds into `VkImageViewCreateInfo`, and Vulkan requires the created view's type to match the `Dim` and `Arrayed` of the image variable the descriptor is read through. The shape was decoded from the AIR type name, and the emitter does not always bind the image that name implies: SPIR-V has no cube texel fetch, so `resources::discovery` binds a `texturecube` that is only ever texel-read as a `Dim2D` ARRAY image with the face in the layer slot. Reflection kept saying `Cube`, so a consumer following it created a `VK_IMAGE_VIEW_TYPE_CUBE` view for a 2D-array image variable and the dispatch was invalid. `reconcile_texture_shapes` corrects each shape from the module's own `OpTypeImage` at that binding, the same way `reconcile_buffer_address_table` and `report_synthesized_placeholders` read their facts off the finished module. `array_ref` and `array_length` describe the descriptor array rather than the image, so they stay with the metadata that decides the descriptor count. A binding is only corrected when its image variables all declare the SAME image type. A function-constant-gated `air.location_index` puts several differently-shaped variables on one binding -- 67 corpus modules do -- and there the module has no single answer to read: the consumer picks one by choosing its function constants. `reflect_sanitized` builds no module and keeps the type-name-derived shape; its doc comment already listed what it approximates. `TextureFormat::from_spirv_format` inverts the existing `to_spirv_format` over a new `TextureFormat::ALL`, with a round-trip test that also proves the mapping is injective -- otherwise the inverse would not be single-valued. Measured over 2880 corpus sources by comparing every reflected shape against the `OpTypeImage` behind its binding: 2 modules disagreed, both cube textures reflected as `Cube` while the module declares 2D arrayed; 0 after. SPIR-V bytes identical and the failure count unchanged at 204; exactly those 2 modules' -- and, from the version bump, every module's -- reflection changed. New `tests/reflection_describes_the_image_it_binds.rs`. The cube fixture binds one AIR type name, `texturecube<float, ...>`, as two different emitted images: the texel-read source as a 2D array, the written destination as a cube. Verified as a detector -- with the reconcile removed it fails. A second authored kernel covers four shapes across dimensionality, component class, and storage format, and asserts they stay four distinct shapes so a decoder that widened them all could not pass by moving both sides together. Only one public fixture binds a texture, which is why the grammar probe carries the coverage; the fixture sweep is there for when that changes. `REFLECTION_VERSION` 33 -> 34: a cached v33 shape can name a view type the module rejects. `docs/REFLECTION.md` follows. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
e195fce0be |
Report the descriptors only the translator knows about
Two passes bind a real resource with no Metal argument behind it, so an AIR value has a legal SPIR-V type: `air.get_null_texture_*()` gets an `OpTypeImage`, `air.get_read_sampler()` gets an `OpTypeSampler`. The parent commit retracts those whose value nothing consumes. One that IS consumed stays -- and nothing in the AIR metadata describes it, so a consumer building its `VkDescriptorSetLayout` from `ShaderReflection` produced a layout the module reads outside of. This was the last of the module-vs-reflection descriptor mismatches. Over 2880 corpus sources the count is now 0, down from 267 when the oracle was first run. `ResourceKind::SynthesizedNullTexture` and `ResourceKind::SynthesizedReadSampler` report them. Which placeholders survive is a fact only the passes hold, so `transform` now returns it -- `Transformed` replaces the `(Module, EmitSidecar)` tuple -- and `finish_module` narrows the list to what the finished module still declares, since the steps after `transform` delete instructions and the liveness pass there can take a variable with them. Reflection reads each placeholder's class from the module's own `OpTypeImage`/`OpTypeSampler`, and a null texture's `texture_shape` off that image's operands, so nothing is inferred from binding numbers. That mirrors `reconcile_buffer_address_table`, which closed the same kind of gap for the address table. `validate_descriptor_abi` constrains a placeholder to its ABI band rather than to a recomputed `base + index`: it takes the first binding in the band no Metal argument claims, so there is no index to recompute from. Validation: `unsupported_reflection_requirements` marks a reflection carrying a placeholder with the new `ToolingRequirement::SynthesizedPlaceholderDescriptor`. The Vulkan executor has no authored resource to write at a descriptor no Metal argument produces, and the Metal oracle has nothing to encode, so the row is honestly not executable until the harness can supply a deterministic placeholder resource. It is not claimed as supported without execution evidence. Before this, such a row built a layout that omitted a binding the shader reads, so it was already failing rather than silently passing. The exhaustive `ResourceKind` match in `executor_contract.rs` is what forced the decision; that is what it is for. `reflect_sanitized` builds no module and therefore reports neither placeholder; its doc comment now says so alongside the address-table approximation it already documented. `REFLECTION_VERSION` 32 -> 33: a cached v32 reflection is missing a binding its module declares. `docs/REFLECTION.md` gains both kinds in its binding-map and descriptor-type tables. Verified over 2880 corpus sources: SPIR-V bytes identical, failure count unchanged at 204, and -- measured before the version bump, which changes every reflection hash -- exactly one module's reflection changed, the one the mismatch scan named. New authored fixture in `tests/reflection_covers_declared_bindings.rs`: a kernel that queries the placeholder's width, the counterpart to the unconsumed probe beside it. Verified as a detector: passing an empty placeholder list to `report_synthesized_placeholders` fails exactly that test. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
eaaf85abb0 |
Retract every descriptor the translator invented and nothing read
Two passes synthesize a resource with no Metal argument behind it, purely so an AIR value has a legal SPIR-V type. `air.get_read_sampler()` gets an `OpTypeSampler` because AIR threads a sampler pointer into the sampler-less `texture.read(coord)`; `air.get_null_texture_*()` gets an `OpTypeImage` because a function-constant-gated optional attachment still has to yield a handle. Either value can end up consumed by nothing -- a phi that folds away, an `air.is_null_texture` that becomes a constant -- and the descriptor then demands a resource the shader never reads, which reflection cannot report because no Metal argument corresponds to it. `cae8971` retracted the sampler. The rule was written over one named variable, so the identical null-texture case kept shipping. It is now stated once, over `Ctx::placeholder_descriptor_vars`: a third synthesized placeholder is covered by registering it rather than by copying the pass. The four sites that create a synthesized descriptor -- read sampler, null image, implicit imageblock plane, custom fragment imageblock plane -- had four copies of the same create-variable / decorate / add-to-interface block. They now share `Ctx::descriptor_variable`, and the two placeholder callers go through `Ctx::placeholder_descriptor`, which is what registers them for retraction. Choosing the binding stays with each caller, since the ABI band is what actually differs between them. Measured over 2880 corpus sources: module-declared bindings reflection omits went 4 -> 1, and exactly 3 modules changed bytes -- each dropping one OpTypeImage, one OpTypePointer, one OpVariable, its two descriptor decorations, and the unconsumed OpLoad. spirv-val passes on all three. The remaining 1 is a placeholder image the module genuinely reads, which needs reporting rather than retracting. New authored fixture in `tests/reflection_covers_declared_bindings.rs`: a kernel that asks `air.is_null_texture` about a placeholder and does nothing else with it. Verified as a detector -- it fails at the parent commit, where the module declares a texture binding reflection does not report. `native_get_null_texture_models_unmodeled_placeholder` asserted that binding exists. Its shader only stored the handle into an alloca nothing reads, which is now the retraction case, so it moves to a kernel that queries the placeholder's width -- a placeholder something DOES read keeps its descriptor -- and its band claim is now checked against every Binding decoration rather than a substring. Reflection output is byte-identical on all 2880 sources, so no REFLECTION_VERSION bump: this removes a binding reflection never reported. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
42a7998514 |
Name each reflected resource once
`ShaderReflection::bindings` is a work list: a consumer walks it and acts once per entry, allocating a descriptor, writing it, and sizing per-resource budgets from the length. `from_fragment` called `append_embedded_resources` twice with the same arguments, so every fragment entry with an `air.indirect_buffer` argument listed each of its argument-buffer residents twice and asked for that work twice. Nothing in the emitted module records the repeat -- the decorations it duplicates are already there once -- so `reflection_covers_declared_bindings.rs`, which asks whether reflection covers what the module declares, cannot see it. Measured over 2880 corpus sources: 405 fully-identical duplicate entries across 19 modules, all fragment `EmbeddedArgBufferTexture` and `EmbeddedArgBufferBuffer`. After: 0. To keep the class from returning silently, `validate_descriptor_abi` -- which both `reflect_sanitized` and the reflected translation path run -- now rejects two entries that agree in every field. Equality is the right test rather than the `(set, binding)` pair, which raw-word alias buffers legitimately share and which this check deliberately still allows; genuinely distinct resources always differ somewhere, in the Metal index, the entry-parameter index, or an argument-buffer resident's field offset. New `tests/reflection_describes_each_resource_once.rs` with an authored fragment fixture: one `air.indirect_buffer` holding a writable texture and a nested device buffer. Verified as a detector -- with the second append restored the fixture test and the gate test both fail. It also sweeps every public fixture and pins the gate itself, so deleting the check cannot make the other two pass by not looking. `REFLECTION_VERSION` 31 -> 32: a cached v31 reflection for such a fragment carries entries a consumer would act on twice. `docs/REFLECTION.md` follows. Verified: 2880 corpus sources, SPIR-V bytes identical and the failure count unchanged at 204; 19 modules differ in reflection only, the same 19 the duplicate scan named. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
aafe9f1342 |
Read the address table off the module instead of predicting it
Whether a shader needs a buffer-address table is decided by the constructed
pointer graph: the emitter creates the descriptor when the graph needs one.
Reflection derived the same fact a second way, from a text scan of the AIR --
`has_device_address_pointer_load` looks for an `inttoptr` or a `load ptr` through
a device-address pointer, and only for `Stage::Kernel`.
Two independent derivations of one fact disagree. Measured over 2880 corpus
sources: 39 modules, in both directions. 13 declared a table at binding 640 that
reflection omitted -- a consumer building its descriptor-set layout from the
reflection under-binds and the shader reads an unbound descriptor. 26 reflected a
table the module never declared, demanding a buffer nothing reads. The binding
number could have disagreed too; nothing tied the emitter's choice to
reflection's first-free-synthetic search.
`ShaderReflection::reconcile_buffer_address_table` observes the module: it reports
one `BufferAddressTable` per synthetic-band binding the finished module decorates,
replacing whatever was predicted. `translate_sanitized_native_reflected` calls it
right after translation, before footprints and the final descriptor-ABI check, and
no longer calls `add_buffer_address_table` beforehand.
`reflect_sanitized` builds no module and keeps the prediction. That is now stated
at the function, with the measurement, rather than left as an unmarked equivalence.
Verified over 2880 corpus sources, release build, rebuilt for the run:
- emitted-vs-reflected address table disagreements: 39 -> 0
- declared-but-unreflected bindings overall: 17 -> 4. The 4 that remain are
`default_null_image_of` placeholders (3 of them with an unconsumed load, the
same shape the read sampler had in
|
||
|
|
ca14b5b544 |
Report an imageblock plane wherever the module asks for one
The interface pass materializes a descriptor-backed render-target plane wherever it lowers an `air.load/store.implicit_imageblock.*` call, and the detector that finds those calls scans the module body -- it never looks at the stage. Reflection did look at the stage: `KernMeta` carried the detected attachments and `from_kernel` reported them, while `from_fragment` and `from_vertex` hardcoded an empty list. A fragment entry that reads its render target back through the implicit imageblock therefore emitted `OpDecorate %n Binding 200` and reflected nothing, so a consumer building its `VkDescriptorSetLayout` from `ShaderReflection` produced a layout that did not cover the shader. Verified on the authored fixture: before this change the module declared Binding 200 with `implicit_imageblock_attachments: []`; now it reports the plane at that binding. `FragMeta` and `VertMeta` now carry the field, filled by the same stage-agnostic detector, and one `implicit_imageblock_planes` helper does the meta-to-reflection mapping for all three constructors instead of the one copy `from_kernel` had. Scope of the evidence: all five corpus users of those intrinsics are kernels, so this is not a claim about how common fragment imageblock read-back is in real AIR. It is the module and its description disagreeing, which is a defect whether or not a shipped shader has hit it. `REFLECTION_VERSION` 30 -> 31, since a cached reflection from v30 is missing a binding its module declares. `docs/REFLECTION.md` said 29 and now says 31. Verified: 2880 corpus sources byte-identical (this changes reflection, not emission). The sweep in `tests/reflection_covers_declared_bindings.rs` stays at each fixture's declared stage. Translating a module at a stage its AIR does not declare leaves the stage parse with no source at all, so the reflection is a stub regardless of what the module contains; that is a different question from this one. Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test -p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation. |
||
|
|
cae8971fb7 |
Do not bind a sampler for a read that never samples
Metal's `texture.read(coord)` takes no sampler. AIR threads one in anyway, from
`air.get_read_sampler()`, and `lower_read` discards it -- so `default_read_sampler`
materialized a real `OpTypeSampler` UniformConstant variable, decorated it with a
DescriptorSet and Binding, and put it on the entry-point interface purely to give
that discarded value a type.
The result was a descriptor the shader never samples with, and one no consumer
could learn about: no Metal argument corresponds to it, so `ShaderReflection` has
nothing to report, while the module demands the binding regardless. A consumer
building a `VkDescriptorSetLayout` from the reflection produces a layout that does
not cover its own shader.
Measured over 2880 corpus sources: 267 bindings the module declared and reflection
omitted; 250 of them were this sampler, and in every single case the load of it had
no consumer at all -- 0 of 250. (The other 17 are two smaller classes, unchanged
here and stated below.)
The fix retracts the synthesis rather than papering over it in reflection: after
lowering, drop the loads of the default sampler that feed nothing, and the sweep
added in
|
||
|
|
7e47d44e8c |
State the global-variable liveness rule once
`fc_specialize` carried its own copy of it. After pruning the arms that read a
disabled feature's resources, `drop_unreferenced_entry_interface_globals`
rebuilt the entry interface from the variables function bodies still reference,
dropped the variables that left, and swept the debug/decorate records the prune
had orphaned -- 95 lines, including a second `defined_ids` identical to
`module_cleanup`'s.
That is `passes::drop_unreferenced_global_variables` followed by
`passes::drop_dangling_debug`. The copy differed in one way: it declined to
remove a variable that was not already in the entry interface. That narrowing
protects nothing -- `finalize` applies the broad rule to every module this
specializer is ever handed -- and it is not what the copy was for.
Verified, since this is a public API (`specialize_function_constants_zero`) with
no CLI path and therefore no ordinary corpus coverage. Translating all 2880
corpus sources and specializing each result:
- the narrowing was inert: 1816 variables removed across 880 sources, every
one of them already in the original entry interface, none outside it
- specialized output is byte-identical before and after, 0 of 2880 differ
- translator output is byte-identical too, 0 of 2880 differ
`drop_dangling_debug` now takes `&mut Module` rather than `&mut Ctx`, which is
all it ever read, and `drop_unreferenced_global_variables` filters interface
entries against the referenced set on every call rather than only when it has a
variable to remove -- so an interface entry naming an id that is not a declared
variable at all is dropped too, which is what the copy did and the shared rule
did not.
Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
|
||
|
|
7aac6cdb3a |
Stop shipping descriptor bindings no instruction reads
A translated module could declare a module-scope OpVariable that no
instruction anywhere references, list it in the entry point's interface, and
decorate it with a DescriptorSet and Binding. A consumer that builds a
VkDescriptorSetLayout from the interface -- the normal way to do it -- then has
to bind a descriptor the shader never touches.
Measured on the private corpus: 58 of 2880 sources, 1105 stranded variables
(1053 Private, 40 StorageBuffer, 12 UniformConstant). spirv-val accepts every
one of them, which is why nothing noticed.
The cause is a liveness snapshot that outlives the bodies it described.
`finalize` filters the entry-point interface to the variables the function
bodies reference, which is right -- and `function_referenced_ids` already says
so: "Entry-point interface variables should be live because code loads/stores/
access-chains them, not because an earlier pass registered them before a later
raw-alias rewrite replaced every use." But instruction-deleting work runs after
it at two boundaries: the pointer and access-chain closures at the tail of
`transform`, and dead-value elimination, constant-CFG pruning, and CFG
construction in `finish_module`. Once one of those deletes a variable's last
use, the arrangement is self-sustaining and nothing downstream can undo it:
`gc_dead_globals` roots liveness AT the entry-point interface, so the interface
entry keeps the variable alive and the variable justifies the interface entry.
`module_cleanup::drop_unreferenced_global_variables` breaks that cycle. It is
the rule stated once -- a global variable lives because an instruction names it
-- applied to the interface, the variable, its decorations, and its debug names
as one transaction, and it runs at each boundary after the last instruction
change there. It can only shrink the interface (an id it keeps is one an
instruction still names), so SPIR-V 1.4's requirement that the interface list
every global the entry point references is preserved. At the `finish_module`
boundary it is placed ahead of the existing null/undef constant sweep so the
initializers it strands are collected in the same step.
Verified over 2880 corpus sources, release build, rebuilt for the run:
- stranded module-scope variables: 58 modules -> 0 modules
- 58 modules differ, every one still OK; the other 2822 are byte-identical,
including all 204 unchanged FALLBACK messages
- removed across those 58: 1105 OpVariable, 1050 OpConstantNull, 104
OpDecorate, 2 OpName; 40,636 bytes. Nothing else changed.
- spirv-val --target-env vulkan1.2: 2676 VALID / 204 FALLBACK, unchanged
- corpus total 100.1s -> 100.7s, slowest source 2.54s -> 2.57s
Known residue, stated rather than hidden: removing the variables leaves 47
OpTypePointer and 2 OpConstantComposite declarations unreferenced across 29
modules. Those are inert declarations with no interface entry and no binding;
collecting the general type graph at that boundary is `gc_dead_globals`' job
and it does not run there.
Tests. The unit tests in `module_cleanup` are the pin: a module with two
descriptors in its interface and a load of only one must come out with the
stranded variable gone from the interface, the globals, its decoration, and its
name, with the live one untouched -- and the sweep must reach a fixed point in
one pass, since the pipeline runs it at more than one boundary.
`tests/live_module_scope_variables.rs` is the end-to-end net: no fixture, under
any stage it translates under, may produce a module declaring a global variable
no instruction references. That sweep is honest but currently vacuous on the
committed fixtures -- it still passes with both call sites removed. The trigger
needs a use deleted by SPIR-V-level constant folding, and llvm-reduce converged
only on inputs (a load through a null constant pointer) too artificial to
commit as an owned fixture. The corpus numbers above are the evidence that the
defect was real; the guard is what keeps a future fixture from reintroducing it
silently.
`fc_specialize::drop_unreferenced_entry_interface_globals` is a third statement
of the same rule, narrowed to variables that were already in the interface.
Consolidating it is a separate change; it is a public API's behavior.
Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
|
||
|
|
0546ccec98 |
Make the rule that names must not decide a translation a test
AGENTS.md's first ground rule is that emit and lowering decisions come from
IR structure, never from a hardcoded function, type, or variable identifier,
and that a name-keyed branch is a defect even when it happens to work. Nothing
checked it. That is the worst shape for a rule: the shader that was tested keeps
translating, so the branch is invisible until a consumer ships an identically
shaped shader spelled differently.
The check is metamorphic. Rewrite every identifier the AIR/LLVM contract does
not own -- global symbols, named struct/class/union types, named local values,
and the bare block labels that define them -- to a generated placeholder, and
translate again. Structure and semantics are untouched, so the two runs must
produce the same module. Only the SPIR-V debug-name section, which exists to
carry those identifiers, may differ; it is dropped before the comparison and
nothing else is.
The contract families that may NOT be perturbed are listed with the code that
reads each: air.*, llvm.*, __air_sampler_state, mtl.*, _GLOBAL__sub_I*, and any
symbol carrying MTL_ (function constants, visible-function references). That
list is the first written-down statement of which names are ABI here.
Committed AIR names the entry after the Metal function and leaves everything
else numbered, so sweeping the public fixtures perturbs one or two names each.
Three inputs are authored for the test instead:
- a kernel whose entry, helpers, parameters, and locals are all spelled as
near-misses of contract names (air_get_width_texture_2d, llvm_fabs_f32,
%texture_buffer, %_cube_array). The helpers are called, so a loosened
residual-intrinsic test leaves their calls unlowered.
- a texture-handle array whose LLVM struct type claims
metal::texture_buffer<float, access::write> while the AIR metadata declares
array<texture2d<float, sample>, 2>. The metadata is the ABI: the emitted
image must be 2D. texture_buffer is the first substring the texture shape
decoder tests for.
- a kernel whose Metal entry is already named main, the one case where an
incoming name collides with an emitted one.
Verified: the suite is a detector, not decoration -- loosening
is_residual_intrinsic from starts_with("air.") to starts_with("air") in
native::ir::ordinary_inline fails the look-alike kernel, and the label-renaming
path was itself found by the fixture sweep rejecting a module whose %body uses
were renamed but whose body: definition was not.
Separately measured, not asserted here: over 2880 private corpus sources this
rewrite leaves every translation byte-identical once debug names are dropped,
and each of air., llvm., __air, and _GLOBAL__sub_I is load-bearing (dropping
one from the contract list changes 136-417 of 500 sampled modules).
Test-only; no product path changed. Gate: fmt, clippy -D warnings, warnings-
denied all-features rustdoc, cargo test -p metal2vulkan (debug and release),
cargo test -p metal2vulkan-validation.
|
||
|
|
bf8493b773 |
Delete four string helpers the typed carrier replaced
`is_phi_line`, `redirect_label`, `is_ident_char` (`structured_emit/phi_util.rs`) and `relower_phi` (`tir/phi_edit.rs`) are `#[cfg(test)]`, so they are not in a release build at all — they are what is left of the string-line era, kept alive by their own tests. Each has a typed successor that the codebase already points at: `TirInst::is_phi` (`tir/mod.rs:1191` calls the string form its "dual"), the typed terminator redirects (`tir/mod.rs:379,413`, "the typed dual of applying the text `redirect_label`"), and the specific typed phi edits `relower_phi`'s own module doc lists in its place. `is_ident_char` had no caller but `redirect_label`. `inline.rs` keeps its own private `is_phi_line`; that one is production and untouched. The three tests that exercised only the deleted helpers go with them (1732 -> 1728). Test-only code with production visibility reads as live behaviour, and this crate has enough of it that I mistook one for a live bug site earlier in this session. `cargo fmt --all --check`, clippy `-D warnings`, `RUSTDOCFLAGS='-D warnings' cargo doc`, `cargo test -p metal2vulkan` debug and release, `cargo test -p metal2vulkan-validation`. No release binary change is possible: every deleted item was `#[cfg(test)]`. |