Commit Graph
20 Commits
Author SHA1 Message Date
Anees Iqbal 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.
2026-08-31 23:54:56 +03:00
Anees Iqbal 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.
2026-08-31 23:34:36 +03:00
Anees Iqbal 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.
2026-08-31 23:09:09 +03:00
Anees Iqbal 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 cae8971).
  - 2880 sources byte-identical: this changes reflection, not emission.

No new test. `deterministic_output.rs::the_device_address_kernel_really_reads_an_
address_table` already pins the positive case and still passes through the new
path. I tried to author a failing case -- a fragment entry doing the same
device-address load, where the prediction is gated off by stage -- and the emitter
built no table for it, so the fixture would have asserted nothing. The corpus
numbers above are the evidence; the disagreeing sources are private.

Folded into the unreleased reflection v31 rather than bumping again.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 22:55:54 +03:00
Anees Iqbal 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.
2026-08-31 22:46:04 +03:00
Anees Iqbal 08970cacd2 Consolidate translation, linkage, and validation work
Squash 147 commits (2026-08-20 through 2026-08-31) into one change on top
of the exact-kernel-grid work. Covers native lowering and pointer/layout
construction, AIR intrinsic and funnel-shift coverage, BDA address
preservation across aggregate calls, CFG structurization, function-constant
and visible-function specialization, the 30-second translation ceiling, the
authored-case corpus and linkage validation suite, and refreshed byte-exact
MoltenVK evidence.

The kernel-grid lowering in this tree supersedes the 324-line variant in
the parent commit; that file is reduced to its current 139-line form here.

Resulting tree is identical to 7174c7b. Prior history remains reachable at
tag pre-squash-backup and branch backup/pre-squash-7174c7b.

Claude-Session: https://claude.ai/code/session_01D1u4vU7Mr5QNWrnnRHC8iS
2026-08-31 09:03:42 +03:00
Anees Iqbal 9ff250502c Make exact kernel grids safe by default
Model kernel dispatch geometry as a typed contract shared by lowering, reflection, validation, and the CLI. Cull surplus dispatchThreads invocations using fixed or reflected push-constant grid bounds, make that safe dynamic-grid path the default, and require an explicit whole-workgroup assertion to omit it.

Reject unsafe source-barrier kernels before every product emission facade by following the selected AIR entry graph, including quoted LLVM symbols. Exercise the same default contract in authored candidate validation and document the host ABI.

Keep corpus audit parent concurrency bounded by feeding isolated translation workers from scratch-backed stdin files instead of creating one feeder thread per row. This removes the scoped-thread exhaustion that aborted late full censuses while retaining child decoding inside the time and memory watchdog.

Verified with format checking, warnings-denied workspace clippy and Rustdoc, validation tests at concurrency 16, the unchanged downstream repro, a forced 88,819-row audit completing in one invocation at jobs 16, failure retries, and a zero-read warm pass.
2026-08-22 02:16:13 +03:00
Anees Iqbal 8e95e84d0c Close specialization and descriptor audit gaps
Distinguish image descriptors from texel buffers, scope synthesized binding occupancy by descriptor set, and decouple the Metal texture source limit from configurable descriptor ranges. Centralize retry finalization and runtime sampler projection so layout and specialization contracts cannot drift across paths. Refresh consumer documentation and add adversarial descriptor tests.
2026-08-20 08:31:42 +03:00
Anees Iqbal 12abadb798 Add caller-selected descriptor layouts
Thread a versioned, validated descriptor layout through emission, reflection, synthesized resources, retry-created address tables, and Vulkan validation. Preserve the existing ABI as the explicit default and cover cross-stage separation, static samplers, embedded textures, raw aliases, invalid ranges, and default byte identity.
2026-08-20 07:52:35 +03:00
Anees Iqbal c37cd41b29 Align storage image reflection refusals
Enforce runtime storage-image component compatibility at the metadata-only reflection boundary as well as executable translation. Update every matching reflected storage binding, cover the authored embedded-texture checker path, and advance reflection and executor fingerprints to prevent stale reuse.\n\nVerified with cargo fmt, warnings-denied workspace clippy and Rustdoc, 1364 serial product tests, and 144 serial validation tests.
2026-08-20 07:05:05 +03:00
Anees Iqbal f3e376361b Specialize embedded runtime storage images
Route writable argument-buffer textures, including fixed descriptor arrays, through the runtime storage-image format and capability contract. Reflect their applied state by synthetic resource index and teach authored validation to resolve structural owner/offset identities through reflection before candidate translation. Bump reflection and executor fingerprints so stale outputs are not reused.\n\nVerified with cargo fmt, warnings-denied workspace clippy and Rustdoc, 1364 serial product tests, and 144 serial validation tests.
2026-08-20 07:00:10 +03:00
Anees Iqbal 547a59d99b Specialize runtime storage image formats
Accept runtime storage surface formats and host feature facts by Metal texture index, specialize image types before interface creation, and reflect the exact explicit or formatless contract. Track runtime origins through arrays and image aliases so every read, write, imageblock write, emulated fetch, and atomic operation checks the required capability or refuses honestly.\n\nWire authored validation resources into the same product options, bump the reflection and candidate executor contracts, document consumer use, and cover type splitting, dependent loads, exact formatless capabilities, atomics, incompatibility, missing bindings, imageblock writes, and pixel-gather storage reads.\n\nVerified with workspace clippy -D warnings, warnings-denied all-features Rustdoc, serial product and validation suites, both packaged AIR reproductions plus spirv-val Vulkan 1.3, and release measurements under 0.5 seconds / 23 MiB RSS.
2026-08-20 06:47:22 +03:00
Anees Iqbal 04666b0f44 Specialize runtime sampler state structurally
Accept bounded pipeline sampler state by Metal index, attach it to the emitted runtime sampler SSA value, and reuse the static sampler lowering seam for pixel-coordinate sampling, addressing, depth, comparison, and LOD refusals. Reflect only applied sampler states and make the validation executor consume that synchronized contract.\n\nCover normalized/pixel switching, fragment and kernel indices, all supported address modes, offsets, depth comparisons, serde, validation plumbing, and honest unsupported-state refusals.
2026-08-20 05:59:50 +03:00
Anees Iqbal 7cf240e05a Fix descriptor binding band collisions
Replace overlapping resource bases with checked sampled-texture, sampler, color, imageblock, storage-texture, and synthetic descriptor bands shared by emission and reflection. Reject unknown or cross-class descriptor layouts at the final module boundary, keep constexpr/default allocation inside its band, and bump reflection ABI version 22.

Also resolve kernel function-constant resource locations consistently, coalesce compatible aliases in the Vulkan validation consumer, and cover high/last indices plus sampled/storage aliases end to end.

Verified with serial product and validation tests, warnings-denied workspace clippy and Rustdoc, the packaged descriptor collision repro, a 500-row current-fingerprint translation checkpoint, and release translation at 0.02s / 22,216,704-byte max RSS.
2026-08-20 05:14:56 +03:00
Anees Iqbal 8b78eaca3b Expand macOS 26 AIR translation coverage
Overhaul the validation workflow around sharded authored cases, dependency-exact observations, incremental indexed corpus audits, bounded parallel translation, and native Metal/Vulkan comparison.\n\nExpand native AIR lowering, reflection, linked-function specialization, resource and stage-interface support, and structural CFG/pointer repair across the harvested macOS 26 corpus. Add exact intrinsic inventory, distributed 16x16x16 matrix lowering, explicit opaque tensor linkage, and regression coverage for the newly supported feature classes.\n\nThe final corpus verification accounts for all 88,819 indexed AIR modules under the current product fingerprint: 65,355 translate and validate directly, 23,464 require exact authored linkage, and zero fail or remain unresolved.
2026-08-13 21:46:27 +02:00
Anees Iqbal 3fbe8e516b Harden AIR translation and consumer validation
Expand structural image, buffer, control-flow, and passthrough lowering, including driver-safe relooper limits and regression coverage.\n\nExpose buffer extent, type, and refined access in reflection v4 for downstream consumers.\n\nHarden corpus oracle planning and loop safety, quarantine non-semantic rows, and refresh the affected translation and execution ledgers.\n\nVerified with cargo fmt --all, workspace clippy with warnings denied, and serial product and validation test suites.
2026-08-10 11:44:46 +02:00
Anees Iqbal 8d982e649e Fix MS/sampler/FC-gating lowering and re-bank execution ledgers
Consolidates the translation fixes surfaced by post-runner triage of the private
corpus, together with the validation-harness work needed to actually run and compare
those cases, and re-banks execution evidence for all three backends.

63 files, +31,520/-6,780. Translator: 51 files under src/, +6,670/-314. Validation
crate: 7 files under validation/src/, +24,813/-6,410. The four
validation/corpus/metal2vulkan-ledger*.jsonl files are Git LFS pointers, so the
tracked diff is 4 lines while the referenced objects are fully re-banked.

================================================================================
Translation fixes
================================================================================

Texture and sampler lowering
  src/passes/air_calls/images/{mod.rs,write_read.rs,sample_depth.rs},
  src/passes/air_calls/dispatch_texture.rs, src/passes/resources/texture_array.rs
- AIR `texture2d_ms` / multisample depth reads now build a multisampled
  `OpTypeImage` (MS=1) and pass the sample id as a `Sample` image operand instead of
  treating it as a mip `Lod`. Multisample size queries use `OpImageQuerySize`
  without a LOD operand.
- Texel-buffer reads (`Dim Buffer`) omit the `Lod` operand entirely; `Dim Buffer`
  has no mip levels, so the operand was invalid.
- Depth sampling and compare-depth paths that select between AIR `constexpr sampler`
  state globals now resolve to a real SPIR-V sampler id, so `OpSampledImage` always
  receives a valid sampler operand.
- Texture-array descriptors carry (dim, arrayed, component type, MS) so array
  element image types match the declared AIR texture type.

Fragment stage interface
  src/meta/{mod.rs,globals.rs,tests.rs}, src/passes/stage_input/{mod.rs,air_layout.rs},
  src/reflect/mod.rs, src/passes/resources/discovery.rs
- New `FragRole::SampleId` and `FragRole::FrontFacing`. `[[sample_id]]` lowers to
  `BuiltIn SampleId` with the required `SampleRateShading` capability;
  `[[front_facing]]` lowers to `BuiltIn FrontFacing`.
- Function-constant-gated `[[color(n)]]` outputs now follow the AIR default-zero
  predicate model (`function_constant_gate_global` /
  `output_metadata_enabled_by_default`), so two mutually exclusive render-target
  formats no longer advertise themselves at the same Vulkan location.

Pointer and access-chain legality under Logical addressing
  src/passes/access/{dynamic_reinterpret.rs,mod.rs}, src/spirv_variable_ptr.rs,
  src/native/emitter/body/{gep_provenance.rs,core_inst.rs,mod.rs,vector_store.rs,
  reinterpret_pointer.rs}, src/native/emitter/pointers/*
- Dynamic sub-word views (`half`/`ushort`/`uchar`) of a raw `{ RuntimeArray<uint> }`
  buffer block lower to `dyn / lanes_per_word` for the backing word plus a lane
  extract/insert, rather than an illegal single dynamic index into the Block struct.
- Dynamic 64-bit views (`ulong`/`long`/`double`) of the same raw model address
  `word = dyn * 2` and `word + 1`, assembling/splitting the scalar little-endian.
- A dynamic index into a homogeneous `OpTypeStruct` (an `[N x T]` array that LLVM
  bitcasts exposed as N identical members) becomes a select over constant-member
  loads, since SPIR-V struct indices must be constants.
- Zero-stride `OpPtrAccessChain` on StorageBuffer demotes to a plain
  `OpAccessChain`; Private palette-array pointer phis likewise use ordinary access
  chains instead of pointer-stride forms.
- Struct-global GEPs (inline and promoted) preserve their zero member index, and
  flat-scalar global views translate through view indices.
- Large dynamic vector extract/insert lowers through composite selects.
- Pointer `OpIEqual`/`OpINotEqual` against loop cursor/end pointers reserves forward
  GEP phi root provenance; unmodeled device GEP phis take a placeholder rather than
  emitting an invalid pointer phi.
- Function-scope aggregate scalar-reinterpret stores target member 0.

Function constants
  src/fc_specialize.rs, src/passes/air_calls/integer_simd.rs
- `air.is_function_constant_defined` now emits a named
  `__metal2vulkan.MTL_FC_DEFINED_<N>` marker that specialization rewrites to
  `OpConstantTrue`/`OpConstantFalse`: all predicates true under zero specialization,
  only the listed indices true under value specialization.
- Value specialization materializes vector-integer FC initializers (lanes split out
  of the little-endian value) and rewrites thread-local byte-subslot stores.

Module cleanup, CFG repair, and retry
  src/native/rewrites.rs, src/native/relooper.rs, src/retry.rs, src/lib.rs,
  src/native/error_class.rs, src/passes/module_cleanup.rs,
  src/native/emitter/ops/atomics.rs, src/native/emitter/functions.rs,
  src/native/emitter/body/calls.rs, src/native/ir/ordinary_inline/mod.rs
- `drop_workgroup_struct_padding_byte_zero_stores_module` removes byte-addressed
  Workgroup padding clears produced from `llvm.memset.p3`; an `OpPtrAccessChain
  %uchar*` from a `%struct*` base is not expressible in Logical addressing, and the
  stores are value-preserving to drop (harness zero-fills, no typed load can observe
  the padding). Real member stores are kept.
- `drop_dangling_debug_targets_module` removes `OpName`/annotation records whose
  target id an earlier rewrite deleted (constant-branch pruning of FC helper
  globals). Both run in `finish_module` before validation, so the retry cascade only
  sees semantic failures.
- The relooper rematerializes pure opaque image/descriptor loads at their use: an
  opaque handle loaded in a non-entry block dominates in the original CFG but not
  once both blocks become sibling switch cases, and handles cannot spill to memory.
- `inline_sroa_raw_relooped` uses the capped relooper, runs
  `repair_relooped_access_chains`, and can escalate through PSB/WG remodel; a new
  `inline_sroa_raw_cfg_restructure` tier joins the cascade for the TopK
  multi-destination shape.
- `reject_visible_function_references` is now
  `reject_unsupported_metal_linked_functions` and also fails fast on
  `air.patch_control_point_function` / `.MTL_CONTROL_POINT_FN`, since tessellation
  patch inputs are not lowered.
- The pointer-typing error classifier recognizes spirv-val's "does not match the
  type that results from indexing into the Composite".
- StorageBuffer atomics carrying Workgroup scope rewrite to Device/Relaxed, and AIR
  barrier memory scope/semantics derive from the barrier's device flag so a
  threadgroup barrier orders StorageBuffer memory.
- Internal calls skip extra AIR ABI operands by formal parameter type.

Tests
  ~38 new unit/integration tests across src/native/tests/{textures,buffers,interface,
  control_flow,intrinsics,threadgroup,types,misc}.rs, src/passes/access/mod.rs,
  src/fc_specialize.rs, src/native/rewrites.rs, src/native/relooper.rs,
  src/spirv_variable_ptr.rs, src/meta/tests.rs.

================================================================================
Validation harness
================================================================================

validation/src/loop_budget.rs (+7,669/-638)
- The pre-submission loop-budget classifier now accepts `LoopInputFacts`: function
  constant values, exact and upper-bound integer/float argument values, constant-GEP
  struct field values, integer vector lane values and bounds, bound texture extents,
  and the imageblock extent. Facts propagate through direct calls, and
  classification starts from the entry function instead of the whole module. Far
  more loops are provably bounded, which is what moves Metal quarantine 2,480 -> 18.

validation/src/oracle_macos.rs (+1,779/-21)
- Derives those facts from AIR metadata plus the concrete bound inputs
  (`exact_scalar_arg_values`, `exact_launch_vector_arg_values`,
  `exact_texture_extent_values`, `exact_struct_arg_values`, ...) and substitutes
  imageblock extent/implicit-load AIR calls with constants before `metal-as`.

validation/src/corpus_run.rs (+14,982/-5,643)
- Seed profile `deterministic_v6_finite_float_render_targets` ->
  `deterministic_v7_thread_indexed_inputs`: thread-indexed input buffers are resized
  to the dispatch grid, output-stride seeds are applied, atomic-counter and
  read-only buffer arguments are recognized, and bounded-control seeding covers
  float vector lanes and result-dimension struct fields.
- Default per-case timeout 60s -> 300s.
- Function-constant value selection for oracle inputs, integer divisors, and
  barrier-loop progress, plus collision detection for conditionally bound resources.
- New incompatible-golden detectors: multisample textures, FC texture-array refs, FC
  private pointer tables, FC simdgroup, and `compare=none` simdgroup-matrix /
  raytracing smoke kernels.
- `--compile-missing` mode: cases with no comparable Metal golden are translated and
  recorded as `smoke` rows carrying the skip reason in `error`, instead of being
  left as empty `missing` cells.

validation/src/runner_linux.rs (+326/-71)
- Derives the full set of fragment color attachments from `air.render_target`
  metadata and the output locations the SPIR-V actually writes, and creates the
  extra attachment views, instead of assuming location 0 only.
- Enables and preflights the `sampleRateShading` feature / `SampleRateShading`
  capability.
- Compute/vertex pipeline creation returns `Result` rather than panicking.

validation/src/corpus_triage.rs
- `tolerance` counts as success only for the Vulkan candidate backend; MoltenVK must
  match the Metal golden byte-exactly.

validation/src/texture.rs
- `depthcube<...>` / `depthcube_array<...>` map to cube / cube-array texture kinds,
  which previously fell through to `Plain`.

================================================================================
Ledger re-bank (rows keyed by air_sha256, last write wins)
================================================================================

"Passing" below means ok + tolerance, i.e. the row reproduced the Metal golden
exactly or within the documented per-format tolerance. Note that this commit also
tightens `execution_status_is_success`: tolerance now counts only for the Vulkan
candidate backend (Metal and MoltenVK require exact `ok`), so the MoltenVK
tolerance rows are reported here for completeness but no longer bank as passes.

Metal goldens (metal2vulkan-ledger-metal.jsonl)  43,514 -> 43,622 rows
  passing      39,986 -> 42,124  (96.6%)   no tolerance rows on either side
  ok           39,986 -> 42,124      quarantine    2,480 ->     18
  fallback      1,048 ->  1,476      timeout           0 ->      4
  comparable goldens (compare=full) 20,336 -> 23,430
  Transitions: quarantine->ok 2,058, quarantine->fallback 404, 108 new rows,
  ok->fallback 23, ok->timeout 4, fallback->ok 3.

MoltenVK (metal2vulkan-ledger-moltenvk.jsonl)    37,136 rows
  passing      28,743 -> 30,089  (81.0%)   = ok 30,089 + tolerance 0
  ok           28,660 -> 30,089      failure       3,828 ->      0
  tolerance        83 ->      0      fallback      1,333 ->      0
  quarantine      491 ->    136      timeout         473 ->      0
  missing       2,268 ->  6,911
  Transitions: failure->ok 538, fallback->ok 410, missing->ok 286,
  quarantine->ok 184, tolerance->ok 11; failure->missing 3,290,
  fallback->missing 923, timeout->missing 473, quarantine->missing 172,
  tolerance->missing 72.

Vulkan / Linux (metal2vulkan-ledger-vulkan.jsonl) 39,090 rows
  passing       5,970 ->  9,823  (25.1%)   = ok 9,243 + tolerance 580
  ok            3,341 ->  9,243      smoke            17 -> 28,846
  tolerance     2,629 ->    580      missing      31,277 ->      0
  quarantine    1,826 ->    421
  Transitions: missing->ok 7,094, tolerance->ok 218, quarantine->ok 148;
  missing->smoke 23,484, tolerance->smoke 2,219, quarantine->smoke 1,568,
  ok->smoke 1,558.

Net state: 42,124 of 43,622 Metal golden rows pass, and 30,089 of 37,136 MoltenVK
rows pass -- all of them exact, byte-identical to the Metal golden they were
compared against, with no tolerance rows left in that ledger. That is ~30k
Metal/MoltenVK pairs in sync out of a ~43.6k-case corpus. On Linux Vulkan 9,823
rows pass (9,243 exact + 580 within tolerance), up from 5,970; the 28,846 `smoke`
rows are compile-only evidence with a recorded reason why no semantic compare was
possible, replacing the 31,277 blank `missing` cells.

Caveats worth stating plainly: a large share of the MoltenVK `failure`/`fallback`/
`timeout` reduction is reclassification, not repair -- 4,930 rows became `missing`
because re-banking the Metal side under seed profile v7 invalidated their golden,
against 1,346 net rows genuinely turning passing (28,743 -> 30,089). Likewise 1,558
Vulkan rows regressed from `ok` to compile-only `smoke` because their golden is no
longer comparable, and 2,219 more moved from `tolerance` to `smoke`.

The translate ledger (metal2vulkan-ledger.jsonl) is carried forward essentially
unchanged: 43,657 rows, 39,090 ok / 4,557 fallback / 10 timeout, with a single row's
SPIR-V digest re-minted.
2026-07-29 14:35:45 +03:00
Anees Iqbal 53b627809c Expand AIR translation and validation coverage 2026-07-26 00:43:57 +03:00
Anees Iqbal 3338acecb5 Reflect AIR constexpr sampler state
Reserve translator-owned constexpr samplers inside the sampler descriptor\nband instead of allowing framebuffer-fetch bindings to push them into the\ncolor-input range. Decode the full two-word AIR sampler state and expose it\nthrough reflection schema version 3 so Vulkan consumers can create the exact\nimmutable sampler rather than guessing from the emitted descriptor.

Keep emission and reflection ordering aligned by the stable AIR sampler\nglobal suffix, and cover the pipe25 shape with runtime sampler, two static\nsamplers, and a framebuffer-fetch color input.

Verified with:\n- cargo test --workspace --all-features -- --test-threads=1\n- cargo clippy --workspace --all-targets --all-features -- -D warnings
2026-07-24 02:23:35 +03:00
Anees Iqbal 3007485352 🆕 Open Source metal2vulkan 2026-07-22 13:15:24 +03:00