diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0e5c66aa5..9c18de484 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -118,13 +118,17 @@ When the primary emit fails validation (or the emitter returns an error), transl ladder of retry **tiers**. Mechanisms live in `retry.rs`; routing lives in `translate_sanitized_with_meta` as a match on `native::classify_{validation,emit}_error`. -Two invariants: +Three invariants: 1. **Adopt only if the candidate validates.** A module that already passed spirv-val never enters the cascade; a non-validating retry result is discarded. 2. **Tier order is load-bearing.** Example: value-select before PhysicalStorageBuffer (device-address) lowering, because some drivers cannot pipeline BDA modules as compute; inline+SROA before relooper where that ordering has been proven safer. Do not reorder tiers casually. +3. **Validator success is not a driver-cost proof.** The whole-function switch/state-machine + relooper has a hard 1,024-block ceiling. Larger flattened modules can validate quickly while + taking real drivers many minutes to compile or crashing their compiler, so they return + `FALLBACK` until a regional structurizer can preserve most of the CFG and SSA. Classification of validator/emitter text into `ValidationClass` / `EmitErrorClass` is confined to `native` (`classify_validation_error` / `classify_emit_error`). The cascade then routes by class: @@ -132,7 +136,7 @@ Classification of validator/emitter text into `ValidationClass` / `EmitErrorClas | Class | Typical tier order (census labels under `METAL2VULKAN_TIER_CENSUS`) | |---|---| | PointerTyping | `fc_promote_logical` → raw → prune → subword pack → raw+relooper → `fc_promote_psb` | -| CfgStructurization | relooper → relooper (huge) → raw+relooper | +| CfgStructurization | relooper → prune+relooper → raw+relooper | | LogicalPointerPhi | phi-index legalization → prune | | CrossBindingPointerMerge | value-select → PSB → raw+PSB → prune | | Other (validation) | prune → raw+relooper → value-select | diff --git a/docs/REFLECTION.md b/docs/REFLECTION.md index dc51533e8..44f6fface 100644 --- a/docs/REFLECTION.md +++ b/docs/REFLECTION.md @@ -55,7 +55,7 @@ metal2vulkan = { version = "0.1", features = ["serde"] } ``` `ShaderReflection` and its nested types derive `Serialize`/`Deserialize` under that feature. -Bump-aware field: `reflection_version` (`REFLECTION_VERSION`, currently `3`). Invalidate any +Bump-aware field: `reflection_version` (`REFLECTION_VERSION`, currently `4`). Invalidate any on-disk cache when that constant changes. ## Descriptor ABI (binding map) @@ -122,17 +122,40 @@ Top-level fields: | `metal_index` | Guest Metal slot `n`, or synthetic index for embedded textures | | `descriptor` | `{ set, binding }` or `None` if no descriptor (threadgroup / some locals) | | `param_index` | SPIR-V `OpFunctionParameter` order, if any | -| `address_space` / `declared_size` / `type_layout` | Buffer layout and sizing | +| `address_space` / `declared_size` / `type_layout` | Buffer address space, argument/pointee size, and aggregate layout | +| `extent` | Buffer reachability: `Object { bytes }`, `Unbounded`, or `Unknown` | | `type_name` | AIR type string when metadata carried it | | `texture_shape` | Dim / arrayed / MS / component / writable / storage format (decoded) | | `embedded_source` | For arg-buffer textures: owning buffer index + field byte offset | -| `access` | When known: `ReadOnly` / `ReadWrite` / `Sampled` / `Storage` | +| `access` | When known: `Unused` / `ReadOnly` / `WriteOnly` / `ReadWrite` / `Sampled` / `Storage` | | `static_sampler` | Decoded immutable state for `StaticSampler`; `None` for other kinds | +### Buffer extent and access + +`extent` is a conservative sizing contract: + +- `Object { bytes }` is emitted only when AIR carries `air.buffer_size`, which proves that the + argument is one bounded reference-like object. A consumer may narrow staging to `bytes`. +- `Unbounded` means AIR identifies a pointer/pointee type but does not carry an array length. +- `Unknown` means the metadata does not distinguish a bounded object from an unbounded pointer. + +Treat both `Unbounded` and `Unknown` as “retain the complete caller-provided window.” An incorrect +narrowing is silent data corruption, so reflection never infers an object extent merely from +`declared_size`: for pointer arguments that field can be only the pointee size. Device-space +bindings expose `declared_size` when AIR carries `air.arg_type_size`; a `void *` with no size +metadata remains `None`. + +Buffer `access` begins with AIR's declared `air.read` / `air.write` / `air.read_write` qualifier. +The reflected translate paths then tighten that declaration using the specialized LLVM entry: +an unused parameter becomes `Unused`, while sound `readonly` and `writeonly` parameter attributes +become `ReadOnly` and `WriteOnly`. When neither source proves a narrower result, the broader AIR +classification is retained. + **Gaps consumers should expect:** -- **Device buffer R/W:** precise read-vs-write often needs SPIR-V dataflow; many buffers have - `access: None`. Prefer IR analysis or treat as read-write unless `address_space` is constant. +- **Device buffer R/W:** ambiguous parameters retain their conservative AIR declaration; malformed + or unusually sparse metadata can still leave `access: None`, which consumers must treat as + read-write. - **Function constants from meta-only builders:** `from_*` constructors leave `function_constants` empty; populate via the reflected translate paths (they scan sanitized IR). - **Datalayout:** only filled when translating from unsanitized `.air`/`.ll` via diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 2ca78c6c6..51b9d195e 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -250,11 +250,11 @@ Candidate statuses: |---|---|---| | `ok` | exact byte match | leave it alone | | `tolerance` | float-like output is within recorded tolerance | accepted; leave it alone unless the policy is wrong | -| `smoke` | candidate executed and captured bytes, but the Metal row is `compare=none` rather than a semantic golden | accepted as an execution smoke; rebank Metal for semantic comparison | +| `smoke` | legacy candidate row derived from a Metal `compare=none` bounded-smoke row | non-semantic; quarantine it and rebank Metal before candidate execution | | `failure` | candidate ran and produced bytes, but they do not match / exceed tolerance | inspect output class; reduce to a synthetic test when possible | | `fallback` | translate, bind, pipeline creation, dispatch, readback, or harness panic before comparable bytes | inspect `error`; usually a harness or executor gap | | `missing` | no usable Metal golden for this hash | rerun/fix `corpus-run-metal` first | -| `quarantine` | Metal loop guard refused to dispatch | do not force GPU execution; improve loop-budget proof or accept quarantine | +| `quarantine` | no safe semantic Metal oracle (including loop-guarded, transformed, or historic `compare=none` work) | do not force GPU execution; improve the proof/harness or accept quarantine | | `timeout` | worker process exceeded `METAL2VULKAN_CORPUS_TIMEOUT_SECS` | rerun single-case with `--jobs 1`; treat persistent timeouts as harness/tool hangs | Use `corpus-triage` to see the current queue: @@ -271,6 +271,34 @@ cargo run -p metal2vulkan-validation --release --bin corpus-triage -- \ On macOS, validation's Metal oracle and MoltenVK-backed runner are machine-specific. On Linux, use a native Vulkan ICD. Treat execution as **layer E**, not the daily default. +Only a Metal `status=ok`, `compare=full` row with captured output bytes is a semantic oracle. +Bounded loop instrumentation and implicit imageblock substitution remain useful compile-only +preflights, but the Metal runner quarantines them instead of submitting transformed work or banking +its bytes. Candidate runners propagate that quarantine without GPU submission; they never treat a +historic `compare=none` row as exact, tolerance, or smoke evidence. + +Targeted recovery of historic `compare=none` rows is deliberately two-step: + +```sh +# Compile through Metal PSO creation without creating/submitting a command buffer. The ledger is +# unchanged; the output list contains only structurally semantic, successfully compiled rows. +cargo run -p metal2vulkan-validation --release --bin corpus-run-metal -- \ + --air-list selected-hashes.txt --force --preflight-only \ + --preflight-safe-list preflight-safe.txt + +# Only an explicit hash/list may opt historic compare=none rows into semantic reminting. +cargo run -p metal2vulkan-validation --release --bin corpus-run-metal -- \ + --air-list preflight-safe.txt --force --remint-compare-none +``` + +The preflight source gate rejects unsupported standalone ABIs, unsafe synthetic input +configurations, CFG-analysis refusals, and every reachable CFG cycle before invoking Apple tools. +It is intentionally stricter than the bounded-loop instrumentation classifier: a finite trip count +alone does not prove a quantitative aggregate GPU-time bound. For large private corpora, split the +hash list by its existing corpus shards so each source-analysis process releases parser memory +before the next shard; do not run several shard-wide Metal preflights concurrently on a +memory-constrained host. + ### 7. Agent loop over ledger failures An agent should not start by rerunning the whole corpus. The useful loop is: diff --git a/src/env_vars.rs b/src/env_vars.rs index 274255aa3..f1fcaa109 100644 --- a/src/env_vars.rs +++ b/src/env_vars.rs @@ -37,7 +37,7 @@ pub const REGISTRY: &[EnvVar] = &[ EnvVar { name: "METAL2VULKAN_RELOOPER_MAX_BLOCKS", default: "1024", - effect: "relooper block-count cap", + effect: "requested relooper block-count cap (hard maximum: 1024)", }, // paths EnvVar { @@ -246,7 +246,8 @@ pub fn val_par() -> usize { .unwrap_or(3) } -/// Relooper block-count cap. Default is the caller-supplied `fallback` (`MAX_RELOOPER_BLOCKS`). +/// Requested relooper block-count cap. The native relooper applies its hard product safety maximum +/// after reading this value, so the override can lower the cap but cannot raise it above 1024. pub fn relooper_max_blocks(fallback: usize) -> usize { std::env::var("METAL2VULKAN_RELOOPER_MAX_BLOCKS") .ok() diff --git a/src/lib.rs b/src/lib.rs index 68113022c..0391ebbac 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -329,6 +329,7 @@ pub fn translate_sanitized_native_reflected( // Function constants are a cross-stage IR fact (not in the per-stage meta): scan the sanitized // IR once so a consumer can discover the module's spec-ids without walking SPIR-V. reflection.function_constants = meta::parse_function_constants(san_ll); + reflection.refine_buffer_access_from_entry(san_ll); // AIR constexpr samplers are module globals rather than entry parameters, so stage metadata // does not carry them. Reflect their decoded state and the same first-free sampler-band // allocation used by the interface pass before returning the consumer contract. @@ -1017,12 +1018,6 @@ fn translate_sanitized_with_meta( rc.prune_then_relooper(&out), ) }) - // Last resort for a HUGE (>1024-block) emitted module whose only blocker is the cfg - // nesting violation — lift the relooper cap (see `relooper_retry_huge`). Clears - // 02/07ef16ba (4630 blocks, reducible, no secondary wall). - .or_else(|| { - rc.census("val-cfg:relooper_huge", rc.relooper_retry_huge(&out)) - }) // The relooper structures the CFG but its from-scratch rebuild can EXPOSE a // cross-binding pointer merge (`Variable pointers must point into the same structure` // on an `OpSelect %_ptr_StorageBuffer_*`) that the repaired form kept off the failing diff --git a/src/meta/mod.rs b/src/meta/mod.rs index f5de13f6a..d0e5efd33 100644 --- a/src/meta/mod.rs +++ b/src/meta/mod.rs @@ -50,6 +50,15 @@ pub enum FragRole { Other, } +/// Declared AIR access on a buffer argument. This is a conservative contract: it may be broader +/// than the specialized body actually uses, but it never understates reads or writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BufferAccess { + ReadOnly, + WriteOnly, + ReadWrite, +} + /// A fragment shader's decoded parameter roles + render-target count/indices. #[derive(Clone, Debug, Default)] pub struct FragMeta { @@ -91,6 +100,14 @@ pub struct FragMeta { /// `param_idx -> declared AIR buffer byte size` (`air.arg_type_size` / `air.buffer_size`), when /// the AIR node carries it. Mirrors [`KernMeta::buffer_type_sizes`] for the fragment stage. pub buffer_type_sizes: HashMap, + /// `param_idx -> air.buffer_size` for reference-like arguments whose metadata bounds the + /// reachable object to exactly that many bytes. Kept separate from `buffer_type_sizes`, which + /// may only be an unbounded pointer's element/pointee size. + pub buffer_object_sizes: HashMap, + /// `param_idx -> AIR buffer argument type name` for every stage. + pub buffer_type_names: HashMap, + /// `param_idx -> declared AIR read/write qualifier`. + pub buffer_accesses: HashMap, /// `param_idx -> AIR texture argument type name`, e.g. `texture2d`. pub texture_type_names: HashMap, /// Framebuffer-fetch color input Location -> AIR render-target type name, e.g. `float4`. @@ -200,6 +217,9 @@ pub struct VertMeta { /// `param_idx -> declared AIR buffer byte size` for buffer args, when the AIR carries it (see /// [`FragMeta::buffer_type_sizes`]). pub buffer_type_sizes: HashMap, + pub buffer_object_sizes: HashMap, + pub buffer_type_names: HashMap, + pub buffer_accesses: HashMap, /// `param_idx -> AIR texture argument type name`, e.g. `texture2d`. pub texture_type_names: HashMap, } @@ -291,8 +311,12 @@ pub struct KernMeta { /// `param_idx -> declared AIR buffer argument byte size`, from `air.arg_type_size` or /// `air.buffer_size` when present. pub buffer_type_sizes: HashMap, + /// `param_idx -> air.buffer_size` when AIR declares one exact reference-object extent. + pub buffer_object_sizes: HashMap, /// `param_idx -> AIR buffer argument type name`, e.g. `char`, `void`, or a struct name. pub buffer_type_names: HashMap, + /// `param_idx -> declared AIR read/write qualifier`. + pub buffer_accesses: HashMap, /// `param_idx -> AIR texture argument type name`, e.g. `texture2d`. pub texture_type_names: HashMap, /// Textures EMBEDDED inside an `air.indirect_buffer` argument buffer (via `air.indirect_argument` @@ -379,7 +403,9 @@ fn parse_air_kernel_meta_with_nodes( let mut imageblock_layouts = HashMap::new(); let mut buffer_address_spaces = HashMap::new(); let mut buffer_type_sizes = HashMap::new(); + let mut buffer_object_sizes = HashMap::new(); let mut buffer_type_names = HashMap::new(); + let mut buffer_accesses = HashMap::new(); let mut texture_type_names = HashMap::new(); // `air.location_index` of every top-level `air.texture` arg — the basis for the synthetic // embedded-texture index K (see `embedded_synthetic_texture_index`). @@ -422,6 +448,12 @@ fn parse_air_kernel_meta_with_nodes( { buffer_type_sizes.insert(idx, size); } + if let Some(size) = i32_after_marker(node, "air.buffer_size") { + buffer_object_sizes.insert(idx, size); + } + if let Some(access) = declared_buffer_access(node) { + buffer_accesses.insert(idx, access); + } KernRole::Buffer(location_index(node, idx)) } "texture" => { @@ -481,7 +513,9 @@ fn parse_air_kernel_meta_with_nodes( imageblock_layouts, buffer_address_spaces, buffer_type_sizes, + buffer_object_sizes, buffer_type_names, + buffer_accesses, texture_type_names, embedded_textures, }) @@ -842,6 +876,18 @@ fn arg_type_name(body: &str) -> Option { string_after_marker(body, "air.arg_type_name") } +fn declared_buffer_access(body: &str) -> Option { + if body.contains("air.read_write") { + Some(BufferAccess::ReadWrite) + } else if body.contains("air.write") { + Some(BufferAccess::WriteOnly) + } else if body.contains("air.read") { + Some(BufferAccess::ReadOnly) + } else { + None + } +} + fn arg_name(body: &str) -> Option { string_after_marker(body, "air.arg_name") } @@ -964,6 +1010,9 @@ fn parse_air_fragment_meta_with_nodes( let mut varying_loc = 0u32; let mut buffer_address_spaces = HashMap::new(); let mut buffer_type_sizes = HashMap::new(); + let mut buffer_object_sizes = HashMap::new(); + let mut buffer_type_names = HashMap::new(); + let mut buffer_accesses = HashMap::new(); // AIR function-param pointer address spaces for the fragment entry, the fallback the kernel // parser uses when a buffer arg node omits `air.address_space`. let param_address_spaces = entry @@ -1028,6 +1077,15 @@ fn parse_air_fragment_meta_with_nodes( { buffer_type_sizes.insert(idx, size); } + if let Some(size) = i32_after_marker(node, "air.buffer_size") { + buffer_object_sizes.insert(idx, size); + } + if let Some(name) = arg_type_name(node) { + buffer_type_names.insert(idx, name); + } + if let Some(access) = declared_buffer_access(node) { + buffer_accesses.insert(idx, access); + } FragRole::Buffer(location_index_with_static(node, idx, &static_int_globals)) } // an air.render_target in the INPUT list = framebuffer fetch ([[color(n)]]). @@ -1057,6 +1115,9 @@ fn parse_air_fragment_meta_with_nodes( buffer_layouts, buffer_address_spaces, buffer_type_sizes, + buffer_object_sizes, + buffer_type_names, + buffer_accesses, texture_type_names, color_input_type_names, }) @@ -1118,6 +1179,9 @@ fn parse_air_vertex_meta_with_nodes( let mut buffer_layouts = HashMap::new(); let mut buffer_address_spaces = HashMap::new(); let mut buffer_type_sizes = HashMap::new(); + let mut buffer_object_sizes = HashMap::new(); + let mut buffer_type_names = HashMap::new(); + let mut buffer_accesses = HashMap::new(); let mut texture_type_names = HashMap::new(); let param_address_spaces = entry .and_then(|name| function_param_pointer_address_spaces(ll, name)) @@ -1158,6 +1222,15 @@ fn parse_air_vertex_meta_with_nodes( { buffer_type_sizes.insert(idx, size); } + if let Some(size) = i32_after_marker(node, "air.buffer_size") { + buffer_object_sizes.insert(idx, size); + } + if let Some(name) = arg_type_name(node) { + buffer_type_names.insert(idx, name); + } + if let Some(access) = declared_buffer_access(node) { + buffer_accesses.insert(idx, access); + } VertRole::Buffer(location_index_with_static(node, idx, &static_int_globals)) } "texture" => { @@ -1183,6 +1256,9 @@ fn parse_air_vertex_meta_with_nodes( buffer_layouts, buffer_address_spaces, buffer_type_sizes, + buffer_object_sizes, + buffer_type_names, + buffer_accesses, texture_type_names, }) } diff --git a/src/native/emitter/body/calls.rs b/src/native/emitter/body/calls.rs index 4999e4f2c..a1e9c6df0 100644 --- a/src/native/emitter/body/calls.rs +++ b/src/native/emitter/body/calls.rs @@ -604,11 +604,11 @@ impl Emitter { /// live. /// /// Gated structurally and tightly so it only fires for the genuine case: the arg must be a Local with - /// a raw_offsets entry that is an IDENTITY reference to a device buffer root (addrspace 1, zero const - /// offset, no dynamic terms, modelable) whose root is a real buffer param value. Any non-identity - /// reference (a non-zero or dynamic offset) would lose the offset if rooted — so it is declined and - /// resolves normally. This lives ONLY on the call-argument path; the default emit path is unchanged, so - /// pointer merges / direct accesses of the bitcast result keep their Private placeholder semantics. + /// a modelable descriptor-backed `raw_offsets` entry whose root is a real device-buffer param. A + /// constant non-zero cursor is recorded for that callee parameter and reapplied while the helper is + /// emitted; conflicting call-site cursors and dynamic offsets fail visibly rather than silently + /// discarding an offset. This lives ONLY on the call-argument path; direct accesses and pointer merges + /// keep their existing behavior. pub(in crate::native::emitter) fn raw_device_call_arg_id( &mut self, callee: &str, @@ -633,10 +633,13 @@ impl Emitter { let LlValue::Local(arg_name) = &arg.value else { return Ok(None); }; - let Some(raw) = self.raw_offsets.get(arg_name) else { + let Some(raw) = self.raw_offsets.get(arg_name).cloned() else { return Ok(None); }; - if raw.addrspace != 1 || raw.const_off != 0 || !raw.dyn_terms.is_empty() || raw.unmodelable + if raw.addrspace != 1 + || !raw.dyn_terms.is_empty() + || raw.unmodelable + || raw.device_addr_base.is_some() { return Ok(None); } @@ -644,6 +647,20 @@ impl Emitter { if !self.param_values.contains(&root) || !self.raw_buffer_params.contains(&root) { return Ok(None); } + let key = (callee.to_string(), param_name.to_string()); + if let Some(previous) = self.raw_call_param_offsets.get(&key) { + if previous.const_off != raw.const_off || previous.addrspace != raw.addrspace { + return Err(format!( + "native emitter: raw helper parameter @{callee} {param_name} is called with \ + conflicting constant byte offsets {} and {}", + previous.const_off, raw.const_off + )); + } + } else { + let mut parameter_raw = raw; + parameter_raw.root = param_name.to_string(); + self.raw_call_param_offsets.insert(key, parameter_raw); + } let id = self.value_id_in(&LlValue::Local(root), &arg.ty, instructions)?; Ok(Some(id)) } diff --git a/src/native/emitter/body/core_inst.rs b/src/native/emitter/body/core_inst.rs index b30088ace..9895a6ac4 100644 --- a/src/native/emitter/body/core_inst.rs +++ b/src/native/emitter/body/core_inst.rs @@ -451,6 +451,28 @@ impl Emitter { instructions: &mut Vec, ) -> Result<(), String> { let resolved_ty = self.resolve_type(&argument.ty)?; + // Preserve a descriptor-backed raw buffer's byte cursor across helper inlining. A non-zero + // GEP of a raw device buffer has a Private placeholder as its ordinary SSA value, while its + // real descriptor root and byte offset live in `raw_offsets`. Binding the helper parameter + // to that placeholder silently turns helper writes into Private writes. Root the inline + // substitution at the descriptor instead and carry the cursor onto the parameter; the + // callee's existing raw load/store lowering then reapplies the offset structurally. + let inline_raw = if self.raw_buffer_params.contains(name) { + match &argument.value { + LlValue::Local(source) => self.raw_offsets.get(source).cloned().filter(|raw| { + raw.addrspace == 1 && !raw.unmodelable && raw.device_addr_base.is_none() + }), + _ => None, + } + } else { + None + }; + let inline_raw_storage = inline_raw.as_ref().map(|raw| { + self.pointer_storage + .get(&raw.root) + .copied() + .unwrap_or(StorageClass::StorageBuffer) + }); let pointer_facts = if let LlType::Ptr(addrspace) = resolved_ty { let storage = self.pointer_storage_for(&argument.value, addrspace)?; let pointee = self.pointer_pointee_for_value(&argument.value)?; @@ -463,7 +485,15 @@ impl Emitter { } else { None }; - let argument_id = self.value_id_in(&argument.value, &argument.ty, instructions)?; + let argument_id = if let Some(raw) = inline_raw.as_ref() { + self.value_id_in( + &LlValue::Local(raw.root.clone()), + &argument.ty, + instructions, + )? + } else { + self.value_id_in(&argument.value, &argument.ty, instructions)? + }; let placeholder_id = self.fresh(); self.values .insert(name.to_string(), (placeholder_id, resolved_ty.clone())); @@ -508,10 +538,18 @@ impl Emitter { self.record_pointer_nullness(name.to_string(), nullness); } if self.raw_buffer_params.contains(name) { - self.raw_offsets.insert( - name.to_string(), - RawBufferOffset::root(name.to_string(), addrspace), - ); + if let Some(mut raw) = inline_raw { + raw.root = name.to_string(); + self.raw_offsets.insert(name.to_string(), raw); + if let Some(storage) = inline_raw_storage { + self.pointer_storage.insert(name.to_string(), storage); + } + } else { + self.raw_offsets.insert( + name.to_string(), + RawBufferOffset::root(name.to_string(), addrspace), + ); + } } } Ok(()) diff --git a/src/native/emitter/functions.rs b/src/native/emitter/functions.rs index 6e947e277..16206d4ad 100644 --- a/src/native/emitter/functions.rs +++ b/src/native/emitter/functions.rs @@ -157,8 +157,13 @@ impl Emitter { self.pointer_pointees.insert(name.clone(), pointee); } if self.raw_buffer_params.contains(name) && !concrete_workgroup_raw_param { - self.raw_offsets - .insert(name.clone(), RawBufferOffset::root(name.clone(), addrspace)); + let mut raw = self + .raw_call_param_offsets + .get(&(f.name.clone(), name.clone())) + .cloned() + .unwrap_or_else(|| RawBufferOffset::root(name.clone(), addrspace)); + raw.root = name.clone(); + self.raw_offsets.insert(name.clone(), raw); } } self.direct_param_values.insert(name.clone()); diff --git a/src/native/emitter/mod.rs b/src/native/emitter/mod.rs index 00c9fdd3e..edee0e580 100644 --- a/src/native/emitter/mod.rs +++ b/src/native/emitter/mod.rs @@ -98,6 +98,10 @@ pub(super) struct Emitter { param_values: HashSet, inline_parameter_substitutions: Vec<(Word, Word)>, raw_buffer_params: HashSet, + /// Constant descriptor-relative byte cursors passed to raw helper parameters, keyed by + /// `(callee, parameter)`. The emitted-helper inliner can then keep a non-zero caller GEP rooted + /// in the real StorageBuffer instead of the ordinary Private placeholder value. + raw_call_param_offsets: HashMap<(String, String), RawBufferOffset>, /// Current function's entry params declared `air.buffer` in kernel metadata (data pointers, /// never textures/samplers). Rebuilt per emit_function from `ir.metadata_data_buffer_params`. data_buffer_params: HashSet, @@ -442,6 +446,7 @@ impl Emitter { param_values: HashSet::new(), inline_parameter_substitutions: Vec::new(), raw_buffer_params: HashSet::new(), + raw_call_param_offsets: HashMap::new(), data_buffer_params: HashSet::new(), raw_offsets: HashMap::new(), int_alignments: HashMap::new(), diff --git a/src/native/emitter/ops/air_calls.rs b/src/native/emitter/ops/air_calls.rs index cb29745aa..8f9fdef27 100644 --- a/src/native/emitter/ops/air_calls.rs +++ b/src/native/emitter/ops/air_calls.rs @@ -165,25 +165,6 @@ impl Emitter { instructions: &mut Vec, ) -> Result { match call.callee.as_str() { - // `air.get_null_texture_()` yields a NULL texture handle. In the MPS NDArray - // kernels (TopK/pooling/FFT-chirp) the result is stored into a vestigial `texture2d` - // field of an `_MPSKernelInOut`/`MPSNDArrays` wrapper struct and forwarded to an - // inlined helper, but NEVER sampled/read (these are pure buffer-compute kernels). Model - // it as an unmodeled null pointer so the downstream store/forward validates; byte-safe - // by construction because the handle is never dereferenced. Dispatches on a stable - // `air.*` ABI symbol, not on a shader name. - callee if callee.starts_with("air.get_null_texture") => { - let result_ty = self.resolve_type(&call.ret)?; - let LlType::Ptr(addrspace) = result_ty else { - return Err(format!( - "native emitter: {} returned non-pointer {result_ty:?}", - call.callee - )); - }; - self.define_unmodeled_byte_pointer_value(name, addrspace)?; - self.null_texture_values.insert(name.to_string()); - Ok(true) - } // `air.is_null_texture_(%tex)` asks whether a texture handle is the null texture. // We consume it HERE only when `%tex` is a value we ourselves synthesized from // `air.get_null_texture_*` (tracked in `null_texture_values`): that value never crosses diff --git a/src/native/opaque_image_select.rs b/src/native/opaque_image_select.rs index 54399a226..6e30eb852 100644 --- a/src/native/opaque_image_select.rs +++ b/src/native/opaque_image_select.rs @@ -44,6 +44,7 @@ struct TreePlan { /// Replace a selected opaque image consumed only by explicit-LOD sampling with a select over the /// sampled value. Returns `true` only after the entire use closure has passed the strict gate. pub(super) fn rewrite_opaque_image_selects(module: &mut Module) -> bool { + let phi_changed = rewrite_opaque_image_phis(module); let type_defs: HashMap = module .types_global_values .iter() @@ -168,7 +169,7 @@ pub(super) fn rewrite_opaque_image_selects(module: &mut Module) -> bool { } if replacements.is_empty() { - return false; + return phi_changed; } for (function, func) in module.functions.iter_mut().enumerate() { @@ -209,6 +210,500 @@ pub(super) fn rewrite_opaque_image_selects(module: &mut Module) -> bool { true } +/// Lower a stale pointer-typed `OpPhi` whose incoming values are all the same image type into a +/// plain integer tag phi. Every external use must be a pure image query/read with a non-opaque +/// result; each use is replayed for every image arm and the ordinary results are selected by tag. +/// This is the control-flow analogue of [`rewrite_opaque_image_selects`]. +fn rewrite_opaque_image_phis(module: &mut Module) -> bool { + let type_defs: HashMap = module + .types_global_values + .iter() + .filter_map(|inst| inst.result_id.map(|id| (id, inst.clone()))) + .collect(); + let value_types: HashMap = module + .all_inst_iter() + .filter_map(|inst| match (inst.result_id, inst.result_type) { + (Some(id), Some(ty)) => Some((id, ty)), + _ => None, + }) + .collect(); + let global_ids: HashSet = module + .types_global_values + .iter() + .filter_map(|inst| inst.result_id) + .collect(); + let mut positions = HashMap::new(); + let mut uses: HashMap> = HashMap::new(); + for (function, func) in module.functions.iter().enumerate() { + for (block, blk) in func.blocks.iter().enumerate() { + for (instruction, inst) in blk.instructions.iter().enumerate() { + let site = Site { + function, + block, + instruction, + }; + if let Some(id) = inst.result_id { + positions.insert(id, site); + } + for (operand, value) in inst.operands.iter().enumerate() { + if let Operand::IdRef(id) = value { + uses.entry(*id).or_default().push(UseSite { site, operand }); + } + } + } + } + } + let dominators = module + .functions + .iter() + .map(block_dominator_indices) + .collect::>(); + let value_dominates_site = |value: Word, site: Site| { + if global_ids.contains(&value) { + return true; + } + let Some(def) = positions.get(&value).copied() else { + return false; + }; + if def.function != site.function { + return false; + } + if def.block == site.block { + return def.instruction < site.instruction; + } + dominators + .get(site.function) + .and_then(|function| function.get(site.block)) + .is_some_and(|blocks| blocks.contains(&def.block)) + }; + + let uint_ty = type_defs.iter().find_map(|(&id, inst)| { + (inst.class.opcode == Op::TypeInt + && matches!( + inst.operands.as_slice(), + [Operand::LiteralBit32(32), Operand::LiteralBit32(0)] + )) + .then_some(id) + }); + let bool_ty = type_defs + .iter() + .find_map(|(&id, inst)| (inst.class.opcode == Op::TypeBool).then_some(id)); + let (Some(uint_ty), Some(bool_ty)) = (uint_ty, bool_ty) else { + return false; + }; + + #[derive(Clone)] + enum PhiConsumer { + Direct(UseSite), + Sampled { + sampled_site: Site, + sample_uses: Vec, + }, + } + + #[derive(Clone)] + struct PhiPlan { + site: Site, + result: Word, + arms: Vec<(Word, Word)>, + consumers: Vec, + } + + let mut plans = Vec::new(); + for (function, func) in module.functions.iter().enumerate() { + for (block, blk) in func.blocks.iter().enumerate() { + for (instruction, inst) in blk.instructions.iter().enumerate() { + if inst.class.opcode != Op::Phi + || !inst + .result_type + .is_some_and(|ty| is_pointer_type(&type_defs, ty)) + { + continue; + } + let Some(result) = inst.result_id else { + continue; + }; + let mut arms = Vec::new(); + let mut image_ty = None; + let mut valid = inst.operands.len() >= 4 && inst.operands.len().is_multiple_of(2); + for pair in inst.operands.chunks_exact(2) { + let (Operand::IdRef(value), Operand::IdRef(label)) = (&pair[0], &pair[1]) + else { + valid = false; + break; + }; + let Some(&ty) = value_types.get(value) else { + valid = false; + break; + }; + if !is_image_type(&type_defs, ty) + || image_ty.is_some_and(|expected| expected != ty) + { + valid = false; + break; + } + image_ty = Some(ty); + arms.push((*value, *label)); + } + if !valid { + continue; + } + let Some(result_uses) = uses.get(&result) else { + continue; + }; + let mut consumers = Vec::new(); + let mut consumers_valid = !result_uses.is_empty(); + for use_site in result_uses { + let Some(consumer) = instruction_at(module, use_site.site) else { + consumers_valid = false; + break; + }; + if use_site.operand != 0 { + consumers_valid = false; + break; + } + if matches!( + consumer.class.opcode, + Op::ImageQuerySizeLod | Op::ImageQuerySize | Op::ImageFetch | Op::ImageRead + ) && consumer.result_id.is_some() + && consumer.result_type.is_some() + && !consumer + .result_type + .is_some_and(|ty| is_opaque_type(&type_defs, ty)) + && arms + .iter() + .all(|(value, _)| value_dominates_site(*value, use_site.site)) + { + consumers.push(PhiConsumer::Direct(*use_site)); + continue; + } + if consumer.class.opcode != Op::SampledImage { + consumers_valid = false; + break; + } + let Some(sampled_id) = consumer.result_id else { + consumers_valid = false; + break; + }; + let Some(sample_uses) = uses.get(&sampled_id).cloned() else { + consumers_valid = false; + break; + }; + let sampler = consumer.operands.get(1).and_then(|operand| match operand { + Operand::IdRef(id) => Some(*id), + _ => None, + }); + if sample_uses.is_empty() + || sampler.is_none() + || sample_uses.iter().any(|sample_use| { + sample_use.operand != 0 + || instruction_at(module, sample_use.site).is_none_or(|sample| { + sample.class.opcode != Op::ImageSampleExplicitLod + || sample.result_id.is_none() + || sample.result_type.is_none() + || sample + .result_type + .is_some_and(|ty| is_opaque_type(&type_defs, ty)) + }) + || arms.iter().any(|(value, _)| { + !value_dominates_site(*value, sample_use.site) + }) + || !value_dominates_site( + sampler.expect("sampled-image sampler was gated"), + sample_use.site, + ) + }) + { + consumers_valid = false; + break; + } + consumers.push(PhiConsumer::Sampled { + sampled_site: use_site.site, + sample_uses, + }); + } + if !consumers_valid { + continue; + } + plans.push(PhiPlan { + site: Site { + function, + block, + instruction, + }, + result, + arms, + consumers, + }); + } + } + } + if plans.is_empty() { + return false; + } + + let mut next_id = module + .header + .as_ref() + .map(|header| header.bound) + .unwrap_or(1); + let fresh = |next_id: &mut Word| { + let id = *next_id; + *next_id += 1; + id + }; + let mut constants = HashMap::new(); + for plan in &plans { + for ordinal in 0..plan.arms.len() as u32 { + constants.entry(ordinal).or_insert_with(|| { + module + .types_global_values + .iter() + .find_map(|inst| { + (inst.class.opcode == Op::Constant + && inst.result_type == Some(uint_ty) + && inst.operands.first() == Some(&Operand::LiteralBit32(ordinal))) + .then_some(inst.result_id) + .flatten() + }) + .unwrap_or_else(|| fresh(&mut next_id)) + }); + } + } + let existing_ids: HashSet = module + .types_global_values + .iter() + .filter_map(|inst| inst.result_id) + .collect(); + let first_variable = module + .types_global_values + .iter() + .position(|inst| inst.class.opcode == Op::Variable) + .unwrap_or(module.types_global_values.len()); + let mut new_constants = constants + .iter() + .filter(|(_, id)| !existing_ids.contains(id)) + .map(|(&value, &id)| { + Instruction::new( + Op::Constant, + Some(uint_ty), + Some(id), + vec![Operand::LiteralBit32(value)], + ) + }) + .collect::>(); + new_constants.sort_by_key(|inst| inst.result_id); + module + .types_global_values + .splice(first_variable..first_variable, new_constants); + + let mut replacements = HashMap::>::new(); + let mut removed_ids = HashSet::new(); + for plan in plans { + let tag = fresh(&mut next_id); + let mut phi_operands = Vec::with_capacity(plan.arms.len() * 2); + for (ordinal, (_, label)) in plan.arms.iter().enumerate() { + phi_operands.push(Operand::IdRef(constants[&(ordinal as u32)])); + phi_operands.push(Operand::IdRef(*label)); + } + replacements.insert( + plan.site, + vec![Instruction::new( + Op::Phi, + Some(uint_ty), + Some(tag), + phi_operands, + )], + ); + removed_ids.insert(plan.result); + + for consumer_plan in plan.consumers { + let (consumer, use_sites, sampled_template) = match consumer_plan { + PhiConsumer::Direct(use_site) => ( + instruction_at(module, use_site.site) + .expect("opaque image phi consumer disappeared") + .clone(), + vec![use_site], + None, + ), + PhiConsumer::Sampled { + sampled_site, + sample_uses, + } => { + let sampled = instruction_at(module, sampled_site) + .expect("opaque image phi sampled-image consumer disappeared") + .clone(); + replacements.insert(sampled_site, Vec::new()); + if let Some(id) = sampled.result_id { + removed_ids.insert(id); + } + (sampled, sample_uses, Some(sampled_site)) + } + }; + for use_site in use_sites { + let value_consumer = if sampled_template.is_some() { + instruction_at(module, use_site.site) + .expect("opaque image phi sample consumer disappeared") + .clone() + } else { + consumer.clone() + }; + let result_ty = value_consumer + .result_type + .expect("gated image consumer result type"); + let final_result = value_consumer + .result_id + .expect("gated image consumer result"); + let mut out = Vec::new(); + let mut arm_results = Vec::with_capacity(plan.arms.len()); + for (image, _) in &plan.arms { + let result = fresh(&mut next_id); + let mut cloned = value_consumer.clone(); + cloned.result_id = Some(result); + if sampled_template.is_some() { + let sampled_result = fresh(&mut next_id); + let mut sampled = consumer.clone(); + sampled.result_id = Some(sampled_result); + sampled.operands[0] = Operand::IdRef(*image); + out.push(sampled); + cloned.operands[0] = Operand::IdRef(sampled_result); + } else { + cloned.operands[0] = Operand::IdRef(*image); + } + out.push(cloned); + arm_results.push(result); + } + let mut selected = arm_results[0]; + for ordinal in 1..arm_results.len() { + let condition = fresh(&mut next_id); + out.push(Instruction::new( + Op::IEqual, + Some(bool_ty), + Some(condition), + vec![ + Operand::IdRef(tag), + Operand::IdRef(constants[&(ordinal as u32)]), + ], + )); + let result = if ordinal + 1 == arm_results.len() { + final_result + } else { + fresh(&mut next_id) + }; + out.push(Instruction::new( + Op::Select, + Some(result_ty), + Some(result), + vec![ + Operand::IdRef(condition), + Operand::IdRef(arm_results[ordinal]), + Operand::IdRef(selected), + ], + )); + selected = result; + } + replacements.insert(use_site.site, out); + } + } + } + + for (function, func) in module.functions.iter_mut().enumerate() { + for (block, blk) in func.blocks.iter_mut().enumerate() { + let old = std::mem::take(&mut blk.instructions); + let mut rebuilt = Vec::with_capacity(old.len()); + for (instruction, inst) in old.into_iter().enumerate() { + let site = Site { + function, + block, + instruction, + }; + if let Some(replacement) = replacements.remove(&site) { + rebuilt.extend(replacement); + } else { + rebuilt.push(inst); + } + } + blk.instructions = rebuilt; + } + } + let targets_removed = |inst: &Instruction| matches!(inst.operands.first(), Some(Operand::IdRef(id)) if removed_ids.contains(id)); + module.debug_names.retain(|inst| !targets_removed(inst)); + module.annotations.retain(|inst| !targets_removed(inst)); + if let Some(header) = module.header.as_mut() { + header.bound = next_id; + } + true +} + +fn block_dominator_indices(function: &crate::spirv_module::Function) -> Vec> { + let labels = function + .blocks + .iter() + .map(|block| block.label.as_ref().and_then(|label| label.result_id)) + .collect::>(); + let by_label = labels + .iter() + .enumerate() + .filter_map(|(index, label)| label.map(|label| (label, index))) + .collect::>(); + let mut predecessors = vec![Vec::new(); function.blocks.len()]; + for (index, block) in function.blocks.iter().enumerate() { + let Some(terminator) = block.instructions.last() else { + continue; + }; + let successors = match terminator.class.opcode { + Op::Branch => terminator.operands.first().into_iter().collect::>(), + Op::BranchConditional => terminator + .operands + .get(1..3) + .unwrap_or_default() + .iter() + .collect(), + Op::Switch => terminator + .operands + .iter() + .skip(1) + .enumerate() + .filter_map(|(operand, value)| operand.is_multiple_of(2).then_some(value)) + .collect(), + _ => Vec::new(), + }; + for successor in successors { + if let Operand::IdRef(label) = successor { + if let Some(&target) = by_label.get(label) { + predecessors[target].push(index); + } + } + } + } + let all = (0..function.blocks.len()).collect::>(); + let mut dominators = vec![all; function.blocks.len()]; + if dominators.is_empty() { + return dominators; + } + dominators[0] = HashSet::from([0]); + loop { + let mut changed = false; + for block in 1..function.blocks.len() { + if predecessors[block].is_empty() { + continue; + } + let mut next = dominators[predecessors[block][0]].clone(); + for predecessor in predecessors[block].iter().skip(1) { + next.retain(|candidate| dominators[*predecessor].contains(candidate)); + } + next.insert(block); + if dominators[block] != next { + dominators[block] = next; + changed = true; + } + } + if !changed { + return dominators; + } + } +} + #[allow(clippy::too_many_arguments)] fn plan_tree( module: &Module, diff --git a/src/native/phi_index.rs b/src/native/phi_index.rs index 0079d17b8..5abf9d5af 100644 --- a/src/native/phi_index.rs +++ b/src/native/phi_index.rs @@ -212,6 +212,13 @@ pub(super) fn rewrite_integer_width_phis(module: &mut Module) -> bool { if let Some(header) = module.header.as_mut() { header.bound = next_id; } + // A pointer induction can start from a narrow zero index while its derived back-edge + // address has already been widened to the platform index width. Phi-the-index preserves + // those operands, so legalize the synthesized integer phi before the caller validates the + // portability candidate. Without this, the otherwise-useful pointer-phi rewrite is + // discarded and SPIRV-Cross later tries to materialize a StorageBuffer pointer phi as an + // invalid MSL pointer-from-lvalue initialization. + rewrite_integer_width_phis(module); } any } diff --git a/src/native/relooper.rs b/src/native/relooper.rs index 674c37273..f8cac1f5c 100644 --- a/src/native/relooper.rs +++ b/src/native/relooper.rs @@ -55,6 +55,7 @@ use std::collections::{HashMap, HashSet}; /// Rewrite every eligible multi-block function of `module` into relooper form. Returns true if any /// function was rewritten. pub(super) fn rewrite_to_relooper(module: &mut Module, max_blocks: usize) -> bool { + let max_blocks = effective_relooper_block_cap(max_blocks); // Snapshot the global type/const tables we read while choosing/creating types and constants. let mut next_id = module.header.as_ref().map(|h| h.bound).unwrap_or(1); let mut tc = TypeCtx::new(module, &mut next_id); @@ -295,12 +296,20 @@ fn block_label(block: &Block) -> Option { /// mostly emit-fail anyway (no module reaches the relooper) and would be pathological to lower. const MAX_RELOOPER_BLOCKS: usize = 1024; -/// The effective default block cap. Defaults to `MAX_RELOOPER_BLOCKS` but can be raised via -/// `METAL2VULKAN_RELOOPER_MAX_BLOCKS` for experiments. The prune-then-relooper retry passes its own (higher) -/// cap explicitly. Behaviour is adopt-if-validates regardless, so a raised cap can only add wins, -/// never regress the floor. +/// Hard product safety ceiling for the whole-function switch/state-machine relooper. Above this +/// size, valid output has thousands of Function variables and memory operations feeding one giant +/// switch; real drivers have been observed compiling it for tens of minutes or crashing. Returning +/// FALLBACK is safer than emitting a module that can wedge a consumer's pipeline compiler. +const MAX_DRIVER_SAFE_RELOOPER_BLOCKS: usize = MAX_RELOOPER_BLOCKS; + +fn effective_relooper_block_cap(requested: usize) -> usize { + requested.min(MAX_DRIVER_SAFE_RELOOPER_BLOCKS) +} + +/// The effective default block cap. `METAL2VULKAN_RELOOPER_MAX_BLOCKS` may lower the cap for +/// diagnostics, but the hard driver-safety ceiling prevents raising it above the product default. pub(super) fn default_max_relooper_blocks() -> usize { - crate::env_vars::relooper_max_blocks(MAX_RELOOPER_BLOCKS) + effective_relooper_block_cap(crate::env_vars::relooper_max_blocks(MAX_RELOOPER_BLOCKS)) } fn rewrite_function(function: &mut Function, tc: &mut TypeCtx, max_blocks: usize) -> bool { @@ -1523,6 +1532,48 @@ mod tests { .collect() } + #[test] + fn whole_function_relooper_clamps_requested_cap_to_driver_safe_limit() { + assert_eq!( + effective_relooper_block_cap(8192), + MAX_DRIVER_SAFE_RELOOPER_BLOCKS + ); + assert_eq!( + effective_relooper_block_cap(MAX_RELOOPER_BLOCKS), + MAX_RELOOPER_BLOCKS + ); + } + + #[test] + fn whole_function_relooper_refuses_1025_block_state_machine() { + let mut spvasm = String::from( + r#"OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint Fragment %main "main" +OpExecutionMode %main OriginUpperLeft +%void = OpTypeVoid +%fn = OpTypeFunction %void +%main = OpFunction %void None %fn +"#, + ); + for index in 0..MAX_DRIVER_SAFE_RELOOPER_BLOCKS + 1 { + spvasm.push_str(&format!("%b{index} = OpLabel\n")); + if index == MAX_DRIVER_SAFE_RELOOPER_BLOCKS { + spvasm.push_str("OpReturn\n"); + } else { + spvasm.push_str(&format!("OpBranch %b{}\n", index + 1)); + } + } + spvasm.push_str("OpFunctionEnd\n"); + + let Some(spv) = assemble(&spvasm) else { + return; + }; + let mut module = crate::spirv_module::load_bytes(&spv).expect("load"); + + assert!(!rewrite_to_relooper(&mut module, 8192)); + } + fn block_id(block: &Block) -> Word { block .label diff --git a/src/native/rewrites.rs b/src/native/rewrites.rs index 285abf6b8..790d37678 100644 --- a/src/native/rewrites.rs +++ b/src/native/rewrites.rs @@ -711,6 +711,9 @@ pub(crate) fn rewrite_variable_pointer_phis_module(module: &mut Module) -> Resul } add_native_module_capabilities(module); crate::passes::lower_scalar_i64_arithmetic_module(module); + // The i64 lowering can widen a synthesized index-phi backedge after phi-the-index has already + // normalized it. Re-run the narrow-incoming legalization on that final shape before validation. + phi_index::rewrite_integer_width_phis(module); add_native_module_capabilities(module); Ok(()) } @@ -808,23 +811,17 @@ pub(crate) fn rewrite_to_relooper_module(module: &mut Module) -> Result<(), Stri rewrite_to_relooper_module_capped(module, relooper::default_max_relooper_blocks()) } -/// Higher block budget for the function-constant-dead prune → relooper composition. Pruning can -/// shrink an otherwise oversized function below this ceiling while it remains above the normal -/// relooper budget. -pub const PRUNE_THEN_RELOOPER_MAX_BLOCKS: usize = 2048; +/// Product-safe block budget for the function-constant-dead prune → relooper composition. Pruning +/// may shrink an oversized function below this ceiling; it never licenses a larger state machine. +pub const PRUNE_THEN_RELOOPER_MAX_BLOCKS: usize = 1024; -/// Bounded high cap for the relooper retry over an unrepaired CFG that the structurizer emitted as a -/// REJECT (complete but spirv-val-invalid bytes). The normal relooper stays capped at 1024 blocks; -/// this retry-only cap is sufficient for the complete graph a reject function emits, while remaining -/// below the 8192 diagnostic ceiling for the separately measured huge emitted-module path. -pub const CFG_EMIT_RELOOPER_MAX_BLOCKS: usize = 2048; +/// Higher retry budget for an unrepaired CFG that the structurizer emitted as a REJECT. The normal +/// relooper stays capped at 1024 blocks; the whole-function relooper independently clamps every +/// caller to its hard downstream-driver safety ceiling. +pub const CFG_EMIT_RELOOPER_MAX_BLOCKS: usize = 1024; -/// Like [`rewrite_to_relooper_module`] but with an explicit block cap. The prune-then-relooper -/// retry uses a higher cap than the default 1024: its input is a function whose statically-dead -/// function-constant arms were already pruned away (byte-correct DCE), so a >1024-block source can -/// land below the cap after pruning yet still exceed the default. Lifting the cap only for that -/// already-failing, adopt-if-validates path keeps the normal relooper's perf budget intact while -/// admitting the pruned huge-function cfg cases. +/// Like [`rewrite_to_relooper_module`] but with an explicit requested block cap. The native +/// whole-function relooper always clamps that request to its hard downstream-driver safety limit. pub(crate) fn rewrite_to_relooper_module_capped( module: &mut Module, max_blocks: usize, diff --git a/src/native/tests/buffers.rs b/src/native/tests/buffers.rs index 445033aae..e4e6dc3c7 100644 --- a/src/native/tests/buffers.rs +++ b/src/native/tests/buffers.rs @@ -1864,6 +1864,58 @@ entry: } } +#[test] +fn native_inline_raw_buffer_gep_argument_keeps_descriptor_root_and_offset() { + let ll = r#" +target triple = "air64-apple-macosx14.0.0" + +define void @k(ptr addrspace(1) %out) { +entry: + %shifted = getelementptr inbounds i32, ptr addrspace(1) %out, i64 4 + tail call fastcc void @helper(ptr addrspace(1) %shifted) + ret void +} + +define internal fastcc void @helper(ptr addrspace(1) %dst) { +entry: + store i32 7, ptr addrspace(1) %dst, align 4 + ret void +} + +!air.kernel = !{!0} +!0 = !{ptr @k, !1, !2} +!1 = !{} +!2 = !{!3} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +"#; + let tmp = std::env::temp_dir().join(format!( + "metal2vulkan_inline_raw_buffer_gep_arg_{}", + std::process::id() + )); + let _ = std::fs::create_dir_all(&tmp); + let spv = crate::translate_sanitized_native(ll, Stage::Kernel, &tmp).expect("translate"); + let asm = disassemble(&spv).expect("disassemble"); + assert_eq!(asm.matches("Binding 0").count(), 1, "{asm}"); + assert!( + !asm.lines() + .any(|line| line.contains("OpVariable %_ptr_Private_uint Private")), + "offset helper store must remain descriptor-backed:\n{asm}" + ); + assert!( + asm.lines() + .any(|line| line.contains("OpInBoundsAccessChain")), + "descriptor-backed helper store must preserve the four-word offset:\n{asm}" + ); + if std::process::Command::new("spirv-val") + .arg("--version") + .output() + .is_ok() + { + tools::spirv_val_bytes(&spv, &tmp).expect("spirv-val"); + } + let _ = std::fs::remove_dir_all(&tmp); +} + #[test] fn native_indirect_helper_gep_drops_signed_zero_record_index() { let ll = r#" diff --git a/src/native/tests/textures.rs b/src/native/tests/textures.rs index 5a440da29..a3dfefb46 100644 --- a/src/native/tests/textures.rs +++ b/src/native/tests/textures.rs @@ -239,10 +239,9 @@ attributes #3 = { convergent nounwind memory(argmem: write) } #[test] fn native_get_null_texture_models_unmodeled_placeholder() { - // `air.get_null_texture_2d()` yields a NULL texture handle that the MPS NDArray kernels store - // into a vestigial struct field but never sample. The native emitter previously bailed - // (`missing pointer storage`) because the result pointer had no storage class. It is now modeled - // as an unmodeled placeholder pointer, so the store validates; the kernel emits a valid module. + // `air.get_null_texture_2d()` yields a synthesized image in the texture descriptor band. Even a + // kernel that only stores the opaque handle must remain valid, and the translator-owned resource + // must not escape into sampler/color-input bindings. let ll = r#" define void @k(ptr addrspace(1) %out) { entry: @@ -261,18 +260,24 @@ declare ptr addrspace(1) @air.get_null_texture_2d() !2 = !{!3} !3 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} "#; - let spv = emit_vulkan_spirv(ll).expect("null-texture kernel must emit a module"); + let tmp = std::env::temp_dir().join(format!( + "metal2vulkan_null_texture_store_{}", + std::process::id() + )); + let _ = std::fs::create_dir_all(&tmp); + let spv = crate::translate_sanitized_native(ll, Stage::Kernel, &tmp) + .expect("null-texture kernel must translate"); let asm = disassemble(&spv).expect("disassemble"); assert!(asm.contains("OpFunction"), "{asm}"); + assert!(asm.contains("Binding 32"), "{asm}"); + let _ = std::fs::remove_dir_all(tmp); } #[test] fn native_is_null_texture_of_get_null_texture_lowers_to_true() { // `air.is_null_texture(%t)` where `%t` came from `air.get_null_texture_2d()` must lower to a - // constant TRUE. The get_null_texture handle never crosses the emitter->reparse seam as a - // recognizable image, so the passes-layer null tracking can't see it; the emitter therefore - // consumes is_null_texture directly, keyed on the value it itself synthesized. Branching on the - // result keeps it live (a realistic "is this texture bound?" use) and forces it into the module. + // constant TRUE. Branching on the result keeps it live (a realistic "is this texture bound?" + // use) and forces the null-image tracking through the lowering pipeline. let ll = r#" define void @k(ptr addrspace(1) %out) { entry: @@ -298,13 +303,20 @@ declare i1 @air.is_null_texture_2d(ptr addrspace(1)) !2 = !{!3} !3 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 4, !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} "#; - let spv = emit_vulkan_spirv(ll).expect("is-null-texture kernel must emit a module"); + let tmp = std::env::temp_dir().join(format!( + "metal2vulkan_null_texture_predicate_{}", + std::process::id() + )); + let _ = std::fs::create_dir_all(&tmp); + let spv = crate::translate_sanitized_native(ll, Stage::Kernel, &tmp) + .expect("is-null-texture kernel must translate"); let asm = disassemble(&spv).expect("disassemble"); // The predicate is the constant TRUE, not FALSE: a synthesized null texture IS null. assert!( asm.contains("OpConstantTrue"), "is_null_texture(get_null_texture()) must lower to constant TRUE; got:\n{asm}" ); + let _ = std::fs::remove_dir_all(tmp); } #[test] diff --git a/src/passes/air_calls/dispatch_texture.rs b/src/passes/air_calls/dispatch_texture.rs index d17c608aa..dc9868147 100644 --- a/src/passes/air_calls/dispatch_texture.rs +++ b/src/passes/air_calls/dispatch_texture.rs @@ -912,7 +912,7 @@ pub(in crate::passes) fn lower_get_null_texture( } else { (Dim::Dim2D, false) }; - let var = ctx.default_null_image_of(dim, arrayed); + let var = ctx.default_null_image_of(dim, arrayed)?; let img_ty = ctx.ty_image(dim, arrayed, crate::passes::ImageComp::Float); ctx.image_dims.insert(res, (dim, arrayed)); ctx.image_comp.insert(res, crate::passes::ImageComp::Float); diff --git a/src/passes/air_calls/images/sample.rs b/src/passes/air_calls/images/sample.rs index a9fe1e782..67663f2c2 100644 --- a/src/passes/air_calls/images/sample.rs +++ b/src/passes/air_calls/images/sample.rs @@ -57,10 +57,13 @@ pub(in crate::passes) fn lower_sample( let pixel_linear = comp == crate::passes::ImageComp::Float && sampler_state.uses_linear_filter() && matches!(dim, Dim::Dim2D | Dim::Dim3D); + let pixel_bicubic = comp == crate::passes::ImageComp::Float + && sampler_state.uses_bicubic_filter() + && dim == Dim::Dim2D; let pixel_fetch = comp != crate::passes::ImageComp::Float || sampler_state.uses_pixel_nearest() || arrayed; - if pixel_linear || pixel_fetch { + if pixel_linear || pixel_bicubic || pixel_fetch { let lod = match find_sample_lod(ctx, arrayed, args, &mut out) { Some(lod) => sample_lod_to_fetch_lod(ctx, lod, &mut out)?, None => ctx.const_uint(0), @@ -80,6 +83,20 @@ pub(in crate::passes) fn lower_sample( )?; return finish_sample_result(ctx, res, rty, color, sample_v4, out); } + if pixel_bicubic { + let color = lower_pixel_bicubic_sample( + ctx, + sampler_state, + img, + arrayed, + coord, + args, + lod, + sample_v4, + &mut out, + )?; + return finish_sample_result(ctx, res, rty, color, sample_v4, out); + } let fetch = build_pixel_fetch_coord( ctx, sampler_state, @@ -111,6 +128,16 @@ pub(in crate::passes) fn lower_sample( return finish_sample_result(ctx, res, rty, color, sample_v4, out); } } + if ctx + .sampler_states + .get(&samp) + .is_some_and(|state| state.uses_bicubic_filter()) + { + return Err( + "air.sample_texture bicubic filtering is supported only for pixel-coordinate 2D float textures" + .into(), + ); + } if is_int_tex { if let Some(sampler_state) = ctx.sampler_states.get(&samp).copied() { if sample_uses_normalized_coords(ctx, arrayed, args) { @@ -217,6 +244,246 @@ pub(in crate::passes) fn lower_sample( finish_sample_result(ctx, res, rty, color, sample_v4, out) } +#[allow(clippy::too_many_arguments)] +fn lower_pixel_bicubic_sample( + ctx: &mut Ctx, + sampler_state: StaticSamplerState, + img: Word, + arrayed: bool, + coord: Word, + args: &[Word], + lod: Word, + sample_v4: Word, + out: &mut Vec, +) -> Result { + let (offset, dynamic_offset) = sample_const_or_dynamic_offset(ctx, arrayed, args, 2)?; + let dynamic_offset = dynamic_offset + .map(|offset| dynamic_i32_integer_offset_components(ctx, offset, 2, out)) + .transpose()?; + let layer = if arrayed { + Some( + args.get(3) + .copied() + .ok_or("air.sample_texture bicubic array texture missing layer")?, + ) + } else { + None + }; + let size = query_image_size(ctx, img, 2, arrayed, lod, out); + let float_ty = ctx.ty_float(); + let sint = ctx.ty_sint(); + let bool_ty = ctx.ty_bool(); + let glsl = ctx.glsl(); + let zero_f = ctx.const_float(0.0); + let half_f = ctx.const_float(0.5); + let mut base = Vec::with_capacity(2); + let mut axis_weights = Vec::with_capacity(2); + for (axis, component) in sample_coord_components(ctx, coord, 2, out)? + .into_iter() + .enumerate() + { + let Operand::IdRef(component) = component else { + return Err("air.sample_texture bicubic coord component is not an id".into()); + }; + let component = + clamp_pixel_coord_component_finite(ctx, component, size, true, axis as u32, out); + let biased = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::FSub, + Some(float_ty), + Some(biased), + vec![Operand::IdRef(component), Operand::IdRef(half_f)], + )); + let floor = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::ExtInst, + Some(float_ty), + Some(floor), + vec![ + Operand::IdRef(glsl), + Operand::LiteralExtInstInteger(8), + Operand::IdRef(biased), + ], + )); + let mut base_i = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::ConvertFToS, + Some(sint), + Some(base_i), + vec![Operand::IdRef(floor)], + )); + if let Some(offset) = &offset { + if offset[axis] != 0 { + let shifted = ctx.module.fresh_id(); + let delta = ctx.const_int_of(sint, offset[axis] as i64); + out.push(Instruction::new( + Op::IAdd, + Some(sint), + Some(shifted), + vec![Operand::IdRef(base_i), Operand::IdRef(delta)], + )); + base_i = shifted; + } + } else if let Some(offset) = &dynamic_offset { + let shifted = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::IAdd, + Some(sint), + Some(shifted), + vec![Operand::IdRef(base_i), Operand::IdRef(offset[axis])], + )); + base_i = shifted; + } + let frac = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::FSub, + Some(float_ty), + Some(frac), + vec![Operand::IdRef(biased), Operand::IdRef(floor)], + )); + base.push(base_i); + axis_weights.push(catmull_rom_weights(ctx, frac, out)); + } + + let zero_color = const_null_of(ctx, sample_v4); + let mut acc = zero_color; + for tap_y in 0..4 { + for tap_x in 0..4 { + let tap_coord = pixel_linear_tap_coord( + ctx, + sampler_state, + Dim::Dim2D, + arrayed, + &base, + &[tap_x - 1, tap_y - 1], + layer, + size, + out, + )?; + let fetched = ctx.module.fresh_id(); + push_image_read_or_fetch( + ctx, + out, + img, + tap_coord.coord, + Some(lod), + sample_v4, + fetched, + ); + let color = if let Some(in_bounds) = tap_coord.in_bounds { + let guarded = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::Select, + Some(sample_v4), + Some(guarded), + vec![ + Operand::IdRef(in_bounds), + Operand::IdRef(fetched), + Operand::IdRef(zero_color), + ], + )); + guarded + } else { + fetched + }; + let weight = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::FMul, + Some(float_ty), + Some(weight), + vec![ + Operand::IdRef(axis_weights[0][tap_x as usize]), + Operand::IdRef(axis_weights[1][tap_y as usize]), + ], + )); + let weighted = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::VectorTimesScalar, + Some(sample_v4), + Some(weighted), + vec![Operand::IdRef(color), Operand::IdRef(weight)], + )); + let weight_is_zero = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::FOrdEqual, + Some(bool_ty), + Some(weight_is_zero), + vec![Operand::IdRef(weight), Operand::IdRef(zero_f)], + )); + let contribution = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::Select, + Some(sample_v4), + Some(contribution), + vec![ + Operand::IdRef(weight_is_zero), + Operand::IdRef(zero_color), + Operand::IdRef(weighted), + ], + )); + let sum = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::FAdd, + Some(sample_v4), + Some(sum), + vec![Operand::IdRef(acc), Operand::IdRef(contribution)], + )); + acc = sum; + } + } + Ok(acc) +} + +fn catmull_rom_weights(ctx: &mut Ctx, t: Word, out: &mut Vec) -> [Word; 4] { + let float_ty = ctx.ty_float(); + let c_half = ctx.const_float(0.5); + let c_neg_half = ctx.const_float(-0.5); + let c_one = ctx.const_float(1.0); + let c_one_half = ctx.const_float(1.5); + let c_two = ctx.const_float(2.0); + let c_two_half = ctx.const_float(2.5); + let mul = |ctx: &mut Ctx, a, b, out: &mut Vec| { + let id = ctx.module.fresh_id(); + out.push(Instruction::new( + Op::FMul, + Some(float_ty), + Some(id), + vec![Operand::IdRef(a), Operand::IdRef(b)], + )); + id + }; + let add = |ctx: &mut Ctx, op, a, b, out: &mut Vec| { + let id = ctx.module.fresh_id(); + out.push(Instruction::new( + op, + Some(float_ty), + Some(id), + vec![Operand::IdRef(a), Operand::IdRef(b)], + )); + id + }; + let t2 = mul(ctx, t, t, out); + let t3 = mul(ctx, t2, t, out); + let w0a = mul(ctx, c_neg_half, t, out); + let w0b = mul(ctx, c_one, t2, out); + let w0c = mul(ctx, c_neg_half, t3, out); + let w0ab = add(ctx, Op::FAdd, w0a, w0b, out); + let w0 = add(ctx, Op::FAdd, w0ab, w0c, out); + let w1a = mul(ctx, c_two_half, t2, out); + let w1b = mul(ctx, c_one_half, t3, out); + let w1a = add(ctx, Op::FSub, c_one, w1a, out); + let w1 = add(ctx, Op::FAdd, w1a, w1b, out); + let w2a = mul(ctx, c_half, t, out); + let w2b = mul(ctx, c_two, t2, out); + let w2c = mul(ctx, c_one_half, t3, out); + let w2ab = add(ctx, Op::FAdd, w2a, w2b, out); + let w2 = add(ctx, Op::FSub, w2ab, w2c, out); + let w3a = mul(ctx, c_neg_half, t2, out); + let w3b = mul(ctx, c_half, t3, out); + let w3 = add(ctx, Op::FAdd, w3a, w3b, out); + [w0, w1, w2, w3] +} + /// Clamp a float pixel-space sample coordinate component to the finite range `[-9.0, size + 9.0]` /// before it is floored / converted to an integer texel index. For finite coordinates this /// preserves sampling behavior: sample offsets are bounded to [-8, 7] texels by the AIR contract, diff --git a/src/passes/resources/bindings.rs b/src/passes/resources/bindings.rs index 109a53b41..bd03ee2c4 100644 --- a/src/passes/resources/bindings.rs +++ b/src/passes/resources/bindings.rs @@ -73,6 +73,24 @@ pub(in crate::passes) fn allocate_static_sampler_binding(module: &Module) -> Opt (SAMPLER_BINDING_BASE..COLOR_INPUT_BINDING_BASE).find(|binding| !occupied.contains(binding)) } +/// Allocate one translator-owned null-image descriptor inside the texture ABI band. It must never +/// use a sampler/color-input binding merely because those bands contain the global high-water mark. +pub(in crate::passes) fn allocate_default_texture_binding(module: &Module) -> Option { + let occupied = module + .annotations + .iter() + .filter(|instruction| { + instruction.class.opcode == Op::Decorate + && instruction.operands.get(1) == Some(&Operand::Decoration(Decoration::Binding)) + }) + .filter_map(|instruction| match instruction.operands.get(2) { + Some(Operand::LiteralBit32(binding)) => Some(*binding), + _ => None, + }) + .collect::>(); + (TEXTURE_BINDING_BASE..SAMPLER_BINDING_BASE).find(|binding| !occupied.contains(binding)) +} + pub(in crate::passes) fn texture_resource_binding(binding: u32) -> u32 { TEXTURE_BINDING_BASE.saturating_add(binding) } diff --git a/src/passes/stage_input/layout.rs b/src/passes/stage_input/layout.rs index 6a86c9dfe..097fdb6d2 100644 --- a/src/passes/stage_input/layout.rs +++ b/src/passes/stage_input/layout.rs @@ -70,24 +70,19 @@ impl Ctx { /// Lazily create a default (null) 2D float texture resource for `air.get_null_texture_2d()`. /// Metal's `[[function_constant]]`-gated optional attachments resolve (with our FCs folded off) to /// a "null texture" the shader still threads through phis and may sample (yielding 0). We bind one - /// real `OpTypeImage` 2D-float UniformConstant variable (past every assigned binding) and load it; + /// real `OpTypeImage` 2D-float UniformConstant variable in a free texture-ABI binding and load it; /// sampling it is valid (reads as the unbound-descriptor default). Memoized across all uses so the /// phi-merged values share one image id and type. - pub(in crate::passes) fn default_null_image_of(&mut self, dim: Dim, arrayed: bool) -> Word { + pub(in crate::passes) fn default_null_image_of( + &mut self, + dim: Dim, + arrayed: bool, + ) -> Result { if let Some(&v) = self.default_null_image_vars.get(&(dim, arrayed)) { - return v; + return Ok(v); } - let mut max_binding: i64 = -1; - for ann in &self.module.annotations { - if ann.class.opcode == Op::Decorate - && ann.operands.get(1) == Some(&Operand::Decoration(Decoration::Binding)) - { - if let Some(Operand::LiteralBit32(b)) = ann.operands.get(2) { - max_binding = max_binding.max(*b as i64); - } - } - } - let binding = (max_binding + 1) as u32; + let binding = allocate_default_texture_binding(&self.module) + .ok_or_else(|| "no free texture binding for synthesized null image".to_string())?; let img_ty = self.ty_image(dim, arrayed, ImageComp::Float); let pptr = self.ty_ptr(StorageClass::UniformConstant, img_ty); let var = self.module.fresh_id(); @@ -100,7 +95,7 @@ impl Ctx { decorate_binding(&mut self.module, var, binding); self.interface_buffer_var(var); self.default_null_image_vars.insert((dim, arrayed), var); - var + Ok(var) } /// A constant/undef of `ty` for unused params (OpUndef is always legal). diff --git a/src/passthrough.rs b/src/passthrough.rs index 465f560a4..b70afba20 100644 --- a/src/passthrough.rs +++ b/src/passthrough.rs @@ -62,6 +62,7 @@ fn emit_float_value( prefix: &str, idx: usize, lanes: u32, + distinct_float3: bool, ) -> Result { match lanes { 1 => Ok("%float_0_25".to_string()), @@ -72,9 +73,12 @@ fn emit_float_value( } 3 => { let id = format!("%{prefix}{idx}"); - p.push(format!( - "{id} = OpCompositeConstruct %v3float %ux %uy %float_0_5" - )); + let z = if distinct_float3 && idx > 0 { + "%float_1" + } else { + "%float_0_5" + }; + p.push(format!("{id} = OpCompositeConstruct %v3float %ux %uy {z}")); Ok(id) } 4 => { @@ -108,7 +112,14 @@ fn emit_integer_value(p: &mut Vec, prefix: &str, idx: usize, ty: &PassTy id } -fn passthrough_vertex_spvasm(meta: &meta::FragMeta) -> Result { +fn passthrough_vertex_spvasm( + meta: &meta::FragMeta, + distinct_float3_inputs: bool, +) -> Result { + let has_viewport_index = meta + .roles + .iter() + .any(|(_, role)| matches!(role, meta::FragRole::ViewportArrayIndex)); let mut locs: Vec = meta .roles .iter() @@ -130,6 +141,9 @@ fn passthrough_vertex_spvasm(meta: &meta::FragMeta) -> Result { let mut out_types: BTreeSet = BTreeSet::new(); out_types.insert("v4float".to_string()); + if has_viewport_index { + out_types.insert("uint".to_string()); + } for (_, ty) in &varyings { out_types.insert(ty.spirv.clone()); } @@ -143,10 +157,16 @@ fn passthrough_vertex_spvasm(meta: &meta::FragMeta) -> Result { if has_int16 { p.push("OpCapability Int16".into()); } + if has_viewport_index { + p.push("OpCapability ShaderViewportIndex".into()); + } p.push("OpCapability Shader".into()); p.push("OpMemoryModel Logical GLSL450".into()); let mut iface = vec!["%glpos".to_string(), "%vidx".to_string()]; + if has_viewport_index { + iface.push("%viewport".to_string()); + } for i in 0..varyings.len() { iface.push(format!("%vout{i}")); } @@ -156,6 +176,9 @@ fn passthrough_vertex_spvasm(meta: &meta::FragMeta) -> Result { )); p.push("OpDecorate %glpos BuiltIn Position".into()); p.push("OpDecorate %vidx BuiltIn VertexIndex".into()); + if has_viewport_index { + p.push("OpDecorate %viewport BuiltIn ViewportIndex".into()); + } for (i, (loc, ty)) in varyings.iter().enumerate() { p.push(format!("OpDecorate %vout{i} Location {loc}")); if ty.needs_flat() || meta.varying_is_flat(*loc) { @@ -211,6 +234,7 @@ fn passthrough_vertex_spvasm(meta: &meta::FragMeta) -> Result { p.push("%int_2 = OpConstant %int 2".into()); p.push("%int_3 = OpConstant %int 3".into()); p.push("%int_4 = OpConstant %int 4".into()); + p.push("%uint_0 = OpConstant %uint 0".into()); p.push("%uint_1 = OpConstant %uint 1".into()); p.push("%uint_2 = OpConstant %uint 2".into()); p.push("%uint_3 = OpConstant %uint 3".into()); @@ -227,6 +251,9 @@ fn passthrough_vertex_spvasm(meta: &meta::FragMeta) -> Result { } p.push("%glpos = OpVariable %_ptr_Output_v4float Output".into()); p.push("%vidx = OpVariable %_ptr_Input_int Input".into()); + if has_viewport_index { + p.push("%viewport = OpVariable %_ptr_Output_uint Output".into()); + } for (i, (_, ty)) in varyings.iter().enumerate() { p.push(format!( "%vout{i} = OpVariable %_ptr_Output_{} Output", @@ -250,14 +277,17 @@ fn passthrough_vertex_spvasm(meta: &meta::FragMeta) -> Result { p.push("%py = OpFSub %float %float_1 %py0".into()); p.push("%pos = OpCompositeConstruct %v4float %px %py %float_0 %float_1".into()); p.push("OpStore %glpos %pos".into()); + if has_viewport_index { + p.push("OpStore %viewport %uint_0".into()); + } p.push("%ux = OpFMul %float %axf %float_2".into()); p.push("%uy = OpFMul %float %ayf %float_2".into()); for (i, (_, ty)) in varyings.iter().enumerate() { let val = match ty.base { - "float" => emit_float_value(&mut p, "uvf", i, ty.lanes)?, + "float" => emit_float_value(&mut p, "uvf", i, ty.lanes, distinct_float3_inputs)?, "half" => { - let fval = emit_float_value(&mut p, "uvf", i, ty.lanes)?; + let fval = emit_float_value(&mut p, "uvf", i, ty.lanes, distinct_float3_inputs)?; let hval = format!("%uvh{i}"); p.push(format!("{hval} = OpFConvert %{} {fval}", ty.spirv)); hval @@ -306,10 +336,24 @@ pub fn translate_passthrough(src: &str, tmp: &Path) -> Result, String> { let san_ll = passthrough_sanitized_ll(src, tmp)?; let frag = meta::parse_air_fragment_meta(&san_ll) .ok_or_else(|| "passthrough: source has no !air.fragment metadata".to_string())?; - let asm = passthrough_vertex_spvasm(&frag)?; + let asm = passthrough_vertex_spvasm(&frag, fragment_requires_distinct_float3_inputs(&san_ll))?; assemble_spvasm(&asm, tmp, "passthrough") } +fn fragment_requires_distinct_float3_inputs(ll: &str) -> bool { + ll.lines() + .filter(|line| { + line.contains(r#""air.fragment_input""#) + && line.contains("!\"air.arg_type_name\", !\"float3\"") + }) + .count() + >= 2 + && ll.contains("@air.fast_rsqrt.f32") + && ll + .lines() + .any(|line| line.trim_start().contains(" = fsub ") && line.contains("<3 x float>")) +} + #[cfg(test)] mod tests { use super::*; @@ -320,7 +364,7 @@ mod tests { frag.roles.push((1, meta::FragRole::Varying(0))); frag.varying_types.insert(0, "float2".to_string()); - let asm = passthrough_vertex_spvasm(&frag).unwrap(); + let asm = passthrough_vertex_spvasm(&frag, false).unwrap(); assert!(asm.contains("%px = OpFSub %float %px0 %float_1")); assert!(asm.contains("%py = OpFSub %float %float_1 %py0")); } @@ -331,11 +375,36 @@ mod tests { frag.roles.push((1, meta::FragRole::Varying(0))); frag.varying_types.insert(0, "float4".to_string()); - let asm = passthrough_vertex_spvasm(&frag).unwrap(); + let asm = passthrough_vertex_spvasm(&frag, false).unwrap(); assert!(asm.contains("%float_0_5 = OpConstant %float 0.5")); assert!(asm.contains("%uvf0 = OpCompositeConstruct %v4float %ux %uy %float_0_5 %float_1")); } + #[test] + fn passthrough_vertex_separates_duplicate_float3_rsqrt_inputs() { + let ll = r#" +define <4 x half> @frag(<3 x float> %a, <3 x float> %b) { + %delta = fsub fast <3 x float> %a, %b + %len2 = tail call fast float @air.dot.v3f32(<3 x float> %delta, <3 x float> %delta) + %inv = tail call fast float @air.fast_rsqrt.f32(float %len2) + ret <4 x half> zeroinitializer +} +declare float @air.fast_rsqrt.f32(float) +!1 = !{i32 0, !"air.fragment_input", !"generated(a)", !"air.arg_type_name", !"float3", !"air.arg_name", !"a"} +!2 = !{i32 1, !"air.fragment_input", !"generated(b)", !"air.arg_type_name", !"float3", !"air.arg_name", !"b"} +"#; + assert!(fragment_requires_distinct_float3_inputs(ll)); + + let mut frag = meta::FragMeta::default(); + frag.roles.push((0, meta::FragRole::Varying(0))); + frag.roles.push((1, meta::FragRole::Varying(1))); + frag.varying_types.insert(0, "float3".to_string()); + frag.varying_types.insert(1, "float3".to_string()); + let asm = passthrough_vertex_spvasm(&frag, true).unwrap(); + assert!(asm.contains("%uvf0 = OpCompositeConstruct %v3float %ux %uy %float_0_5")); + assert!(asm.contains("%uvf1 = OpCompositeConstruct %v3float %ux %uy %float_1")); + } + #[test] fn passthrough_vertex_preserves_air_flat_float_varying() { let mut frag = meta::FragMeta::default(); @@ -343,7 +412,7 @@ mod tests { frag.varying_types.insert(0, "float4".to_string()); frag.flat_varyings.insert(0); - let asm = passthrough_vertex_spvasm(&frag).unwrap(); + let asm = passthrough_vertex_spvasm(&frag, false).unwrap(); assert!(asm.contains("OpDecorate %vout0 Flat"), "{asm}"); } @@ -359,7 +428,7 @@ mod tests { frag.varying_types.insert(2, "short3".to_string()); frag.varying_types.insert(3, "ushort".to_string()); - let asm = passthrough_vertex_spvasm(&frag).unwrap(); + let asm = passthrough_vertex_spvasm(&frag, false).unwrap(); assert!(asm.contains("OpCapability Int16"), "{asm}"); assert!(asm.contains("%int = OpTypeInt 32 1")); assert!(asm.contains("%uint = OpTypeInt 32 0")); @@ -382,10 +451,28 @@ mod tests { frag.roles.push((1, meta::FragRole::Varying(0))); frag.varying_types.insert(0, "bool".to_string()); - let asm = passthrough_vertex_spvasm(&frag).unwrap(); + let asm = passthrough_vertex_spvasm(&frag, false).unwrap(); assert!(asm.contains("OpDecorate %vout0 Flat"), "{asm}"); assert!(asm.contains("%vout0 = OpVariable %_ptr_Output_uint Output")); assert!(asm.contains("OpStore %vout0 %uint_1")); assert!(!asm.contains("OpTypeBool"), "{asm}"); } + + #[test] + fn passthrough_vertex_defines_requested_viewport_index() { + let mut frag = meta::FragMeta::default(); + frag.roles.push((1, meta::FragRole::ViewportArrayIndex)); + + let asm = passthrough_vertex_spvasm(&frag, false).unwrap(); + assert!(asm.contains("OpCapability ShaderViewportIndex"), "{asm}"); + assert!( + asm.contains("OpDecorate %viewport BuiltIn ViewportIndex"), + "{asm}" + ); + assert!( + asm.contains("%viewport = OpVariable %_ptr_Output_uint Output"), + "{asm}" + ); + assert!(asm.contains("OpStore %viewport %uint_0"), "{asm}"); + } } diff --git a/src/primary_retry.rs b/src/primary_retry.rs index 2ac7328a0..c0dfe1235 100644 --- a/src/primary_retry.rs +++ b/src/primary_retry.rs @@ -53,7 +53,6 @@ pub(crate) fn primary_wide_raw_store_guard_cfg_chain_if_needed( retry.prune_then_relooper(spv), ) }) - .or_else(|| retry.census("val-cfg:relooper_huge", retry.relooper_retry_huge(spv))) .or_else(|| { retry.census( "val-cfg:relooper_then_value_select", @@ -492,10 +491,11 @@ pub(crate) fn primary_logical_pointer_inline_sroa_raw_if_needed( .then_some(primary) } -/// Move a stale opaque-image select into its pure explicit-LOD sampling consumers only after the raw -/// primary reports the broad `Other` select-type diagnostic. The post-emit pass requires an image-only -/// select tree and rejects every non-sampling opaque use, so it cannot turn a pointer repair into a -/// resource-policy guess. The result is retained only after independent spirv-val. +/// Move a stale opaque-image select/phi into its pure sampling/query consumers after the raw primary +/// reports either the broad `Other` select diagnostic or the exact pointer-result/image-incoming phi +/// mismatch. The post-emit pass requires a fully image-only merge and rejects every write, sparse, +/// opaque, or non-dominating use, so it cannot turn a pointer repair into a resource-policy guess. +/// The result is retained only after independent spirv-val. /// `finish_module` has already loaded, transformed, and canonicalized this module; clone that /// retained carrier for the speculative rewrite instead of reparsing its just-assembled bytes. pub(crate) fn primary_opaque_image_select_module_if_needed( @@ -504,7 +504,11 @@ pub(crate) fn primary_opaque_image_select_module_if_needed( spv: &[u8], tmp: &Path, ) -> Option> { - if native::classify_validation_error(validation_error) != native::ValidationClass::Other { + let class = native::classify_validation_error(validation_error); + let opaque_phi_mismatch = class == native::ValidationClass::PointerTyping + && validation_error.contains("OpPhi's result type") + && validation_error.contains("does not match incoming value"); + if class != native::ValidationClass::Other && !opaque_phi_mismatch { return None; } let mut primary_module = module.clone(); diff --git a/src/reflect/mod.rs b/src/reflect/mod.rs index 1692b773c..06007a006 100644 --- a/src/reflect/mod.rs +++ b/src/reflect/mod.rs @@ -14,8 +14,8 @@ //! data and never re-reads the emitted SPIR-V, so it is byte-neutral on the translator. use crate::meta::{ - texture_shape_from_name, AirType, FragMeta, FragRole, FunctionConstant, KernMeta, KernRole, - TextureComponent, TextureDimension, TextureShape, VertMeta, VertOutRole, VertRole, + texture_shape_from_name, AirType, BufferAccess, FragMeta, FragRole, FunctionConstant, KernMeta, + KernRole, TextureComponent, TextureDimension, TextureShape, VertMeta, VertOutRole, VertRole, }; /// Schema version of [`ShaderReflection`]. Bump on any breaking change to the serialized shape so a @@ -28,7 +28,10 @@ use crate::meta::{ /// the source `datalayout`; plus fragment/vertex buffer `address_space`/`declared_size` population. /// /// v3 reports AIR-embedded constexpr samplers as `StaticSampler` bindings with their decoded state. -pub const REFLECTION_VERSION: u32 = 3; +/// +/// v4 adds conservative buffer extent classes, all-stage buffer type names / declared sizes, and +/// declared buffer access (including write-only). +pub const REFLECTION_VERSION: u32 = 4; /// The single descriptor set every Metal-facing resource is bound in. The interface pass hardcodes /// `DescriptorSet 0` for every resource (buffers, textures, samplers, color inputs). @@ -118,9 +121,14 @@ pub struct DescriptorLocation { #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum ResourceAccess { + /// The specialized entry does not dereference this buffer. Its descriptor may still be bound, + /// but no buffer contents need to be staged for this shader invocation. + Unused, /// A buffer read but never written by the shader. ReadOnly, - /// A buffer written by the shader. + /// A buffer written but never read by the shader. + WriteOnly, + /// A buffer both read and written by the shader, or conservatively declared for both. ReadWrite, /// A sampled texture (`OpTypeImage Sampled=1`), read through a sampler. Sampled, @@ -128,6 +136,23 @@ pub enum ResourceAccess { Storage, } +/// Conservative byte-extent classification for a buffer binding. +/// +/// Consumers may narrow a staged buffer window only for [`BufferExtent::Object`]. `Unbounded` and +/// `Unknown` both require retaining the complete caller-provided window. Every classification is an +/// over-approximation: an uncertain pointer must never be reported as a bounded object, because an +/// understated extent silently corrupts shader reads. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum BufferExtent { + /// AIR declares a reference-like object whose reachable extent is exactly `bytes`. + Object { bytes: u32 }, + /// AIR declares a pointer/array element size but carries no array length. + Unbounded, + /// The metadata does not distinguish a bounded object from an unbounded pointer. + Unknown, +} + /// Minification or magnification filtering encoded in an AIR constexpr sampler. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -302,13 +327,19 @@ impl StaticSamplerState { } pub(crate) fn uses_pixel_nearest(self) -> bool { - self.uses_pixel_coordinates() && !self.uses_linear_filter() + self.uses_pixel_coordinates() + && self.min_filter == SamplerFilter::Nearest + && self.mag_filter == SamplerFilter::Nearest } pub(crate) fn uses_linear_filter(self) -> bool { self.min_filter == SamplerFilter::Linear && self.mag_filter == SamplerFilter::Linear } + pub(crate) fn uses_bicubic_filter(self) -> bool { + self.min_filter == SamplerFilter::Bicubic && self.mag_filter == SamplerFilter::Bicubic + } + pub(crate) fn uses_pixel_coordinates(self) -> bool { self.coordinates == SamplerCoordinates::Pixel } @@ -374,6 +405,9 @@ pub struct ResourceBinding { pub address_space: Option, /// For a buffer: the declared AIR argument byte size, when the metadata carries one. pub declared_size: Option, + /// For a buffer: whether AIR bounds the binding to one object or leaves its array extent open. + /// `None` for non-buffer resources. + pub extent: Option, /// For a buffer with `air.struct_type_info`: the reconstructed AIR aggregate layout. pub type_layout: Option, /// The AIR argument type name (`texture2d`, a struct name, `char`, …), when carried. @@ -519,11 +553,19 @@ impl ShaderReflection { param_index: Some(idx), address_space: meta.buffer_address_spaces.get(&idx).copied(), declared_size: meta.buffer_type_sizes.get(&idx).copied(), + extent: Some(buffer_extent( + meta.buffer_object_sizes.get(&idx).copied(), + meta.buffer_type_sizes.get(&idx).copied(), + meta.buffer_type_names.get(&idx), + )), type_layout: meta.buffer_layouts.get(&idx).cloned(), - type_name: None, + type_name: meta.buffer_type_names.get(&idx).cloned(), texture_shape: None, embedded_source: None, - access: None, + access: buffer_access( + meta.buffer_accesses.get(&idx).copied(), + meta.buffer_address_spaces.get(&idx).copied(), + ), static_sampler: None, }, FragRole::Texture(n) => texture_binding(*n, Some(idx), &meta.texture_type_names), @@ -535,6 +577,7 @@ impl ShaderReflection { param_index: Some(idx), address_space: None, declared_size: None, + extent: None, type_layout: None, type_name: None, texture_shape: None, @@ -615,11 +658,19 @@ impl ShaderReflection { param_index: Some(idx), address_space: meta.buffer_address_spaces.get(&idx).copied(), declared_size: meta.buffer_type_sizes.get(&idx).copied(), + extent: Some(buffer_extent( + meta.buffer_object_sizes.get(&idx).copied(), + meta.buffer_type_sizes.get(&idx).copied(), + meta.buffer_type_names.get(&idx), + )), type_layout: meta.buffer_layouts.get(&idx).cloned(), - type_name: None, + type_name: meta.buffer_type_names.get(&idx).cloned(), texture_shape: None, embedded_source: None, - access: None, + access: buffer_access( + meta.buffer_accesses.get(&idx).copied(), + meta.buffer_address_spaces.get(&idx).copied(), + ), static_sampler: None, }, VertRole::Texture(n) => texture_binding(*n, Some(idx), &meta.texture_type_names), @@ -700,11 +751,19 @@ impl ShaderReflection { param_index: Some(idx), address_space, declared_size: meta.buffer_type_sizes.get(&idx).copied(), + extent: Some(buffer_extent( + meta.buffer_object_sizes.get(&idx).copied(), + meta.buffer_type_sizes.get(&idx).copied(), + meta.buffer_type_names.get(&idx), + )), type_layout: meta.buffer_layouts.get(&idx).cloned(), type_name: meta.buffer_type_names.get(&idx).cloned(), texture_shape: None, embedded_source: None, - access: buffer_access_from_address_space(address_space), + access: buffer_access( + meta.buffer_accesses.get(&idx).copied(), + address_space, + ), static_sampler: None, } } @@ -717,6 +776,7 @@ impl ShaderReflection { param_index: Some(idx), address_space: None, declared_size: None, + extent: None, type_layout: None, type_name: None, texture_shape: None, @@ -739,6 +799,7 @@ impl ShaderReflection { param_index: None, address_space: None, declared_size: None, + extent: None, type_layout: None, type_name: None, texture_shape: Some(TextureShape { @@ -794,6 +855,46 @@ impl ShaderReflection { .find(|b| b.kind == kind && b.metal_index == metal_index) } + /// Tighten declared buffer access using LLVM parameter attributes on the translated entry. + /// `readonly` / `writeonly` apply transitively to calls made by the function and are therefore + /// stronger than AIR's sometimes-broad `air.read_write` metadata. A parameter absent from the + /// body is classified `Unused`; ambiguous uses retain the conservative declared classification. + pub(crate) fn refine_buffer_access_from_entry(&mut self, ll: &str) { + let Some(entry) = self.entry_point.as_deref() else { + return; + }; + let Some((args, body)) = llvm_entry_args_and_body(ll, entry) else { + return; + }; + for binding in &mut self.bindings { + if !matches!( + binding.kind, + ResourceKind::Buffer | ResourceKind::ThreadgroupBuffer + ) { + continue; + } + let Some(param_index) = binding + .param_index + .and_then(|idx| usize::try_from(idx).ok()) + else { + continue; + }; + let Some(arg) = args.get(param_index) else { + continue; + }; + let Some(name) = percent_tokens(arg).last().copied() else { + continue; + }; + if !ssa_token_occurs(body, name) || llvm_arg_has_attribute(arg, "readnone") { + binding.access = Some(ResourceAccess::Unused); + } else if llvm_arg_has_attribute(arg, "readonly") { + binding.access = Some(ResourceAccess::ReadOnly); + } else if llvm_arg_has_attribute(arg, "writeonly") { + binding.access = Some(ResourceAccess::WriteOnly); + } + } + } + pub(crate) fn add_static_samplers(&mut self, ll: &str) -> Result<(), String> { let constants = parse_static_sampler_constants(ll)?; if constants.is_empty() { @@ -824,6 +925,7 @@ impl ShaderReflection { param_index: None, address_space: None, declared_size: None, + extent: None, type_layout: None, type_name: None, texture_shape: None, @@ -836,6 +938,91 @@ impl ShaderReflection { } } +fn llvm_entry_args_and_body<'a>(ll: &'a str, entry: &str) -> Option<(Vec<&'a str>, &'a str)> { + let plain = format!("@{entry}("); + let quoted = format!("@\"{entry}\"("); + let start = ll.lines().position(|line| { + line.trim_start().starts_with("define ") + && (line.contains(&plain) || line.contains("ed)) + })?; + let byte_start = ll + .lines() + .take(start) + .map(|line| line.len() + 1) + .sum::(); + let function = &ll[byte_start..]; + // Search from the entry symbol, rather than taking the first `{` / `(` in the header: an LLVM + // function may return an aggregate such as `<{ i32, i32 }>`, and those delimiters precede its + // parameter list. + let symbol = function.find(&plain).or_else(|| function.find("ed))?; + let open = function[symbol..].find('(')? + symbol; + let mut depth = 0u32; + let mut close = None; + for (offset, character) in function[open..].char_indices() { + match character { + '(' => depth += 1, + ')' => { + depth = depth.checked_sub(1)?; + if depth == 0 { + close = Some(open + offset); + break; + } + } + _ => {} + } + } + let close = close?; + let header_end = function[close + 1..].find('{')? + close + 1; + let args = split_top_level_llvm(&function[open + 1..close]); + let tail = &function[header_end + 1..]; + let body_end = tail.find("\n}").unwrap_or(tail.len()); + Some((args, &tail[..body_end])) +} + +fn split_top_level_llvm(text: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut start = 0usize; + let mut depth = 0i32; + for (index, character) in text.char_indices() { + match character { + '(' | '[' | '{' | '<' => depth += 1, + ')' | ']' | '}' | '>' => depth -= 1, + ',' if depth == 0 => { + out.push(text[start..index].trim()); + start = index + 1; + } + _ => {} + } + } + if !text[start..].trim().is_empty() { + out.push(text[start..].trim()); + } + out +} + +fn percent_tokens(text: &str) -> Vec<&str> { + text.split('%') + .skip(1) + .filter_map(|tail| { + let token = tail + .split(|character: char| { + !(character.is_ascii_alphanumeric() || character == '_' || character == '.') + }) + .next()?; + (!token.is_empty()).then_some(token) + }) + .collect() +} + +fn ssa_token_occurs(text: &str, name: &str) -> bool { + percent_tokens(text).contains(&name) +} + +fn llvm_arg_has_attribute(arg: &str, attribute: &str) -> bool { + arg.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) + .any(|token| token == attribute) +} + fn parse_static_sampler_constants(ll: &str) -> Result, String> { let mut globals = std::collections::HashMap::::new(); let mut nodes = std::collections::HashMap::::new(); @@ -947,6 +1134,7 @@ fn texture_binding( param_index, address_space: None, declared_size: None, + extent: None, type_layout: None, type_name, texture_shape, @@ -982,14 +1170,28 @@ fn classify_texture(shape: Option<&TextureShape>) -> (ResourceKind, ResourceAcce } } -/// Access for a buffer given its raw AIR address space: the CONSTANT space is read-only. A DEVICE -/// buffer may be written, and proving it is not requires IR dataflow the facade does not carry — so -/// its access stays `None` (the consumer determines it SPIR-V-side). Only kernel metadata carries -/// address spaces; fragment/vertex buffers report `None`. -fn buffer_access_from_address_space(address_space: Option) -> Option { - match address_space { - Some(ADDRESS_SPACE_CONSTANT) => Some(ResourceAccess::ReadOnly), - _ => None, +fn buffer_extent( + object_size: Option, + declared_size: Option, + type_name: Option<&String>, +) -> BufferExtent { + match (object_size, declared_size, type_name) { + (Some(bytes), _, _) => BufferExtent::Object { bytes }, + (None, Some(_), _) | (None, None, Some(_)) => BufferExtent::Unbounded, + (None, None, None) => BufferExtent::Unknown, + } +} + +fn buffer_access( + declared: Option, + address_space: Option, +) -> Option { + match declared { + Some(BufferAccess::ReadOnly) => Some(ResourceAccess::ReadOnly), + Some(BufferAccess::WriteOnly) => Some(ResourceAccess::WriteOnly), + Some(BufferAccess::ReadWrite) => Some(ResourceAccess::ReadWrite), + None if address_space == Some(ADDRESS_SPACE_CONSTANT) => Some(ResourceAccess::ReadOnly), + None => None, } } @@ -1001,6 +1203,7 @@ fn sampler_binding(n: u32, param_index: Option) -> ResourceBinding { param_index, address_space: None, declared_size: None, + extent: None, type_layout: None, type_name: None, texture_shape: None, diff --git a/src/reflect/tests.rs b/src/reflect/tests.rs index d99f0c573..3c07c8f50 100644 --- a/src/reflect/tests.rs +++ b/src/reflect/tests.rs @@ -636,7 +636,7 @@ fn reflection_serde_round_trips() { #[cfg(feature = "serde")] #[test] -fn reflection_serde_covers_every_v3_field() { +fn reflection_serde_covers_every_v4_field() { // R6: the persisted-cache contract. Build a reflection with EVERY field populated to a // non-default value — including the translate-path-only fields a stage builder never fills // (function_constants, datalayout, imageblock_layouts) and the storage-format / embedded-source @@ -657,6 +657,7 @@ fn reflection_serde_covers_every_v3_field() { param_index: Some(0), address_space: Some(2), declared_size: Some(64), + extent: Some(BufferExtent::Object { bytes: 64 }), type_layout: Some(AirType::Vec { scalar: AirScalar::Float, lanes: 4, @@ -674,6 +675,7 @@ fn reflection_serde_covers_every_v3_field() { param_index: None, address_space: None, declared_size: None, + extent: None, type_layout: None, type_name: Some("texture2d".to_string()), texture_shape: Some(storage_tex), @@ -691,6 +693,7 @@ fn reflection_serde_covers_every_v3_field() { param_index: None, address_space: None, declared_size: None, + extent: None, type_layout: None, type_name: None, texture_shape: None, @@ -746,6 +749,50 @@ fn reflection_serde_covers_every_v3_field() { assert_eq!(back.reflection_version, REFLECTION_VERSION); } +#[test] +fn buffer_reflection_exports_extent_type_size_and_refined_access() { + let ll = r#" +define { float } @f(ptr addrspace(2) readonly %object, ptr addrspace(1) readonly %array, ptr addrspace(1) %unused) { +entry: + %a = load float, ptr addrspace(2) %object, align 4 + %b = load float, ptr addrspace(1) %array, align 4 + %sum = fadd float %a, %b + %result = insertvalue { float } undef, float %sum, 0 + ret { float } %result +} + +!air.fragment = !{!0} +!0 = !{ptr @f, !1, !3} +!1 = !{!2} +!2 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float"} +!3 = !{!4, !5, !6} +!4 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_name", !"Params"} +!5 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_name", !"float"} +!6 = !{i32 2, !"air.buffer", !"air.location_index", i32 2, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_name", !"void"} +"#; + let meta = parse_air_fragment_meta(ll).expect("fragment metadata"); + let mut reflection = ShaderReflection::from_fragment(&meta, Some("f")); + reflection.refine_buffer_access_from_entry(ll); + + let object = reflection.binding_at(ResourceKind::Buffer, 0).unwrap(); + assert_eq!(object.declared_size, Some(16)); + assert_eq!(object.extent, Some(BufferExtent::Object { bytes: 16 })); + assert_eq!(object.type_name.as_deref(), Some("Params")); + assert_eq!(object.access, Some(ResourceAccess::ReadOnly)); + + let array = reflection.binding_at(ResourceKind::Buffer, 1).unwrap(); + assert_eq!(array.declared_size, Some(4)); + assert_eq!(array.extent, Some(BufferExtent::Unbounded)); + assert_eq!(array.type_name.as_deref(), Some("float")); + assert_eq!(array.access, Some(ResourceAccess::ReadOnly)); + + let unused = reflection.binding_at(ResourceKind::Buffer, 2).unwrap(); + assert_eq!(unused.declared_size, None); + assert_eq!(unused.extent, Some(BufferExtent::Unbounded)); + assert_eq!(unused.type_name.as_deref(), Some("void")); + assert_eq!(unused.access, Some(ResourceAccess::Unused)); +} + #[test] fn abi_base_constants_are_the_contract() { assert_eq!(RESOURCE_DESCRIPTOR_SET, 0); diff --git a/src/retry.rs b/src/retry.rs index 5f87338ea..3627b3e0f 100644 --- a/src/retry.rs +++ b/src/retry.rs @@ -40,12 +40,6 @@ fn load_relooper_module(bytes: &[u8]) -> Result { Ok(module) } -fn load_relooper_module_capped(bytes: &[u8], max_blocks: usize) -> Result { - let mut module = load_bytes(bytes).map_err(|error| format!("SPIR-V load: {error:?}"))?; - native::rewrite_to_relooper_module_capped(&mut module, max_blocks)?; - Ok(module) -} - /// Shared context for the retry tiers: the sanitized IR, the temp dir spirv-val runs against, the /// module metadata `finish` re-applies on every re-emit, and the A/B env gates read once at /// construction. Every tier borrows this immutably (`&self`). @@ -961,25 +955,6 @@ impl<'a> RetryCtx<'a> { ) } - // High-cap relooper retry for a HUGE emitted-then-cfg-rejected function. The default relooper cap - // (1024) is tuned to bound gate time on the large cfg cluster. A function that emitted a - // complete module yet fails spirv-val for a cfg-nesting violation (e.g. 02/07ef16ba, 4630 blocks, - // "branches to the selection construct, but not to the selection header") is reducible and carries - // no secondary wall — the only thing keeping it failing is the default cap bailing its >1024 blocks. - // Lifting the cap on THIS arm clears it (the relooper structures the SAME reachable CFG → byte- - // neutral) without making the R4-walled cost-budget cluster waste time relooping-then-discarding. - // Adopt-if-validates, so floor-safe; the 8192 ceiling still bounds a pathological future input. - pub(crate) fn relooper_retry_huge(&self, out: &[u8]) -> Option> { - let r = load_relooper_module_capped(out, 8192).map(|module| module_bytes(&module)); - if self.retry_debug_on { - if let Err(e) = &r { - eprintln!("[retry-debug] relooper_retry_huge rewrite failed: {e}"); - } - } - r.ok() - .filter(|b| self.validates_dbg("relooper_retry_huge", b)) - } - // Combined prune-then-relooper retry — a huge (>1024-block) function whose statically-dead // function-constant arms inflate its block count past the relooper's block cap. Const-fold the // dead arms first (byte-correct DCE — removes only code that never runs at the disabled FC @@ -991,10 +966,8 @@ impl<'a> RetryCtx<'a> { pub(crate) fn prune_then_relooper(&self, out: &[u8]) -> Option> { let mut pruned_module = load_bytes(out).ok()?; native::prune_constant_branches_module(&mut pruned_module).ok()?; - // A function-constant-gated huge function (e.g. the MPS dynamic-struct-index family, ~2265 - // blocks) shrinks to ~1100 blocks once its dead FC arms are pruned — past the default 1024 - // relooper cap but well under this ceiling. Only this already-failing, adopt-if-validates - // path lifts the cap, so the normal relooper's perf budget is unchanged. + // Function-constant pruning can shrink an oversized source below the same hard product cap; + // a residual graph above that cap remains an honest fallback. let r = native::rewrite_to_relooper_module_capped( &mut pruned_module, native::PRUNE_THEN_RELOOPER_MAX_BLOCKS, diff --git a/validation/corpus/metal2vulkan-ledger-metal.jsonl b/validation/corpus/metal2vulkan-ledger-metal.jsonl index 3d9bcc57a..64ccc7e48 100644 --- a/validation/corpus/metal2vulkan-ledger-metal.jsonl +++ b/validation/corpus/metal2vulkan-ledger-metal.jsonl @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:1ca7e0b43e43e74e0481421f5cb6ca5e6984b5c2f9d2adbccdebbe217fb0309d -size 427277109 +oid sha256:85be3a3823881380b437ecfaa92703bb6d71ddf49b3720d3afd64584a14b153b +size 481377854 diff --git a/validation/corpus/metal2vulkan-ledger-moltenvk.jsonl b/validation/corpus/metal2vulkan-ledger-moltenvk.jsonl index 43ab03e7b..f35c2dec4 100644 --- a/validation/corpus/metal2vulkan-ledger-moltenvk.jsonl +++ b/validation/corpus/metal2vulkan-ledger-moltenvk.jsonl @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7e42cdc2d1719ed7eabf9d36eeb0d7e037968122f0f34dd92bf540e3a5618b2d -size 42192944 +oid sha256:2a32580a1538956c693c4cff0747317cc18d94928ae1944a2c8a978381922cfa +size 31376363 diff --git a/validation/corpus/metal2vulkan-ledger.jsonl b/validation/corpus/metal2vulkan-ledger.jsonl index cae17c99c..2f8ba59ec 100644 --- a/validation/corpus/metal2vulkan-ledger.jsonl +++ b/validation/corpus/metal2vulkan-ledger.jsonl @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:87e074a851e7c068c07ef164f15c33da5057aad313abd7e27eb916db02c179ab +oid sha256:43f2d2a61406f2ae23f86a0095d065684ad7f21f4aa4d00eca8005b5861bfa09 size 13501388 diff --git a/validation/src/corpus_run.rs b/validation/src/corpus_run.rs index 8398d07db..99c4aa7c8 100644 --- a/validation/src/corpus_run.rs +++ b/validation/src/corpus_run.rs @@ -28,6 +28,7 @@ use std::path::{Path, PathBuf}; pub const SEED_PROFILE: &str = "deterministic_v7_thread_indexed_inputs"; pub const PLAN_VERSION: u32 = 1; const POINT_COORD_TOPOLOGY_PLAN_VERSION: u32 = 2; +const SAFE_LOOP_BUDGET_PLAN_VERSION: u32 = 3; pub const DEFAULT_BUFFER_LEN: usize = 256; const DEFAULT_DISPATCH_GRID_X: usize = 64; pub const DEFAULT_TEXTURE_EXTENT: Extent3d = Extent3d::new(8, 8, 1); @@ -43,6 +44,11 @@ pub const CASE_TIMEOUT_ENV: &str = "METAL2VULKAN_CORPUS_TIMEOUT_SECS"; pub const DEFAULT_CASE_TIMEOUT_SECS: u64 = 300; /// Log `# SLOW …` when a case is still running (or finished) past this wall time. pub const SLOW_CASE_SECS: u64 = 30; +/// Compile-only Metal PSO creation must not consume enough memory for macOS to kill the small +/// supervisor first and leave the compiler worker orphaned. This is deliberately below one eighth +/// of the 16-GiB validation host; a row that exceeds it is not safe for unattended recovery. +#[cfg(target_os = "macos")] +const PREFLIGHT_WORKER_MAX_RESIDENT_BYTES: u64 = 2 * 1024 * 1024 * 1024; const FC_SPECIALIZATION_ZERO: &str = "zero"; const FC_SPECIALIZATION_VALUES: &str = "values"; const INPUT_SPECIALIZATION_EXPLICIT: &str = "explicit"; @@ -504,6 +510,13 @@ pub struct RunConfig { pub dry_run: bool, pub quiet: bool, pub compile_missing: bool, + /// Metal diagnostic: compile through PSO creation without creating or submitting GPU work. + pub preflight_only: bool, + /// Parent-only output containing hashes whose compile-only Metal preflight remained semantic. + pub preflight_safe_list: Option, + /// Explicitly allow selected historic `compare=none` rows to reach the current Metal oracle. + /// Requires `--air-sha256` or `--air-list`; broad filters remain ledger-only quarantine. + pub remint_compare_none: bool, pub only_air: Option, pub only_air_list: Option, pub jobs: usize, @@ -536,6 +549,9 @@ impl RunConfig { dry_run: false, quiet: false, compile_missing: false, + preflight_only: false, + preflight_safe_list: None, + remint_compare_none: false, only_air: None, only_air_list: None, jobs: default_workers(), @@ -617,6 +633,14 @@ pub fn parse_run_args(backend: RunBackend) -> Option { "--dry-run" => cfg.dry_run = true, "--quiet" => cfg.quiet = true, "--compile-missing" => cfg.compile_missing = true, + "--preflight-only" => cfg.preflight_only = true, + "--preflight-safe-list" => { + cfg.preflight_safe_list = + Some(PathBuf::from(args.next().unwrap_or_else(|| { + fatal(program, "--preflight-safe-list requires a path") + }))); + } + "--remint-compare-none" => cfg.remint_compare_none = true, "--oneshot" => cfg.oneshot = true, "--delta-ledger" => { cfg.delta_ledger = @@ -711,6 +735,25 @@ pub fn parse_run_args(backend: RunBackend) -> Option { if cfg.oneshot && cfg.delta_ledger.is_none() { fatal(program, "--oneshot requires --delta-ledger PATH"); } + if cfg.preflight_only && backend != RunBackend::Metal { + fatal( + program, + "--preflight-only is supported only by corpus-run-metal", + ); + } + if cfg.preflight_safe_list.is_some() && !cfg.preflight_only { + fatal(program, "--preflight-safe-list requires --preflight-only"); + } + if cfg.remint_compare_none + && (backend != RunBackend::Metal + || (cfg.only_air.is_none() && cfg.only_air_list.is_none()) + || !cfg.force) + { + fatal( + program, + "--remint-compare-none requires Metal plus --force and --air-sha256/--air-list", + ); + } Some(cfg) } @@ -747,6 +790,12 @@ fn print_run_usage(program: &str) { --contains TEXT re-run existing backend rows whose label/error/status/hash contains TEXT\n\ --compile-missing translate+spirv-val Vulkan/MoltenVK rows that cannot compare to Metal;\n\ successful rows are recorded as smoke with the skip reason in error\n\ + --preflight-only Metal: compile through PSO creation without submitting\n\ + GPU work; does not modify the ledger\n\ + --preflight-safe-list FILE write hashes whose preflight needs no semantic transform;\n\ + requires --preflight-only\n\ + --remint-compare-none Metal: with --force and an explicit hash/list, allow historic\n\ + compare=none rows through the current guarded oracle\n\ --skip N skip N eligible rows after filters and stable sorting, before --limit\n\ --limit N run at most N eligible rows after filters and stable sorting\n\ --air-list FILE run AIR SHA-256 hashes listed one per line, after other filters\n\ @@ -853,6 +902,7 @@ pub struct TechRowInfo { pub status: String, pub label: String, pub error: Option, + pub compare: String, pub signature: String, } @@ -862,6 +912,9 @@ impl TechRowInfo { self.air_sha256.contains(&text) || self.status.to_ascii_lowercase().contains(&text) || self.label.to_ascii_lowercase().contains(&text) + || format!("compare={}", self.compare) + .to_ascii_lowercase() + .contains(&text) || self.signature.to_ascii_lowercase().contains(&text) || self .error @@ -873,6 +926,21 @@ impl TechRowInfo { } pub fn load_tech_rows(path: &Path) -> HashMap { + #[derive(Deserialize)] + struct TechRowProjection { + air_sha256: String, + #[serde(default)] + status: String, + #[serde(default)] + label: String, + #[serde(default)] + error: Option, + #[serde(default)] + compare: String, + #[serde(default)] + tolerance: Option, + } + let mut rows = HashMap::new(); let Ok(file) = File::open(path) else { return rows; @@ -882,25 +950,15 @@ pub fn load_tech_rows(path: &Path) -> HashMap { if t.is_empty() || t.starts_with('#') { continue; } - let Ok(v) = serde_json::from_str::(t) else { + let Ok(row) = serde_json::from_str::(t) else { continue; }; - let Some(h) = v.get("air_sha256").and_then(|x| x.as_str()) else { - continue; - }; - let air_sha256 = h.to_ascii_lowercase(); - let status = v - .get("status") - .and_then(|x| x.as_str()) - .unwrap_or("") - .to_string(); - let label = v - .get("label") - .and_then(|x| x.as_str()) - .unwrap_or("") - .to_string(); - let error = v.get("error").and_then(|x| x.as_str()).map(str::to_string); - let has_tolerance = v.get("tolerance").is_some(); + let air_sha256 = row.air_sha256.to_ascii_lowercase(); + let status = row.status; + let label = row.label; + let error = row.error; + let compare = row.compare; + let has_tolerance = row.tolerance.is_some(); let signature = execution_failure_signature(&status, error.as_deref(), has_tolerance); rows.insert( air_sha256.clone(), @@ -909,6 +967,7 @@ pub fn load_tech_rows(path: &Path) -> HashMap { status, label, error, + compare, signature, }, ); @@ -920,7 +979,7 @@ pub fn execution_status_is_success(backend: RunBackend, status: &str) -> bool { match backend { RunBackend::Metal => status == "ok", RunBackend::Vulkan => status == "ok" || status == "tolerance" || status == "smoke", - RunBackend::MoltenVk => status == "ok", + RunBackend::MoltenVk => status == "ok" || status == "tolerance", } } @@ -976,6 +1035,13 @@ fn normalize_execution_error_signature(first_line: &str) -> String { } pub fn load_metal_rows(path: &Path) -> HashMap { + load_metal_rows_for_hashes(path, None) +} + +fn load_metal_rows_for_hashes( + path: &Path, + wanted: Option<&HashSet>, +) -> HashMap { let mut map = HashMap::new(); let Ok(file) = File::open(path) else { return map; @@ -985,6 +1051,12 @@ pub fn load_metal_rows(path: &Path) -> HashMap { if t.is_empty() || t.starts_with('#') { continue; } + if wanted.is_some_and(|wanted| { + crate::corpus_shards::compact_json_string_field(t.as_bytes(), b"air_sha256") + .is_none_or(|hash| !wanted.contains(hash)) + }) { + continue; + } if let Ok(row) = serde_json::from_str::(t) { map.insert(row.air_sha256.to_ascii_lowercase(), row); } @@ -1050,7 +1122,7 @@ pub fn merge_delta_into_ledger(ledger: &Path, delta: &Path) -> std::io::Result::new(); let mut n_delta = 0usize; for line in BufReader::new(file).lines() { let line = line?; @@ -1064,53 +1136,17 @@ pub fn merge_delta_into_ledger(ledger: &Path, delta: &Path) -> std::io::Result std::io::Result> { - let mut by_hash = HashMap::new(); - let file = match File::open(path) { - Ok(f) => f, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(by_hash), - Err(e) => return Err(e), - }; - for line in BufReader::new(file).lines() { - let line = line?; - let t = line.trim(); - if t.is_empty() || t.starts_with('#') { - continue; - } - let Ok(v) = serde_json::from_str::(t) else { - continue; - }; - let Some(air) = v.get("air_sha256").and_then(|x| x.as_str()) else { - continue; - }; - by_hash.insert(air.to_ascii_lowercase(), v); + if delta_by_hash.is_empty() { + return Ok(0); } - Ok(by_hash) -} -fn rewrite_jsonl_ledger( - path: &Path, - by_hash: &HashMap, -) -> std::io::Result<()> { - let mut rows: Vec<&serde_json::Value> = by_hash.values().collect(); - rows.sort_by(|a, b| { - let la = a.get("label").and_then(|x| x.as_str()).unwrap_or(""); - let lb = b.get("label").and_then(|x| x.as_str()).unwrap_or(""); - let ha = a.get("air_sha256").and_then(|x| x.as_str()).unwrap_or(""); - let hb = b.get("air_sha256").and_then(|x| x.as_str()).unwrap_or(""); - la.cmp(lb).then(ha.cmp(hb)) - }); - - let tmp = path.with_extension("jsonl.tmp"); + // The execution ledgers contain hundreds of megabytes of base64 output. Stream the existing + // rows instead of materializing every payload as a JSON tree; only the small per-run delta and + // the set of seen hashes need to stay resident. Replacements retain their existing position. + let tmp = ledger.with_extension("jsonl.tmp"); { let mut f = File::create(&tmp)?; writeln!( @@ -1121,15 +1157,68 @@ fn rewrite_jsonl_ledger( f, "# unique by air_sha256 after per-run delta merge; last write wins for a given hash" )?; - for row in rows { - let line = - serde_json::to_string(&sort_json(row.clone())).map_err(std::io::Error::other)?; - writeln!(f, "{line}")?; + + let mut seen = HashSet::::new(); + match File::open(ledger) { + Ok(base) => { + for line in BufReader::new(base).lines() { + let line = line?; + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') { + continue; + } + let Ok(value) = serde_json::from_str::(trimmed) else { + continue; + }; + let Some(air) = value.get("air_sha256").and_then(|value| value.as_str()) else { + continue; + }; + let air = air.to_ascii_lowercase(); + if !seen.insert(air.clone()) { + continue; + } + if let Some(replacement) = delta_by_hash.remove(&air) { + let replacement = + serde_json::to_string(&replacement).map_err(std::io::Error::other)?; + writeln!(f, "{replacement}")?; + } else { + writeln!(f, "{trimmed}")?; + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + + let mut additions = delta_by_hash.into_values().collect::>(); + additions.sort_by(|a, b| { + a.get("label") + .and_then(|value| value.as_str()) + .unwrap_or("") + .cmp( + b.get("label") + .and_then(|value| value.as_str()) + .unwrap_or(""), + ) + .then_with(|| { + a.get("air_sha256") + .and_then(|value| value.as_str()) + .unwrap_or("") + .cmp( + b.get("air_sha256") + .and_then(|value| value.as_str()) + .unwrap_or(""), + ) + }) + }); + for addition in additions { + let addition = serde_json::to_string(&addition).map_err(std::io::Error::other)?; + writeln!(f, "{addition}")?; } f.flush()?; } - fs::rename(&tmp, path)?; - Ok(()) + fs::rename(&tmp, ledger)?; + Ok(n_delta) } struct MetalStatusFields<'a> { @@ -1342,25 +1431,37 @@ fn thread_indexed_input_required_len(ll: &str, type_name: &str, grid_x: u64) -> } fn apply_output_stride_seed_values(ll: &str, output_index: u32, buffers: &mut [PlanBuffer]) { - let mut required_by_buffer: HashMap = HashMap::new(); - for req in output_stride_control_requirements(ll, output_index, buffers) { - required_by_buffer - .entry(req.buffer) - .and_modify(|current| *current = (*current).max(req.min_row_bytes)) - .or_insert(req.min_row_bytes); - } - if required_by_buffer.is_empty() { + let requirements = output_stride_control_requirements(ll, output_index, buffers); + if requirements.is_empty() { return; } + let packed_loop_scatter_fields = packed_loop_scatter_control_fields(ll); for buffer in buffers .iter_mut() .filter(|b| b.seed_mode == SEED_MODE_BOUNDED_CONTROL) { - let Some(&required) = required_by_buffer.get(&buffer.index) else { - continue; - }; for field in &mut buffer.seed_layout { + if packed_loop_scatter_fields + .get(&buffer.index) + .into_iter() + .flatten() + .any(|&(offset, size)| { + field.offset < offset.saturating_add(size) + && field.offset.saturating_add(field.size) > offset + }) + { + continue; + } + let required = requirements + .iter() + .filter(|req| req.buffer == buffer.index) + .filter(|req| req.field_offset.is_none_or(|offset| offset == field.offset)) + .map(|req| req.min_row_bytes) + .max(); + let Some(required) = required else { + continue; + }; if !bounded_control_seed_field_is_within_buffer(buffer.len, field) { continue; } @@ -1421,6 +1522,17 @@ fn infer_buffers(ll: &str) -> Vec { let fdiv_denominator_control_bufs = buffers_with_float_loads_used_as_fdiv_denominators(ll); let local_array_index_control_bufs = buffers_with_loads_used_as_local_array_indices(ll); let bounded_control_module = module_uses_bounded_control_buffers(ll, &loop_bound_bufs); + let direct_scalar_control_bufs = if bounded_control_module { + direct_scalar_integer_load_buffer_locations(ll) + } else { + HashSet::new() + }; + let switch_control_fields = switch_control_struct_field_seed_values(ll); + let packed_loop_scatter_fields = packed_loop_scatter_control_fields(ll); + let zero_exit_cycle_guard_fields = zero_exit_cycle_guard_struct_fields(ll); + let zero_unspecified_bicubic_fragment_controls = ll.contains("!air.fragment") + && ll.contains("@air.sample_texture") + && static_pixel_bicubic_sampler(ll); let readonly_buffers = readonly_entry_buffer_locations(ll); let writeonly_buffers = writeonly_entry_buffer_locations(ll); let locations = stage_resource_locations(ll); @@ -1463,10 +1575,14 @@ fn infer_buffers(ll: &str) -> Vec { }; let type_name = quoted_metadata_string_after(line, "air.arg_type_name"); let atomic_counter_buffer = is_atomic_counter_air_type(type_name.as_deref()); + let direct_device_scalar_control = role == "Input" + && extract_i32_after(line, "air.address_space") == Some(1) + && direct_scalar_control_bufs.contains(&loc_u); let seed_mode = if control_param || atomic_counter_buffer || loop_bound_bufs.contains(&loc_u) || stride_control_bufs.contains(&loc_u) + || direct_device_scalar_control || (role == "Input" && atomic_i32_load_bufs.contains(&loc_u)) { SEED_MODE_BOUNDED_CONTROL @@ -1476,6 +1592,15 @@ fn infer_buffers(ll: &str) -> Vec { SEED_MODE_DETERMINISTIC }; let mut len = (size as usize).max(4); + if fixed_size.is_none() + && !packed_loop_scatter_fields.is_empty() + && writeonly_buffers.contains(&loc_u) + { + let element_size = extract_i32_after(line, "air.arg_type_size") + .and_then(|size| usize::try_from(size).ok()) + .unwrap_or(0); + len = len.max(element_size.saturating_mul(DEFAULT_DISPATCH_GRID_X)); + } if fixed_size.is_none() && bounded_control_module && (role == "Input" || readonly_buffers.contains(&loc_u)) @@ -1499,14 +1624,91 @@ fn infer_buffers(ll: &str) -> Vec { if atomic_counter_buffer { zero_u32_seed_layout(len) } else { - bounded_control_seed_layout( + let mut layout = bounded_control_seed_layout( ll, line, len, &stride_control_bufs, &fdiv_denominator_control_bufs, &local_array_index_control_bufs, - ) + ); + if direct_device_scalar_control { + for field in &mut layout { + if matches!(field.size, 1 | 2 | 4 | 8) && field.value.is_none() { + field.value = Some(1); + } + } + } + for field in &mut layout { + if let Some(&value) = + switch_control_fields.get(&(loc_u, field.offset, field.size)) + { + field.value = Some(value); + } + if zero_exit_cycle_guard_fields.contains(&(loc_u, field.offset, field.size)) { + field.value = Some(0); + } + } + for &(offset, size) in packed_loop_scatter_fields.get(&loc_u).into_iter().flatten() + { + let stride = extract_i32_after(line, "air.arg_type_size") + .and_then(|stride| usize::try_from(stride).ok()) + .filter(|&stride| stride >= offset.saturating_add(size)) + .unwrap_or(len); + // AIR bitfield metadata describes both halves using their four-byte backing + // storage. The IR is authoritative: `and 65535` is the bounded loop count, + // while `lshr 16` is the output base. Zero selects the kernel's defined early + // exit. Any positive count makes a source CFG cycle reachable, which Metal + // oracle policy deliberately refuses to submit even with loop instrumentation. + // Seed every array element identically so the loop proof stays valid before + // the dynamic element index is reduced using the serial dispatch fact. + let mut element_offset = offset; + while element_offset.saturating_add(size) <= len { + let end = element_offset.saturating_add(size); + layout.retain(|field| { + field.offset.saturating_add(field.size) <= element_offset + || field.offset >= end + }); + layout.push(ControlSeedField { + offset: element_offset, + size: 4, + value: Some(0), + }); + element_offset = element_offset.saturating_add(stride); + } + layout.sort_by_key(|field| (field.offset, field.size)); + } + if zero_unspecified_bicubic_fragment_controls { + // A pixel-coordinate bicubic footprint spans four texels per axis. The generic + // bounded-control value (16) commonly pushes synthesized fragment coordinates + // outside the small validation texture, where Metal's fixed-function cubic + // edge behavior is not a portable oracle for the explicit-fetch emulation. + // Keep structurally discovered switch values, but zero every unspecified + // scalar control field so the oracle measures an in-range Catmull-Rom sample. + for field in &mut layout { + if field.value.is_none() { + field.value = Some(0); + } + } + } + let untyped_byte_buffer = type_name.as_deref().is_some_and(|name| { + matches!(name.trim().trim_end_matches('*'), "char" | "uchar" | "void") + }); + if loop_bound_bufs.contains(&loc_u) && untyped_byte_buffer { + // Untyped AIR headers have no struct metadata. Seed only integer fields the + // IR actually loads at constant byte offsets; unrelated payload bytes retain + // the established bounded-control pattern. + layout.extend(raw_integer_load_seed_fields(ll, loc_u, len, 1)); + let memcpy_counts = raw_direct_memcpy_loop_count_offsets(ll, loc_u); + for field in &mut layout { + if field.size == 8 && memcpy_counts.contains(&field.offset) { + field.value = Some(u64::from(BOUNDED_CONTROL_DIM)); + } + } + layout.sort_by_key(|field| (field.offset, field.size)); + layout.dedup_by_key(|field| (field.offset, field.size)); + } + layout } } else if seed_mode == SEED_MODE_FINITE_STRUCT_FLOAT { finite_struct_seed @@ -1567,6 +1769,714 @@ fn infer_buffers(ll: &str) -> Vec { v } +#[derive(Clone)] +struct LlFunctionView<'a> { + name: String, + args: Vec<&'a str>, + body: &'a str, +} + +fn ll_function_views(ll: &str) -> Vec> { + let mut out = Vec::new(); + for line in ll + .lines() + .filter(|line| line.trim_start().starts_with("define ")) + { + let Some(name) = llvm_defined_function_name(line) else { + continue; + }; + let (Some(args), Some(body)) = ( + function_args_for_entry(ll, &name), + function_body_for_entry(ll, &name), + ) else { + continue; + }; + out.push(LlFunctionView { + name, + args: split_llvm_arguments(args), + body, + }); + } + out +} + +fn llvm_defined_function_name(line: &str) -> Option { + let rest = line.trim_start().strip_prefix("define ")?; + let at = rest.find('@')?; + let after = &rest[at + 1..]; + if let Some(quoted) = after.strip_prefix('"') { + let end = quoted.find('"')?; + return Some(quoted[..end].to_string()); + } + let end = after.find('(')?; + Some(after[..end].trim().to_string()) +} + +fn split_llvm_arguments(args: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut start = 0usize; + let mut round = 0i32; + let mut square = 0i32; + let mut curly = 0i32; + let mut angle = 0i32; + let mut quoted = false; + let mut escaped = false; + for (index, ch) in args.char_indices() { + if quoted { + if escaped { + escaped = false; + } else if ch == '\\' { + escaped = true; + } else if ch == '"' { + quoted = false; + } + continue; + } + match ch { + '"' => quoted = true, + '(' => round += 1, + ')' => round -= 1, + '[' => square += 1, + ']' => square -= 1, + '{' => curly += 1, + '}' => curly -= 1, + '<' => angle += 1, + '>' => angle -= 1, + ',' if round == 0 && square == 0 && curly == 0 && angle == 0 => { + out.push(args[start..index].trim()); + start = index + ch.len_utf8(); + } + _ => {} + } + } + if start < args.len() { + out.push(args[start..].trim()); + } + out +} + +fn switch_selector_case_values(body: &str) -> HashMap { + let lines = body.lines().collect::>(); + let mut out = HashMap::new(); + let mut index = 0usize; + while index < lines.len() { + let trimmed = lines[index].trim_start(); + if !trimmed.starts_with("switch i") { + index += 1; + continue; + } + let Some(selector) = first_percent_reg(trimmed) else { + index += 1; + continue; + }; + let mut cases = Vec::new(); + let mut cursor = index; + loop { + cases.extend(nonnegative_switch_case_literals(lines[cursor])); + if lines[cursor].contains(']') || cursor + 1 >= lines.len() { + break; + } + cursor += 1; + } + if let Some(value) = cases.into_iter().min() { + out.insert(selector.to_string(), value); + } + index = cursor + 1; + } + out +} + +fn nonnegative_switch_case_literals(line: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = line; + while let Some(pos) = rest.find("i") { + rest = &rest[pos + 1..]; + let width_len = rest.chars().take_while(char::is_ascii_digit).count(); + if width_len == 0 || !rest[width_len..].starts_with(' ') { + continue; + } + let value_text = rest[width_len + 1..] + .trim_start() + .chars() + .take_while(|ch| ch.is_ascii_digit() || *ch == '-') + .collect::(); + if let Ok(value) = value_text.parse::() { + if let Ok(value) = u64::try_from(value) { + out.push(value); + } + } + rest = &rest[width_len + 1..]; + } + out +} + +fn call_arguments_for_callee<'a>(line: &'a str, callee: &str) -> Option> { + let plain = format!("@{callee}("); + let quoted = format!("@\"{callee}\"("); + let open = line + .find(&plain) + .map(|pos| pos + plain.len()) + .or_else(|| line.find("ed).map(|pos| pos + quoted.len()))?; + let mut depth = 1i32; + let mut in_string = false; + let mut escaped = false; + for (relative, ch) in line[open..].char_indices() { + if in_string { + if escaped { + escaped = false; + } else if ch == '\\' { + escaped = true; + } else if ch == '"' { + in_string = false; + } + continue; + } + match ch { + '"' => in_string = true, + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + return Some(split_llvm_arguments(&line[open..open + relative])); + } + } + _ => {} + } + } + None +} + +fn typed_gep_field_path(rhs: &str, pointer_name: &str) -> Option> { + let operands = rhs.split(',').collect::>(); + let pointer_ordinal = operands.iter().position(|operand| { + operand.contains("ptr") && percent_operands(operand).last().copied() == Some(pointer_name) + })?; + let mut indices = Vec::new(); + for (ordinal, operand) in operands.iter().skip(pointer_ordinal + 1).enumerate() { + let operand = operand.trim(); + let (ty, value) = operand.split_once(' ')?; + if !ty.starts_with('i') { + return None; + } + // The first index selects an array element of the root pointee and may be dynamic. It + // does not name a struct member, so only subsequent indices must be constants. + if ordinal > 0 { + indices.push(value.trim().parse::().ok()?); + } + } + // An array-element GEP has only the discarded root index. Preserve it as an empty struct path + // so a following GEP can append the actual member index. + Some(indices) +} + +fn struct_metadata_field( + ll: &str, + node: u32, + member: usize, +) -> Option<(usize, usize, Option)> { + let line = metadata_node_line(ll, node)?; + let payload = metadata_payload(line)?; + let tokens = metadata_tokens(payload); + let mut pending_nested = None; + let mut field_index = 0usize; + let mut index = 0usize; + while index + 3 < tokens.len() { + if metadata_quoted_token(tokens[index]) == Some("air.struct_type_info") { + pending_nested = tokens + .get(index + 1) + .and_then(|token| metadata_ref_token(token)); + index += 2; + continue; + } + let (Some(offset), Some(size), Some(_repeat), Some(_type_name)) = ( + metadata_i32_token(tokens[index]), + metadata_i32_token(tokens[index + 1]), + metadata_i32_token(tokens[index + 2]), + metadata_quoted_token(tokens[index + 3]), + ) else { + index += 1; + continue; + }; + if field_index == member { + return Some(( + usize::try_from(offset).ok()?, + usize::try_from(size).ok()?, + pending_nested, + )); + } + pending_nested = None; + field_index += 1; + index += 5; + } + None +} + +fn struct_metadata_path_offset_and_size( + ll: &str, + root: u32, + path: &[usize], +) -> Option<(usize, usize)> { + let mut node = root; + let mut base = 0usize; + for (depth, &member) in path.iter().enumerate() { + let (offset, size, nested) = struct_metadata_field(ll, node, member)?; + base = base.checked_add(offset)?; + if depth + 1 == path.len() { + return Some((base, size)); + } + node = nested?; + } + None +} + +/// Exact seed overrides for integer struct fields whose loaded values select an explicit LLVM +/// `switch` case, including selectors forwarded as direct call arguments to helper functions. +fn switch_control_struct_field_seed_values(ll: &str) -> HashMap<(u32, usize, usize), u64> { + let Some(entry_name) = entry_name_from_ll(ll) else { + return HashMap::new(); + }; + let functions = ll_function_views(ll); + let Some(entry) = functions + .iter() + .find(|function| function.name == entry_name) + else { + return HashMap::new(); + }; + let arg_to_buf = arg_index_to_buffer_location(ll); + let arg_names = entry + .args + .iter() + .enumerate() + .filter_map(|(ordinal, arg)| { + let buffer = arg_to_buf.get(&ordinal).copied()?; + let name = percent_operands(arg).last()?.to_string(); + Some((name, buffer)) + }) + .collect::>(); + let switch_choices = functions + .iter() + .map(|function| { + ( + function.name.clone(), + switch_selector_case_values(function.body), + ) + }) + .collect::>(); + + let mut pointer_fields = HashMap::)>::new(); + let mut loaded_fields = HashMap::)>::new(); + let mut requested = Vec::<(u32, Vec, u64)>::new(); + for line in entry.body.lines().map(str::trim) { + if let Some((reg, rhs)) = split_assign(line) { + if rhs.starts_with("getelementptr") { + for pointer_name in percent_operands(rhs) { + let origin = pointer_fields.get(pointer_name).cloned().or_else(|| { + arg_names + .get(pointer_name) + .map(|&buffer| (buffer, Vec::new())) + }); + let Some((buffer, mut path)) = origin else { + continue; + }; + let Some(mut suffix) = typed_gep_field_path(rhs, pointer_name) else { + continue; + }; + path.append(&mut suffix); + pointer_fields.insert(reg.to_string(), (buffer, path)); + break; + } + } else if rhs.starts_with("bitcast ") { + if let Some(origin) = percent_operands(rhs) + .into_iter() + .find_map(|name| pointer_fields.get(name).cloned()) + { + pointer_fields.insert(reg.to_string(), origin); + } + } else if is_scalar_integer_load_rhs(rhs) { + if let Some(origin) = percent_operands(rhs).into_iter().find_map(|name| { + pointer_fields + .get(name) + .cloned() + .or_else(|| arg_names.get(name).map(|&buffer| (buffer, Vec::new()))) + }) { + loaded_fields.insert(reg.to_string(), origin); + } + } + } + + if let Some(entry_switches) = switch_choices.get(&entry.name) { + if line.starts_with("switch i") { + if let Some(selector) = first_percent_reg(line) { + if let (Some(origin), Some(&value)) = + (loaded_fields.get(selector), entry_switches.get(selector)) + { + requested.push((origin.0, origin.1.clone(), value)); + } + } + } + } + for function in &functions { + let Some(function_switches) = switch_choices.get(&function.name) else { + continue; + }; + if function_switches.is_empty() { + continue; + } + let Some(call_args) = call_arguments_for_callee(line, &function.name) else { + continue; + }; + for (ordinal, parameter) in function.args.iter().enumerate() { + let Some(parameter_name) = percent_operands(parameter).into_iter().last() else { + continue; + }; + let Some(&value) = function_switches.get(parameter_name) else { + continue; + }; + let Some(actual) = call_args + .get(ordinal) + .and_then(|argument| percent_operands(argument).into_iter().last()) + else { + continue; + }; + if let Some(origin) = loaded_fields.get(actual) { + requested.push((origin.0, origin.1.clone(), value)); + } + } + } + } + + let struct_nodes = ll + .lines() + .filter(|line| line.contains("air.buffer") && line.contains("air.location_index")) + .filter_map(|line| { + let location = metadata_param_index(line) + .and_then(|index| stage_resource_locations(ll).buffers.get(&index).copied()) + .or_else(|| extract_i32_after(line, "air.location_index").map(|v| v as u32))?; + let node = metadata_ref_after(line, "air.struct_type_info")?; + Some((location, node)) + }) + .collect::>(); + requested + .into_iter() + .filter_map(|(buffer, path, value)| { + let root = *struct_nodes.get(&buffer)?; + let (offset, size) = struct_metadata_path_offset_and_size(ll, root, &path)?; + Some(((buffer, offset, size), value)) + }) + .collect() +} + +/// Locate a packed 32-bit input field whose low half bounds a loop and whose high half seeds a +/// helper-mediated output scatter. Some AIR struct metadata reports each logical 16-bit field as +/// the full four-byte backing integer, so blindly applying both metadata records creates an +/// out-of-bounds, cross-thread write oracle. +fn packed_loop_scatter_control_fields(ll: &str) -> HashMap> { + let Some(entry_name) = entry_name_from_ll(ll) else { + return HashMap::new(); + }; + let functions = ll_function_views(ll); + let Some(entry) = functions + .iter() + .find(|function| function.name == entry_name) + else { + return HashMap::new(); + }; + let loop_bound_buffers = buffers_with_loads_used_as_loop_bounds(ll); + if loop_bound_buffers.is_empty() || !ll.contains(r#""air.thread_position_in_grid""#) { + return HashMap::new(); + } + + let arg_to_buf = arg_index_to_buffer_location(ll); + let arg_names = entry + .args + .iter() + .enumerate() + .filter_map(|(ordinal, arg)| { + let buffer = arg_to_buf.get(&ordinal).copied()?; + let name = percent_operands(arg).last()?.to_string(); + Some((name, buffer)) + }) + .collect::>(); + let writable_buffers = writeonly_entry_buffer_locations(ll); + let writable_args = arg_names + .iter() + .filter(|(_, buffer)| writable_buffers.contains(buffer)) + .map(|(name, _)| name.as_str()) + .collect::>(); + let helper_receives_output = entry.body.lines().any(|line| { + line.contains("call ") + && percent_operands(line) + .iter() + .any(|operand| writable_args.contains(operand)) + }); + if !helper_receives_output { + return HashMap::new(); + } + + let mut pointer_fields = HashMap::)>::new(); + let mut loaded_fields = HashMap::)>::new(); + let mut low_half_sources = HashSet::::new(); + let mut high_half_sources = HashSet::::new(); + for line in entry.body.lines().map(str::trim) { + let Some((reg, rhs)) = split_assign(line) else { + continue; + }; + if rhs.starts_with("getelementptr") { + for pointer_name in percent_operands(rhs) { + let origin = pointer_fields.get(pointer_name).cloned().or_else(|| { + arg_names + .get(pointer_name) + .map(|&buffer| (buffer, Vec::new())) + }); + let Some((buffer, mut path)) = origin else { + continue; + }; + let Some(mut suffix) = typed_gep_field_path(rhs, pointer_name) else { + continue; + }; + path.append(&mut suffix); + pointer_fields.insert(reg.to_string(), (buffer, path)); + break; + } + } else if rhs.starts_with("bitcast ") { + if let Some(origin) = percent_operands(rhs) + .into_iter() + .find_map(|name| pointer_fields.get(name).cloned()) + { + pointer_fields.insert(reg.to_string(), origin); + } + } else if is_scalar_integer_load_rhs(rhs) { + if let Some(origin) = percent_operands(rhs).into_iter().find_map(|name| { + pointer_fields + .get(name) + .cloned() + .or_else(|| arg_names.get(name).map(|&buffer| (buffer, Vec::new()))) + }) { + loaded_fields.insert(reg.to_string(), origin); + } + } else if rhs.starts_with("and i32 ") && rhs.trim_end().ends_with(", 65535") { + if let Some(source) = first_percent_reg(rhs) { + low_half_sources.insert(source.to_string()); + } + } else if rhs.starts_with("lshr i32 ") && rhs.trim_end().ends_with(", 16") { + if let Some(source) = first_percent_reg(rhs) { + high_half_sources.insert(source.to_string()); + } + } + } + + let struct_nodes = ll + .lines() + .filter(|line| line.contains("air.buffer") && line.contains("air.location_index")) + .filter_map(|line| { + let location = metadata_param_index(line) + .and_then(|index| stage_resource_locations(ll).buffers.get(&index).copied()) + .or_else(|| extract_i32_after(line, "air.location_index").map(|v| v as u32))?; + let node = metadata_ref_after(line, "air.struct_type_info")?; + Some((location, node)) + }) + .collect::>(); + + let mut out = HashMap::>::new(); + for source in low_half_sources.intersection(&high_half_sources) { + let Some((buffer, path)) = loaded_fields.get(source) else { + continue; + }; + if !loop_bound_buffers.contains(buffer) { + continue; + } + let Some(root) = struct_nodes.get(buffer) else { + continue; + }; + let Some((offset, size)) = struct_metadata_path_offset_and_size(ll, *root, path) else { + continue; + }; + if size == 4 { + out.entry(*buffer).or_default().push((offset, size)); + } + } + out +} + +/// Find an integer struct field whose zero value makes the entry branch directly to return while +/// its other arm reaches a source CFG cycle. This is used only for the packed loop/scatter oracle +/// class: choosing the defined no-op entry path is safer than submitting even a finite source loop +/// to Metal, and the proof remains structural (entry CFG + rooted load provenance). +fn zero_exit_cycle_guard_struct_fields(ll: &str) -> HashSet<(u32, usize, usize)> { + if packed_loop_scatter_control_fields(ll).is_empty() { + return HashSet::new(); + } + let Some(entry_name) = entry_name_from_ll(ll) else { + return HashSet::new(); + }; + let functions = ll_function_views(ll); + let Some(entry) = functions + .iter() + .find(|function| function.name == entry_name) + else { + return HashSet::new(); + }; + let arg_to_buf = arg_index_to_buffer_location(ll); + let arg_names = entry + .args + .iter() + .enumerate() + .filter_map(|(ordinal, arg)| { + let buffer = arg_to_buf.get(&ordinal).copied()?; + let name = percent_operands(arg).last()?.to_string(); + Some((name, buffer)) + }) + .collect::>(); + + let mut pointer_fields = HashMap::)>::new(); + let mut loaded_fields = HashMap::)>::new(); + let mut zero_conditions = HashMap::), bool)>::new(); + for line in entry.body.lines().map(str::trim) { + let Some((reg, rhs)) = split_assign(line) else { + continue; + }; + if rhs.starts_with("getelementptr") { + for pointer_name in percent_operands(rhs) { + let origin = pointer_fields.get(pointer_name).cloned().or_else(|| { + arg_names + .get(pointer_name) + .map(|&buffer| (buffer, Vec::new())) + }); + let Some((buffer, mut path)) = origin else { + continue; + }; + let Some(mut suffix) = typed_gep_field_path(rhs, pointer_name) else { + continue; + }; + path.append(&mut suffix); + pointer_fields.insert(reg.to_string(), (buffer, path)); + break; + } + } else if rhs.starts_with("bitcast ") { + if let Some(origin) = percent_operands(rhs) + .into_iter() + .find_map(|name| pointer_fields.get(name).cloned()) + { + pointer_fields.insert(reg.to_string(), origin); + } + } else if is_scalar_integer_load_rhs(rhs) { + if let Some(origin) = percent_operands(rhs).into_iter().find_map(|name| { + pointer_fields + .get(name) + .cloned() + .or_else(|| arg_names.get(name).map(|&buffer| (buffer, Vec::new()))) + }) { + loaded_fields.insert(reg.to_string(), origin); + } + } else if let Some(cmp) = rhs.strip_prefix("icmp ") { + let predicate = cmp.split_whitespace().next().unwrap_or_default(); + let operands = percent_operands(cmp); + let loaded = operands + .iter() + .enumerate() + .find_map(|(index, name)| loaded_fields.get(*name).cloned().map(|v| (index, v))); + let Some((loaded_index, origin)) = loaded else { + continue; + }; + let zero_result = match (predicate, loaded_index) { + ("ult", 1) | ("ugt", 0) => Some(false), + _ => None, + }; + if let Some(zero_result) = zero_result { + zero_conditions.insert(reg.to_string(), (origin, zero_result)); + } + } + } + + let cyclic = cyclic_cfg_blocks(entry.body); + let return_blocks = function_return_blocks(entry.body); + let struct_nodes = ll + .lines() + .filter(|line| line.contains("air.buffer") && line.contains("air.location_index")) + .filter_map(|line| { + let location = metadata_param_index(line) + .and_then(|index| stage_resource_locations(ll).buffers.get(&index).copied()) + .or_else(|| extract_i32_after(line, "air.location_index").map(|v| v as u32))?; + Some((location, metadata_ref_after(line, "air.struct_type_info")?)) + }) + .collect::>(); + let mut out = HashSet::new(); + for line in entry.body.lines().map(str::trim) { + if !line.starts_with("br i1 ") { + continue; + } + let Some(condition) = first_percent_reg(line) else { + continue; + }; + let Some(((buffer, path), zero_result)) = zero_conditions.get(condition) else { + continue; + }; + let labels = branch_labels(line); + if labels.len() != 2 { + continue; + } + let exit = labels[usize::from(!*zero_result)]; + let work = labels[usize::from(*zero_result)]; + if !return_blocks.contains(exit) || !block_reaches_any(entry.body, work, &cyclic) { + continue; + } + let Some(root) = struct_nodes.get(buffer) else { + continue; + }; + if let Some((offset, size)) = struct_metadata_path_offset_and_size(ll, *root, path) { + out.insert((*buffer, offset, size)); + } + } + out +} + +fn function_return_blocks(body: &str) -> HashSet<&str> { + let mut current = None; + let mut out = HashSet::new(); + for line in body.lines().map(str::trim) { + if let Some(label) = block_label(line) { + current = Some(label); + } else if line.starts_with("ret ") { + if let Some(label) = current { + out.insert(label); + } + } + } + out +} + +fn block_reaches_any(body: &str, start: &str, targets: &HashSet<&str>) -> bool { + let mut current = None; + let mut successors = HashMap::<&str, Vec<&str>>::new(); + for line in body.lines().map(str::trim) { + if let Some(label) = block_label(line) { + current = Some(label); + successors.entry(label).or_default(); + } else if let Some(block) = current { + if line.starts_with("br ") + || line.starts_with("switch ") + || (line.starts_with('i') && line.contains("label %")) + { + successors + .entry(block) + .or_default() + .extend(branch_labels(line)); + } + } + } + let mut pending = vec![start]; + let mut seen = HashSet::new(); + while let Some(block) = pending.pop() { + if targets.contains(block) { + return true; + } + if seen.insert(block) { + pending.extend(successors.get(block).into_iter().flatten().copied()); + } + } + false +} + fn writeonly_entry_buffer_locations(ll: &str) -> HashSet { entry_buffer_locations_with_arg_attr(ll, "writeonly") } @@ -1794,17 +2704,26 @@ fn texture_format_from_air_type(type_name: Option<&str>) -> &'static str { let Some(type_name) = type_name else { return "Rgba32Float"; }; - if type_name.starts_with("depth") { + // Texture arrays wrap the actual texture spelling in `array<...>`. Parse the innermost AIR + // texture type so its component/access qualifiers, rather than the outer aggregate, determine + // the validation format. + let texture_type = [type_name.find("texture"), type_name.find("depth")] + .into_iter() + .flatten() + .min() + .map(|start| &type_name[start..]) + .unwrap_or(type_name); + if texture_type.starts_with("depth") { return "R32Float"; } - let component = type_name + let component = texture_type .split_once('<') .and_then(|(_, rest)| rest.split([',', '>']).next()) .map(str::trim) .unwrap_or(""); match component { "half" => "Rgba16Float", - "float" if texture_type_is_writable(type_name) => "R32Float", + "float" if texture_type_is_writable(texture_type) => "R32Float", "float" => "Rgba32Float", "ushort" => "Rgba16Uint", "uint" | "uchar" => "Rgba8Uint", @@ -1906,31 +2825,81 @@ fn fragment_output_format_from_air_type(type_name: &str) -> Option<&'static str> }) } -fn unsupported_fragment_color_output_arity(ll: &str) -> Option { +fn fragment_rgb_render_target_padding(ll: &str, output_format: &str) -> Option<(usize, usize)> { let meta = metal2vulkan::meta::parse_air_fragment_meta(ll)?; - let mut render_targets: Vec<_> = meta.render_target_members.iter().collect(); - render_targets.sort_by_key(|(_, location)| *location); + let mut location_zero_types = meta + .render_target_members + .iter() + .filter(|(_, location)| *location == 0) + .filter_map(|(member, _)| meta.render_target_type_name(*member)); + let type_name = location_zero_types.next()?; + if location_zero_types.any(|other| other != type_name) { + return None; + } - for (member, location) in render_targets { - let Some(type_name) = meta.render_target_type_name(*member) else { - continue; - }; - if fragment_output_type_has_three_components(type_name) { - return Some(format!( - "unsupported Metal fragment color output attachment arity: render target location \ - {location} uses AIR type {type_name:?}, but Metal has no renderable RGB color \ - attachment format for a full golden" - )); + match (type_name, output_format) { + ("half3", "Rgba16Float") | ("ushort3", "Rgba16Uint") | ("short3", "Rgba16Sint") => { + Some((6, 8)) } + ("float3", "Rgba32Float") | ("uint3", "Rgba32Uint") | ("int3", "Rgba32Sint") => { + Some((12, 16)) + } + _ => None, } - None } -fn fragment_output_type_has_three_components(type_name: &str) -> bool { - matches!( - type_name, - "half3" | "float3" | "ushort3" | "short3" | "uint3" | "int3" - ) +/// Metal and Vulkan render three-component fragment outputs into four-component attachments. +/// The shader defines RGB, but the attachment's fourth lane is API padding rather than part of +/// the AIR result. Canonicalize that lane after readback so the oracle compares every defined AIR +/// output byte without depending on backend-specific padding values. +fn canonicalize_fragment_render_target_padding(ll: &str, plan: &HarnessPlan, bytes: &mut [u8]) { + if plan.output.kind != "render_target" { + return; + } + let Some((defined_bytes, attachment_stride)) = + fragment_rgb_render_target_padding(ll, &plan.output.format) + else { + return; + }; + assert!( + bytes.len().is_multiple_of(attachment_stride), + "RGB render-target readback length {} is not a multiple of attachment stride {}", + bytes.len(), + attachment_stride + ); + for texel in bytes.chunks_exact_mut(attachment_stride) { + texel[defined_bytes..].fill(0); + } +} + +fn canonicalize_unordered_atomic_append_output(ll: &str, plan: &HarnessPlan, bytes: &mut [u8]) { + if plan.output.kind != "buffer" + || plan.output.format != "RawBytes" + || !bytes.len().is_multiple_of(4) + || !ll.contains("@air.atomic.global.add") + || !ll.contains("\"air.thread_position_in_grid\"") + || !ll + .lines() + .any(|line| line.trim_start().contains(" = getelementptr inbounds i32")) + || !ll + .lines() + .any(|line| line.trim_start().starts_with("store i32 ")) + { + return; + } + let mut words = bytes + .chunks_exact(4) + .map(|word| u32::from_le_bytes(word.try_into().expect("four-byte chunk"))) + .collect::>(); + words.sort_unstable(); + for (word, value) in bytes.chunks_exact_mut(4).zip(words) { + word.copy_from_slice(&value.to_le_bytes()); + } +} + +fn canonicalize_output_bytes(ll: &str, plan: &HarnessPlan, bytes: &mut [u8]) { + canonicalize_fragment_render_target_padding(ll, plan, bytes); + canonicalize_unordered_atomic_append_output(ll, plan, bytes); } fn buffer_output_format(ll: &str, output_index: u32) -> Option<&'static str> { @@ -2375,6 +3344,19 @@ fn buffers_with_loads_used_as_loop_bounds(ll: &str) -> HashSet { || rhs.starts_with("select ") || rhs.starts_with("add ") || rhs.starts_with("sub ") + || rhs.starts_with("mul ") + || rhs.starts_with("shl ") + || rhs.starts_with("lshr ") + || rhs.starts_with("ashr ") + || rhs.starts_with("and ") + || rhs.starts_with("or ") + || rhs.starts_with("xor ") + || rhs.starts_with("udiv ") + || rhs.starts_with("sdiv ") + || rhs.starts_with("urem ") + || rhs.starts_with("srem ") + || rhs.contains("@air.min.") + || rhs.contains("@air.max.") { if let Some(buf) = first_int_buf_operand(rhs, &int_from_buf) { int_from_buf.insert(reg, buf); @@ -2414,6 +3396,196 @@ fn buffers_with_loads_used_as_loop_bounds(ll: &str) -> HashSet { branched } +fn direct_scalar_integer_load_buffer_locations(ll: &str) -> HashSet { + let Some(body) = primary_entry_function_body(ll) else { + return HashSet::new(); + }; + let arg_to_buf = arg_index_to_buffer_location(ll); + let arg_name_to_buf = arg_name_to_buffer_location(ll, &arg_to_buf); + let pointers = HashMap::new(); + body.lines() + .filter_map(|line| { + let (_, rhs) = split_assign(line.trim())?; + is_scalar_integer_load_rhs(rhs).then_some(rhs) + }) + .filter_map(|rhs| first_buf_operand(rhs, &pointers, &arg_to_buf, &arg_name_to_buf)) + .collect() +} + +/// Integer fields read at constant byte offsets from an untyped buffer. AIR metadata sometimes +/// describes a structured control/header allocation only as `char*`, so there is no +/// `air.struct_type_info` from which to build a seed layout. Recover the field offsets from the +/// pointer chain instead; only buffers already proven to feed a cyclic branch use these fields. +fn raw_integer_load_seed_fields( + ll: &str, + target_buffer: u32, + len: usize, + value: u64, +) -> Vec { + let Some(body) = primary_entry_function_body(ll) else { + return Vec::new(); + }; + let arg_to_buf = arg_index_to_buffer_location(ll); + let arg_name_to_buf = arg_name_to_buffer_location(ll, &arg_to_buf); + let mut pointers = HashMap::<&str, (u32, usize)>::new(); + let mut fields = Vec::new(); + + for line in body.lines().map(str::trim) { + let Some((reg, rhs)) = split_assign(line) else { + continue; + }; + if rhs.starts_with("bitcast ") { + if let Some(pointer) = + pointer_buffer_and_offset(rhs, &pointers, &arg_to_buf, &arg_name_to_buf) + { + pointers.insert(reg, pointer); + } + continue; + } + if rhs.starts_with("getelementptr") { + let Some((buffer, base)) = + pointer_buffer_and_offset(rhs, &pointers, &arg_to_buf, &arg_name_to_buf) + else { + continue; + }; + // Only byte GEPs have a layout-independent constant offset. Typed GEP offsets need + // LLVM layout information and are intentionally left unknown here. + if rhs.contains(" i8,") { + if let Some(delta) = trailing_constant_i64(rhs) { + if let Some(offset) = base.checked_add_signed(delta) { + pointers.insert(reg, (buffer, offset)); + } + } + } else if rhs.contains(", i64 0") { + pointers.insert(reg, (buffer, base)); + } + continue; + } + if !is_scalar_integer_load_rhs(rhs) { + continue; + } + let Some((buffer, offset)) = + pointer_buffer_and_offset(rhs, &pointers, &arg_to_buf, &arg_name_to_buf) + else { + continue; + }; + if buffer != target_buffer { + continue; + } + let Some(size) = scalar_integer_load_size(rhs) else { + continue; + }; + if offset.saturating_add(size) <= len { + fields.push(ControlSeedField { + offset, + size, + value: Some(value), + }); + } + } + fields +} + +fn raw_direct_memcpy_loop_count_offsets(ll: &str, target_buffer: u32) -> HashSet { + let Some(body) = primary_entry_function_body(ll) else { + return HashSet::new(); + }; + if !body.contains("@llvm.memcpy.") { + return HashSet::new(); + } + let arg_to_buf = arg_index_to_buffer_location(ll); + let arg_name_to_buf = arg_name_to_buffer_location(ll, &arg_to_buf); + let mut pointers = HashMap::<&str, (u32, usize)>::new(); + let mut raw_i64_loads = HashMap::<&str, usize>::new(); + for line in body.lines().map(str::trim) { + let Some((reg, rhs)) = split_assign(line) else { + continue; + }; + if rhs.starts_with("bitcast ") { + if let Some(pointer) = + pointer_buffer_and_offset(rhs, &pointers, &arg_to_buf, &arg_name_to_buf) + { + pointers.insert(reg, pointer); + } + continue; + } + if rhs.starts_with("getelementptr") { + let Some((buffer, base)) = + pointer_buffer_and_offset(rhs, &pointers, &arg_to_buf, &arg_name_to_buf) + else { + continue; + }; + if rhs.contains(" i8,") { + if let Some(delta) = trailing_constant_i64(rhs) { + if let Some(offset) = base.checked_add_signed(delta) { + pointers.insert(reg, (buffer, offset)); + } + } + } + continue; + } + if scalar_integer_load_size(rhs) == Some(8) { + if let Some((buffer, offset)) = + pointer_buffer_and_offset(rhs, &pointers, &arg_to_buf, &arg_name_to_buf) + { + if buffer == target_buffer { + raw_i64_loads.insert(reg, offset); + } + } + } + } + let mut out = HashSet::new(); + for line in body.lines().filter(|line| line.contains(" = phi i64 ")) { + for (reg, offset) in &raw_i64_loads { + if line.contains(&format!("[ %{reg},")) { + out.insert(*offset); + } + } + } + out +} + +fn pointer_buffer_and_offset<'a>( + rhs: &'a str, + pointers: &HashMap<&'a str, (u32, usize)>, + arg_to_buf: &HashMap, + arg_name_to_buf: &HashMap, +) -> Option<(u32, usize)> { + for name in percent_operands(rhs) { + if let Some(&pointer) = pointers.get(name) { + return Some(pointer); + } + if let Some(&buffer) = arg_name_to_buf.get(name) { + return Some((buffer, 0)); + } + if let Ok(ordinal) = name.parse::() { + if let Some(&buffer) = arg_to_buf.get(&ordinal) { + return Some((buffer, 0)); + } + } + } + None +} + +fn trailing_constant_i64(rhs: &str) -> Option { + let (_, tail) = rhs.rsplit_once("i64 ")?; + tail.split(|ch: char| ch == ',' || ch.is_whitespace()) + .next()? + .parse() + .ok() +} + +fn scalar_integer_load_size(rhs: &str) -> Option { + let rest = rhs.strip_prefix("load i")?; + let bits = rest + .chars() + .take_while(char::is_ascii_digit) + .collect::() + .parse::() + .ok()?; + matches!(bits, 8 | 16 | 32 | 64).then_some(bits / 8) +} + fn first_int_buf_operand(rhs: &str, int_from_buf: &HashMap<&str, u32>) -> Option { for tok in rhs.split([',', ' ', '[', ']']) { let t = tok.trim(); @@ -2458,7 +3630,10 @@ fn cyclic_cfg_blocks(body: &str) -> HashSet<&str> { let Some(block) = current else { continue; }; - if line.starts_with("br ") { + if line.starts_with("br ") + || line.starts_with("switch ") + || (line.starts_with('i') && line.contains("label %")) + { succs.entry(block).or_default().extend(branch_labels(line)); } } @@ -3017,7 +4192,32 @@ fn bounded_control_seed_fields( let offset = base_offset.saturating_add(offset.max(0) as usize); let field_byte_size = byte_size.max(0) as usize; let repeat_count = usize::try_from(repeat_count).unwrap_or(0).max(1); - if let Some(size) = bounded_control_field_seed_size(type_name, byte_size) { + if let Some((element_size, columns, rows)) = + bounded_control_matrix_shape(type_name, byte_size) + { + for element in 0..repeat_count { + let element_offset = offset.saturating_add(element.saturating_mul(field_byte_size)); + for column in 0..columns { + for row in 0..rows { + let lane = column.saturating_mul(rows).saturating_add(row); + let field_offset = + element_offset.saturating_add(lane.saturating_mul(element_size)); + if field_offset.saturating_add(element_size) <= ctx.len { + let one = match element_size { + 2 => 0x3c00, + 4 => 0x3f80_0000, + _ => unreachable!("validated matrix scalar size"), + }; + fields.push(ControlSeedField { + offset: field_offset, + size: element_size, + value: Some(if column == row { one } else { 0 }), + }); + } + } + } + } + } else if let Some(size) = bounded_control_field_seed_size(type_name, byte_size) { for element in 0..repeat_count { let field_offset = offset.saturating_add(element.saturating_mul(field_byte_size)); if field_offset < ctx.len && field_offset.saturating_add(size) <= ctx.len { @@ -3034,6 +4234,30 @@ fn bounded_control_seed_fields( }); } } + } else if let Some((lanes, scalar, element_size)) = integer_vector_shape(type_name) { + if field_byte_size == lanes.saturating_mul(element_size) { + for element in 0..repeat_count { + let element_offset = + offset.saturating_add(element.saturating_mul(field_byte_size)); + for lane in 0..lanes { + let field_offset = + element_offset.saturating_add(lane.saturating_mul(element_size)); + if field_offset.saturating_add(element_size) <= ctx.len { + fields.push(ControlSeedField { + offset: field_offset, + size: element_size, + value: scalar_value_override.or_else(|| { + bounded_control_field_seed_value( + scalar, + ctx.seed_float_one, + ctx.seed_int_zero, + ) + }), + }); + } + } + } + } } else if let Some(nested_node) = pending_nested_node.take() { let nested_scalar_value_override = result_dimension_struct_field(type_name, field_name).then_some(0); @@ -3181,6 +4405,98 @@ fn metadata_ref_token(token: &str) -> Option { token.strip_prefix('!')?.parse().ok() } +fn fragment_has_uninitialized_imageblock_input(ll: &str) -> bool { + let Some(fragment_line) = ll + .lines() + .find(|line| line.trim_start().starts_with("!air.fragment =")) + else { + return false; + }; + let Some(fragment_entry) = metadata_payload(fragment_line) + .map(metadata_tokens) + .and_then(|tokens| tokens.into_iter().find_map(metadata_ref_token)) + else { + return false; + }; + let Some(entry_line) = metadata_node_line(ll, fragment_entry) else { + return false; + }; + let entry_refs = metadata_payload(entry_line) + .map(metadata_tokens) + .unwrap_or_default() + .into_iter() + .filter_map(metadata_ref_token) + .collect::>(); + let Some(input_list) = entry_refs.first().copied() else { + return false; + }; + let Some(input_line) = metadata_node_line(ll, input_list) else { + return false; + }; + metadata_payload(input_line) + .map(metadata_tokens) + .unwrap_or_default() + .into_iter() + .filter_map(metadata_ref_token) + .filter_map(|node| metadata_node_line(ll, node)) + .any(|line| line.contains(r#"!"air.imageblock_data""#)) +} + +const UNINITIALIZED_FRAGMENT_IMAGEBLOCK_REASON: &str = + "fragment reads incoming air.imageblock_data, but the validation render pass has no prior draw \ + or tile initializer defining that imageblock memory"; + +const POST_TESSELLATION_VERTEX_ORACLE_REASON: &str = + "vertex entry consumes air.patch_control_point_input and therefore requires a complete Metal \ + tessellation pipeline with a control-point producer; the standalone validation vertex harness \ + cannot construct a defined oracle for this ABI"; + +fn invalid_standalone_metal_oracle_reason(ll: &str) -> Option<&'static str> { + ll.contains(r#"!"air.patch_control_point_input""#) + .then_some(POST_TESSELLATION_VERTEX_ORACLE_REASON) +} + +fn unsafe_metal_submission_reason(ll: &str) -> Option<&'static str> { + if fragment_has_uninitialized_imageblock_input(ll) { + return Some(UNINITIALIZED_FRAGMENT_IMAGEBLOCK_REASON); + } + + let conditional_threadgroup_buffers = ll + .lines() + .filter(|line| { + line.contains(r#"!"air.function_constant""#) + && line.contains(r#"!"air.buffer""#) + && extract_i32_after(line, "air.address_space") == Some(3) + }) + .count(); + if conditional_threadgroup_buffers >= 2 && ll.contains(r#"section "air.fc_initializer""#) { + return Some( + "kernel combines multiple function-constant-selected threadgroup buffers with packed \ + air.fc_initializer controls; the synthetic scalar specialization cannot prove a \ + coherent allocation/use configuration or bounded work", + ); + } + + let conditional_textures = ll + .lines() + .filter(|line| { + line.contains(r#"!"air.function_constant""#) && line.contains(r#"!"air.texture""#) + }) + .count(); + if ll.len() >= 300_000 + && conditional_textures >= 8 + && ll.contains("array_ref Option { let name = type_name.trim().trim_end_matches('*').trim(); let size = match name { @@ -3193,6 +4509,25 @@ fn bounded_control_field_seed_size(type_name: &str, byte_size: i32) -> Option Option<(usize, usize, usize)> { + let name = type_name.trim().trim_end_matches('*').trim(); + let (element_size, dimensions) = if let Some(dimensions) = name.strip_prefix("float") { + (4usize, dimensions) + } else if let Some(dimensions) = name.strip_prefix("half") { + (2usize, dimensions) + } else { + return None; + }; + let (columns, rows) = dimensions.split_once('x')?; + let columns = columns.parse::().ok()?; + let rows = rows.parse::().ok()?; + if !(2..=4).contains(&columns) || !(2..=4).contains(&rows) { + return None; + } + let packed_size = element_size.checked_mul(columns)?.checked_mul(rows)?; + (packed_size <= usize::try_from(byte_size).ok()?).then_some((element_size, columns, rows)) +} + fn bounded_control_field_seed_value( type_name: &str, _seed_float_one: bool, @@ -3681,34 +5016,6 @@ fn incompatible_multisample_texture_golden(ll: &str, _metal: &MetalRow) -> Optio ) } -fn incompatible_function_constant_texture_array_ref_golden( - ll: &str, - metal: &MetalRow, -) -> Option { - if !matches!( - metal.fc_specialization.as_deref(), - Some(FC_SPECIALIZATION_ZERO | FC_SPECIALIZATION_VALUES) - ) { - return None; - } - let has_fc_texture_metadata = ll.lines().any(|line| { - line.contains(r#""air.function_constant""#) - && line.contains(r#""air.texture""#) - && line.contains("texture") - }); - let mixes_plain_and_array = ll.contains("texture2d<") && ll.contains("texture2d_array<"); - if !has_fc_texture_metadata || !mixes_plain_and_array { - return None; - } - Some( - "metal golden uses function-constant-selected texture metadata mixing texture2d and \ - texture2d_array image-view families; the Vulkan validation runner cannot bind a single \ - compatible image view for that reflected descriptor set, so rebank with a concrete texture \ - family or drop the row" - .into(), - ) -} - fn incompatible_function_constant_private_pointer_table_golden( ll: &str, metal: &MetalRow, @@ -3758,6 +5065,9 @@ fn incompatible_function_constant_simdgroup_golden(ll: &str, metal: &MetalRow) - { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden specializes AIR function constants that enable simdgroup/threadgroup-memory \ paths; subgroup topology, barriers, and threadgroup scratch scheduling are not a portable \ @@ -4261,7 +5571,10 @@ fn declares_air_function_constants(ll: &str) -> bool { } fn incompatible_output_plan_golden(ll: &str, metal: &MetalRow) -> Option { - let current_plan = infer_plan(ll); + // Compare against the current effective oracle plan, including structural launch + // specialization. Comparing only raw inference incorrectly rejects deliberately serial plans + // that `metal_oracle_inputs` would reproduce before every new Metal execution. + let (current_plan, _) = metal_oracle_inputs(ll, None); let current = ¤t_plan.output; let banked = &metal.plan.output; if !output_plans_match(current, banked) { @@ -4421,6 +5734,7 @@ struct OwnedLoopInputFacts { arg_values: Vec<(String, i128)>, arg_float_values: Vec<(String, f64)>, arg_field_values: Vec<(String, Vec, i128)>, + arg_byte_values: Vec<(String, usize, i128)>, arg_upper_bounds: Vec<(String, i128)>, arg_vector_values: Vec<(String, usize, i128)>, arg_vector_upper_bounds: Vec<(String, usize, i128)>, @@ -4435,6 +5749,7 @@ impl OwnedLoopInputFacts { arg_values: &self.arg_values, arg_float_values: &self.arg_float_values, arg_field_values: &self.arg_field_values, + arg_byte_values: &self.arg_byte_values, arg_upper_bounds: &self.arg_upper_bounds, arg_vector_values: &self.arg_vector_values, arg_vector_upper_bounds: &self.arg_vector_upper_bounds, @@ -4445,11 +5760,6 @@ impl OwnedLoopInputFacts { } fn loop_input_facts_for_metal_plan(ll: &str, entry: &str, metal: &MetalRow) -> OwnedLoopInputFacts { - let arg_names = entry_arg_names(ll, entry); - if arg_names.is_empty() { - return OwnedLoopInputFacts::default(); - } - let owned_inputs = plan_to_owned_inputs(&metal.plan).ok(); let fc_values = metal .fc_values .as_deref() @@ -4461,16 +5771,31 @@ fn loop_input_facts_for_metal_plan(ll: &str, entry: &str, metal: &MetalRow) -> O .collect() }) .unwrap_or_else(|| function_constant_values_for_oracle_inputs(ll)); + loop_input_facts_for_plan(ll, entry, &metal.plan, fc_values) +} + +fn loop_input_facts_for_plan( + ll: &str, + entry: &str, + plan: &HarnessPlan, + fc_values: Vec<(usize, u64)>, +) -> OwnedLoopInputFacts { + let arg_names = entry_arg_names(ll, entry); + if arg_names.is_empty() { + return OwnedLoopInputFacts::default(); + } + let owned_inputs = plan_to_owned_inputs(plan).ok(); let mut facts = OwnedLoopInputFacts { fc_values, - arg_values: exact_launch_scalar_arg_values(ll, &arg_names, &metal.plan), + arg_values: exact_launch_scalar_arg_values(ll, &arg_names, plan), arg_float_values: Vec::new(), arg_field_values: Vec::new(), - arg_upper_bounds: launch_scalar_arg_upper_bounds(ll, &arg_names, &metal.plan), - arg_vector_values: exact_launch_vector_arg_values(ll, &arg_names, &metal.plan), - arg_vector_upper_bounds: launch_vector_arg_upper_bounds(ll, &arg_names, &metal.plan), - texture_extents: exact_texture_extent_values(ll, &arg_names, &metal.plan), - imageblock_extent: exact_imageblock_extent_value(ll, &metal.plan), + arg_byte_values: Vec::new(), + arg_upper_bounds: launch_scalar_arg_upper_bounds(ll, &arg_names, plan), + arg_vector_values: exact_launch_vector_arg_values(ll, &arg_names, plan), + arg_vector_upper_bounds: launch_vector_arg_upper_bounds(ll, &arg_names, plan), + texture_extents: exact_texture_extent_values(ll, &arg_names, plan), + imageblock_extent: exact_imageblock_extent_value(ll, plan), }; if let Some(owned_inputs) = &owned_inputs { facts.arg_values.extend(exact_scalar_buffer_arg_values( @@ -4490,6 +5815,13 @@ fn loop_input_facts_for_metal_plan(ll: &str, entry: &str, metal: &MetalRow) -> O &arg_names, &owned_inputs.inputs, )); + facts + .arg_byte_values + .extend(exact_raw_integer_buffer_arg_byte_values( + ll, + entry, + &owned_inputs.inputs, + )); facts .arg_vector_values .extend(exact_vector_buffer_arg_values( @@ -4839,6 +6171,13 @@ fn exact_struct_buffer_arg_field_values( arg_names: &[String], inputs: &Inputs, ) -> Vec<(String, Vec, i128)> { + let serial_packed_buffers = if inputs.dispatch.threads_per_grid == [1, 1, 1] { + packed_loop_scatter_control_fields(ll) + .into_keys() + .collect::>() + } else { + HashSet::new() + }; let input_bytes = inputs .buffers .iter() @@ -4853,10 +6192,7 @@ fn exact_struct_buffer_arg_field_values( let locations = stage_resource_locations(ll); let mut out = Vec::new(); for line in ll.lines() { - if !line.contains(r#""air.buffer""#) - || !line.contains(r#""air.location_index""#) - || !line.contains(r#""air.address_space", i32 2"#) - { + if !line.contains(r#""air.buffer""#) || !line.contains(r#""air.location_index""#) { continue; } let Some(arg_ord) = metadata_param_index(line).and_then(|v| usize::try_from(v).ok()) else { @@ -4871,6 +6207,12 @@ fn exact_struct_buffer_arg_field_values( let Some(raw_loc) = extract_i32_after(line, "air.location_index").map(|v| v as u32) else { continue; }; + let address_space = extract_i32_after(line, "air.address_space"); + if address_space != Some(2) + && !(address_space == Some(1) && serial_packed_buffers.contains(&raw_loc)) + { + continue; + } let Some(bytes) = locations .buffers .get(&(arg_ord as u32)) @@ -4890,6 +6232,48 @@ fn exact_struct_buffer_arg_field_values( out } +pub(crate) fn exact_raw_integer_buffer_arg_byte_values( + ll: &str, + entry: &str, + inputs: &Inputs, +) -> Vec<(String, usize, i128)> { + let arg_names = entry_arg_names(ll, entry); + let arg_to_buffer = arg_index_to_buffer_location(ll); + let input_bytes = inputs + .buffers + .iter() + .filter_map(|buffer| match buffer.seed { + Seed::ExactBytes { bytes, .. } => Some((buffer.index, bytes)), + _ => None, + }) + .collect::>(); + let mut out = Vec::new(); + for (arg_ordinal, buffer) in arg_to_buffer { + let Some(arg_name) = arg_names.get(arg_ordinal) else { + continue; + }; + let Some(bytes) = input_bytes.get(&buffer).copied() else { + continue; + }; + for field in raw_integer_load_seed_fields(ll, buffer, bytes.len(), 0) { + let end = field.offset.saturating_add(field.size); + let Some(raw) = bytes.get(field.offset..end) else { + continue; + }; + let mut widened = [0u8; 8]; + widened[..raw.len()].copy_from_slice(raw); + out.push(( + arg_name.clone(), + field.offset, + i128::from(u64::from_le_bytes(widened)), + )); + } + } + out.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1))); + out.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1); + out +} + struct StructFieldCollectCtx<'a, 'b> { ll: &'a str, bytes: &'a [u8], @@ -5209,10 +6593,11 @@ fn incompatible_compare_none_loop_guard_golden( return None; } let loop_facts = loop_input_facts_for_metal_plan(ll, entry, metal); - match crate::loop_budget::classify_and_instrument_with_loop_input_facts( + match crate::loop_budget::classify_and_instrument_with_loop_input_facts_and_budget( ll, entry, loop_facts.as_loop_input_facts(), + loop_budget_for_metal_row(metal), ) { crate::loop_budget::GuardPlan::Quarantine(reason) => Some(format!( "metal golden compare=none cannot be reproduced by current loop guard: {reason}; \ @@ -5223,6 +6608,19 @@ fn incompatible_compare_none_loop_guard_golden( } } +fn loop_budget_for_metal_row(metal: &MetalRow) -> i32 { + // A compare=none row is smoke-only: it has no semantic output whose replay depends on the + // historic guard transform. Always use the current safety cap for those rows, including old + // plan versions, so a stale smoke row cannot turn a large bounded kernel into a multi-minute + // GPU submission. Exact/tolerance rows retain the legacy cap until they are rebanked because + // changing their guard can change a banked output when the old cap was reached. + if metal.compare == "none" || metal.plan_version >= SAFE_LOOP_BUDGET_PLAN_VERSION { + crate::loop_budget::LOOP_BUDGET_BACKEDGES + } else { + crate::loop_budget::LEGACY_LOOP_BUDGET_BACKEDGES + } +} + fn incompatible_compare_none_simdgroup_matrix_smoke_golden( ll: &str, metal: &MetalRow, @@ -5279,25 +6677,11 @@ fn incompatible_parallel_dynamic_buffer_scatter_golden( metal: &MetalRow, ) -> Option { if metal.compare == "none" - || metal.plan.output.kind != "buffer" - || metal.plan.output.format != "RawBytes" || !metal.plan.dispatch_grid.iter().any(|&n| n > 1) - || !ll.contains("\"air.thread_position_in_grid\"") - || !ll.contains("@air.atomic.global.") + || !requires_serial_dynamic_buffer_scatter_plan(ll, &metal.plan) { return None; } - let output = metal - .plan - .buffers - .iter() - .find(|buffer| buffer.index == metal.plan.output.index)?; - if output.role != "InOut" { - return None; - } - if !declares_data_dependent_non_atomic_store_to_buffer(ll, metal.plan.output.index) { - return None; - } Some( "metal golden compares parallel non-atomic dynamic buffer scatter output whose write order \ is backend-schedule-dependent; rebank Metal row with a serial/smoke plan" @@ -5305,6 +6689,28 @@ fn incompatible_parallel_dynamic_buffer_scatter_golden( ) } +fn requires_serial_dynamic_buffer_scatter_plan(ll: &str, plan: &HarnessPlan) -> bool { + if plan.output.kind != "buffer" + || plan.output.format != "RawBytes" + || !ll.contains("\"air.thread_position_in_grid\"") + { + return false; + } + let Some(output) = plan + .buffers + .iter() + .find(|buffer| buffer.index == plan.output.index) + else { + return false; + }; + let atomic_scatter = output.role == "InOut" + && ll.contains("@air.atomic.global.") + && declares_data_dependent_non_atomic_store_to_buffer(ll, plan.output.index); + let packed_loop_scatter = matches!(output.role.as_str(), "Output" | "InOut") + && !packed_loop_scatter_control_fields(ll).is_empty(); + atomic_scatter || packed_loop_scatter +} + fn incompatible_undefined_threadgroup_memory_golden(ll: &str, metal: &MetalRow) -> Option { if metal.compare == "none" || !declares_undefined_threadgroup_memory_read(ll) { return None; @@ -6037,18 +7443,37 @@ fn incompatible_overlapping_output_stride_golden(ll: &str, metal: &MetalRow) -> .is_some_and(|buffer| bounded_control_output_stride_too_small(buffer, *req)) }) .map(|req| { + let field = metal + .plan + .buffers + .iter() + .find(|buffer| buffer.index == req.buffer) + .and_then(|buffer| output_stride_offending_field(buffer, req)); + let field_detail = field.map_or_else( + || "unresolved field".into(), + |field| { + format!( + "field offset {} size {} value {}", + field.offset, + field.size, + field.value.unwrap_or(u64::from(BOUNDED_CONTROL_DIM)) + ) + }, + ); format!( "metal golden seeds output byte-stride/control buffer too small while replay stores \ - {} bytes per element to output buffer {output_index}; rebank Metal row \ - with non-overlapping output stride", - req.store_bytes + {} bytes per element to output buffer {output_index}; control buffer {} requires \ + at least {} bytes per row ({field_detail}); rebank Metal row with non-overlapping \ + output stride", + req.store_bytes, req.buffer, req.min_row_bytes, ) }) } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug)] struct OutputStrideRequirement { buffer: u32, + field_offset: Option, store_bytes: usize, min_row_bytes: u64, } @@ -6073,6 +7498,7 @@ fn output_stride_control_requirements( let mut ptr_buf: HashMap<&str, u32> = HashMap::new(); let mut pointer_roots: HashMap> = HashMap::new(); let mut pointer_offsets: HashMap> = HashMap::new(); + let mut pointer_control_fields: HashMap> = HashMap::new(); for arg in entry_function_args(ll) .into_iter() .flat_map(|args| args.split(',').enumerate()) @@ -6089,6 +7515,9 @@ fn output_stride_control_requirements( ptr_buf.insert(name, buf); pointer_roots.insert(name.to_string(), HashSet::from([buf])); pointer_offsets.insert(name.to_string(), HashSet::new()); + if stride_control_buffers.contains_key(&buf) { + pointer_control_fields.insert(name.to_string(), HashSet::from([(buf, 0)])); + } } if let Some(entry) = entry_name_from_ll(ll) { for (ord, name) in entry_arg_names(ll, &entry).into_iter().enumerate() { @@ -6098,11 +7527,17 @@ fn output_stride_control_requirements( pointer_roots .entry(name.clone()) .or_insert_with(|| HashSet::from([buf])); - pointer_offsets.entry(name).or_default(); + pointer_offsets.entry(name.clone()).or_default(); + if stride_control_buffers.contains_key(&buf) { + pointer_control_fields + .entry(name.clone()) + .or_insert_with(|| HashSet::from([(buf, 0)])); + } } } let mut value_sources: HashMap> = HashMap::new(); + let mut value_control_fields: HashMap> = HashMap::new(); let mut requirements = Vec::new(); for line in ll.lines() { let trimmed = line.trim_start(); @@ -6127,9 +7562,26 @@ fn output_stride_control_requirements( if !sources.is_empty() { value_sources.insert(reg.to_string(), sources.clone()); } + let mut control_fields = HashSet::new(); + if rhs.starts_with("load ") { + if let Some(ptr) = load_pointer_operand(rhs) { + if let Some(fields) = pointer_control_fields.get(ptr) { + control_fields.extend(fields.iter().copied()); + } + } + } + for operand in &operands { + if let Some(prev) = value_control_fields.get(*operand) { + control_fields.extend(prev.iter().copied()); + } + } + if !control_fields.is_empty() { + value_control_fields.insert(reg.to_string(), control_fields.clone()); + } let mut roots = HashSet::new(); let mut offsets = HashSet::new(); + let mut offset_fields = HashSet::new(); for operand in operands { if let Some(prev) = pointer_roots.get(operand) { roots.extend(prev.iter().copied()); @@ -6140,14 +7592,38 @@ fn output_stride_control_requirements( if let Some(prev) = value_sources.get(operand) { offsets.extend(prev.iter().copied()); } + if let Some(prev) = pointer_control_fields.get(operand) { + offset_fields.extend(prev.iter().copied()); + } + if let Some(prev) = value_control_fields.get(operand) { + offset_fields.extend(prev.iter().copied()); + } } if !roots.is_empty() && (rhs.contains("getelementptr") || rhs.starts_with("bitcast ") || rhs.starts_with("select ")) { + let roots_include_control = roots + .iter() + .any(|buffer| stride_control_buffers.contains_key(buffer)); pointer_roots.insert(reg.to_string(), roots); pointer_offsets.insert(reg.to_string(), offsets); + if rhs.contains("getelementptr") && roots_include_control { + if let Some(field_index) = trailing_const_i32_gep_index(rhs) { + offset_fields = offset_fields + .into_iter() + .filter_map(|(buffer, _)| { + let plan = stride_control_buffers.get(&buffer)?; + let offset = packed_u32_control_field_offset(plan, field_index)?; + Some((buffer, offset)) + }) + .collect(); + } + } + if !offset_fields.is_empty() { + pointer_control_fields.insert(reg.to_string(), offset_fields); + } } continue; } @@ -6170,11 +7646,30 @@ fn output_stride_control_requirements( if let Some(offsets) = pointer_offsets.get(ptr) { for buf in offsets { if stride_control_buffers.contains_key(buf) { - requirements.push(OutputStrideRequirement { - buffer: *buf, - store_bytes, - min_row_bytes: output_stride_min_row_bytes(store_bytes), - }); + let exact_fields = pointer_control_fields + .get(ptr) + .into_iter() + .flatten() + .filter(|(field_buffer, _)| field_buffer == buf) + .map(|(_, offset)| *offset) + .collect::>(); + if exact_fields.is_empty() { + requirements.push(OutputStrideRequirement { + buffer: *buf, + field_offset: None, + store_bytes, + min_row_bytes: output_stride_min_row_bytes(store_bytes), + }); + continue; + } + for field_offset in exact_fields { + requirements.push(OutputStrideRequirement { + buffer: *buf, + field_offset: Some(field_offset), + store_bytes, + min_row_bytes: output_stride_min_row_bytes(store_bytes), + }); + } } } } @@ -6186,12 +7681,42 @@ fn output_stride_min_row_bytes(store_bytes: usize) -> u64 { u64::from(BOUNDED_CONTROL_DIM).saturating_mul(store_bytes as u64) } +fn packed_u32_control_field_offset(buffer: &PlanBuffer, field_index: u64) -> Option { + let field_index = usize::try_from(field_index).ok()?; + let field_offset = field_index.checked_mul(4)?; + if !buffer + .seed_layout + .iter() + .any(|field| field.offset == field_offset && field.size == 4) + { + return None; + } + if buffer + .seed_layout + .iter() + .any(|field| field.offset < field_offset && field.offset % 4 == 0 && field.size != 4) + { + return None; + } + Some(field_offset) +} + fn bounded_control_output_stride_too_small( buffer: &PlanBuffer, req: OutputStrideRequirement, ) -> bool { - buffer.seed_layout.iter().any(|field| { - bounded_control_seed_field_is_within_buffer(buffer.len, field) + output_stride_offending_field(buffer, req).is_some() +} + +fn output_stride_offending_field( + buffer: &PlanBuffer, + req: OutputStrideRequirement, +) -> Option<&ControlSeedField> { + buffer.seed_layout.iter().find(|field| { + req.field_offset.is_none_or(|offset| field.offset == offset) + && bounded_control_seed_field_is_within_buffer(buffer.len, field) + && control_seed_field_max_value(field.size) + .is_some_and(|max_value| req.min_row_bytes <= max_value) && field.value.unwrap_or(u64::from(BOUNDED_CONTROL_DIM)) < req.min_row_bytes }) } @@ -7148,6 +8673,13 @@ fn incompatible_float_output_golden(ll: &str, metal: &MetalRow) -> Option bool { + let format = current_output_format_for_plan(ll, &metal.plan.output) + .and_then(|format| parse_format(format).ok()) + .or_else(|| parse_format(&metal.plan.output.format).ok()); + format.is_some_and(|format| tolerance_for_metal_context(format, Some(ll), metal).is_some()) +} + fn incompatible_finite_struct_half_fragment_golden(ll: &str, metal: &MetalRow) -> Option { if metal.compare == "none" || metal.stage.as_deref() != Some("Fragment") @@ -7163,6 +8695,9 @@ fn incompatible_finite_struct_half_fragment_golden(ll: &str, metal: &MetalRow) - if !has_finite_struct_input { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden feeds finite_struct_float synthetic data through AIR fast half division before \ float render-target output; Metal/Vulkan half division and rounding are not a portable \ @@ -7212,29 +8747,6 @@ fn incompatible_moltenvk_vertex_clip_distance_half_texture_golden( ) } -fn incompatible_moltenvk_sampled_half_render_target_exact_golden( - ll: &str, - metal: &MetalRow, -) -> Option { - if metal.compare == "none" - || metal.stage.as_deref() != Some("Fragment") - || metal.plan.output.kind != "render_target" - || !ll_has_fast_no_nans_float_semantics(ll) - || !(ll.contains("@air.sample_texture") || ll.contains("@air.gather_texture")) - || !sampled_finite_half_texture(ll) - || !float_texture_or_render_target_output(ll, metal) - { - return None; - } - Some( - "metal golden samples synthetic finite f16 texture data before a float fragment \ - render-target output under AIR fast/no-nans math; MoltenVK exact byte comparison is not a \ - portable oracle for half texture filtering and render-target rounding in this seed; \ - rebank or drop the Metal row" - .into(), - ) -} - fn incompatible_moltenvk_half_texture_output_exact_golden( ll: &str, metal: &MetalRow, @@ -7252,6 +8764,9 @@ fn incompatible_moltenvk_half_texture_output_exact_golden( { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden samples or reads synthetic finite f16 texture data before a float texture \ output under AIR fast/no-nans math; MoltenVK exact byte comparison is not a portable \ @@ -7276,6 +8791,9 @@ fn incompatible_moltenvk_storage_f32_texture_output_exact_golden( { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden reads synthetic finite f32 storage texture data through AIR fast/no-nans \ math before float texture output; MoltenVK exact byte comparison is not a portable oracle \ @@ -7333,6 +8851,9 @@ fn incompatible_moltenvk_fast_f32_input_buffer_exact_golden( if !format.is_float_like() { return None; } + if tolerance_for_metal_context(format, Some(ll), metal).is_some() { + return None; + } let finite_f32_inputs = metal .plan .buffers @@ -7378,6 +8899,9 @@ fn incompatible_moltenvk_fast_half_buffer_output_exact_golden( ) { return None; } + if tolerance_for_metal_context(format, Some(ll), metal).is_some() { + return None; + } Some( "metal golden writes finite f16 buffer output through AIR fast/no-nans approximate math; \ MoltenVK exact byte comparison is not a portable oracle for half conversion, denorm \ @@ -7400,6 +8924,9 @@ fn incompatible_moltenvk_sampled_f32_render_target_exact_golden( { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden samples synthetic finite f32 texture data before a float fragment \ render-target output under AIR fast/no-nans math; MoltenVK exact byte comparison is not a \ @@ -7427,6 +8954,9 @@ fn incompatible_moltenvk_fast_f32_buffer_output_exact_golden( if !format.is_float_like() { return None; } + if tolerance_for_metal_context(format, Some(ll), metal).is_some() { + return None; + } let has_finite_f32_output = metal.plan.buffers.iter().any(|buffer| { matches!(buffer.role.as_str(), "InOut" | "Output") && buffer.seed_mode == SEED_MODE_FINITE_FLOAT32 @@ -7449,27 +8979,6 @@ fn incompatible_moltenvk_fast_f32_buffer_output_exact_golden( ) } -fn incompatible_moltenvk_fast_raw_float_buffer_output_exact_golden( - ll: &str, - metal: &MetalRow, -) -> Option { - if metal.compare == "none" - || metal.stage.as_deref() != Some("Kernel") - || metal.plan.output.kind != "buffer" - || metal.plan.output.format != "RawBytes" - || !ll_has_fast_no_nans_float_semantics(ll) - || !raw_buffer_writes_float_derived_bytes(ll) - { - return None; - } - Some( - "metal golden compares raw buffer bytes written from AIR fast/no-nans float values; \ - MoltenVK exact byte comparison is not a portable oracle for float denorm flushing, \ - signed-zero handling, and raw padding bytes in this seed; rebank or drop the Metal row" - .into(), - ) -} - fn incompatible_moltenvk_fast_half_render_target_exact_golden( ll: &str, metal: &MetalRow, @@ -7488,6 +8997,9 @@ fn incompatible_moltenvk_fast_half_render_target_exact_golden( if !matches!(format, DataFormat::Rgba16Float | DataFormat::Rgba32Float) { return None; } + if tolerance_for_metal_context(format, Some(ll), metal).is_some() { + return None; + } Some( "metal golden writes a float fragment render target through AIR fast_sqrt under \ fast/no-nans math; MoltenVK exact byte comparison is not a portable oracle for \ @@ -7612,9 +9124,22 @@ fn writes_f32_texture_output(ll: &str) -> bool { || ll.contains("@air.write_imageblock_slice_to_texture_") && ll.contains("f32") } +#[cfg(test)] fn raw_buffer_writes_float_derived_bytes(ll: &str) -> bool { ll.contains("store float ") - || ll.contains("store <") + || ll.contains("store half ") + || ll.contains("store double ") + || ll.lines().any(|line| { + let Some(vector) = line.trim_start().strip_prefix("store <") else { + return false; + }; + let Some(element_type) = vector.split('>').next() else { + return false; + }; + ["half", "float", "double", "bfloat"] + .iter() + .any(|scalar| element_type.split_whitespace().last() == Some(*scalar)) + }) || ll.lines().any(|line| { line.contains("@air.pack.") && (line.contains("f16") || line.contains("f32")) }) @@ -7647,6 +9172,16 @@ fn static_normalized_linear_sampler(ll: &str) -> bool { .any(air_sampler_word_is_normalized_linear) } +fn static_pixel_bicubic_sampler(ll: &str) -> bool { + ll.lines() + .filter(|line| line.contains("@__air_sampler_state") && line.contains(" constant ")) + .filter_map(first_i64_literal) + .any(|word| { + let word = word as u64; + ((word >> 11) & 0x3) == 2 && ((word >> 9) & 0x3) == 2 && word & 0x8000 != 0 + }) +} + fn air_sampler_word_is_normalized_linear(word: i64) -> bool { let word = word as u64; let min_linear = ((word >> 11) & 0x3) == 1; @@ -7678,6 +9213,9 @@ fn incompatible_sampled_half_domain_sensitive_texture_golden( { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden samples synthetic finite f16 texture data through AIR fast/no-nans \ domain-sensitive math before float texture output; Metal/Vulkan texture sampling, \ @@ -7717,6 +9255,9 @@ fn incompatible_sampled_half_linear_filter_texture_golden( { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } if ll.contains("@air.gather_texture_2d.v4f16") && ll.contains("@air.imageblock_data") && ll.contains("@air.write_imageblock_slice_to_texture_2d") @@ -7930,6 +9471,9 @@ fn incompatible_sampled_fast_pow_texture_golden(ll: &str, metal: &MetalRow) -> O if !has_signed_sampled_f32_texture { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden samples synthetic finite f32 texture data through AIR fast_pow/fast_powr \ under fast/no-nans math; Metal/Vulkan linear sampling and approximate pow rounding are \ @@ -7978,6 +9522,9 @@ fn incompatible_sampled_f32_domain_math_texture_golden( { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden samples synthetic finite f32 texture data through AIR fast/no-nans \ domain-sensitive math before float output; Metal/Vulkan texture sampling and approximate \ @@ -8058,6 +9605,9 @@ fn incompatible_sampled_f32_dynamic_lod_render_target_golden( if sampled_f32_count < 2 || !declares_dynamic_lod_sample(ll) { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden samples synthetic finite f32 texture data from generated fragment coordinates \ with dynamic LOD before float render-target output; Metal/Vulkan sampling, LOD selection, \ @@ -8173,6 +9723,9 @@ fn incompatible_fragment_fast_pow_rsqrt_render_target_golden( { return None; } + if metal_output_has_numeric_tolerance(ll, metal) { + return None; + } Some( "metal golden writes a float fragment render target through AIR fast_pow and fast_rsqrt \ under fast/no-nans math; approximate reciprocal-square-root, pow, and reassociation \ @@ -8484,6 +10037,12 @@ fn incompatible_sampled_f32_texture_output_golden(ll: &str, metal: &MetalRow) -> { return None; } + let format = current_output_format_for_plan(ll, &metal.plan.output) + .and_then(|format| parse_format(format).ok()) + .or_else(|| parse_format(&metal.plan.output.format).ok())?; + if tolerance_for_metal_context(format, Some(ll), metal).is_some() { + return None; + } Some( "metal golden samples synthetic finite f32 texture data into f32 texture output; \ Metal/Vulkan sampling and texture write rounding are not an exact byte oracle for this \ @@ -8734,7 +10293,9 @@ pub fn compare_candidate_to_metal( if let Some(result) = compare_finite_struct_float_raw_bytes(candidate, &golden, metal, format, ll) { - if metal.compare == "none" && result.status != "ok" { + if metal.compare == "none" + && !matches!(result.status.as_str(), "ok" | "tolerance") + { return ("smoke".to_string(), result.observed, result.tolerance); } return (result.status, result.observed, result.tolerance); @@ -8742,7 +10303,9 @@ pub fn compare_candidate_to_metal( if let Some(result) = compare_finite_bfloat_raw_bytes(candidate, &golden, metal, format) { - if metal.compare == "none" && result.status != "ok" { + if metal.compare == "none" + && !matches!(result.status.as_str(), "ok" | "tolerance") + { return ("smoke".to_string(), result.observed, result.tolerance); } return (result.status, result.observed, result.tolerance); @@ -8757,7 +10320,8 @@ pub fn compare_candidate_to_metal( max_ulp: None, }); } - if metal.compare == "none" && result.status != "ok" { + if metal.compare == "none" && !matches!(result.status.as_str(), "ok" | "tolerance") + { return ("smoke".to_string(), result.observed, result.tolerance); } return (result.status, result.observed, result.tolerance); @@ -8809,19 +10373,12 @@ fn enforce_backend_compare_policy( status: &mut String, error: &mut Option, ) { - if backend != RunBackend::MoltenVk || status == "ok" { + if backend != RunBackend::MoltenVk || status != "smoke" { return; } - if status == "tolerance" { - *status = "failure".into(); - if error.is_none() { - *error = Some("MoltenVK output differs from Metal; exact byte match required".into()); - } - } else if status == "smoke" { - *status = "failure".into(); - if error.is_none() { - *error = Some("MoltenVK compare=none smoke row is not an exact Metal match".into()); - } + *status = "failure".into(); + if error.is_none() { + *error = Some("MoltenVK compare=none smoke row has no semantic Metal golden".into()); } } @@ -9298,6 +10855,9 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { if cfg.compile_missing { eprintln!("# compile-missing"); } + if cfg.preflight_only { + eprintln!("# preflight-only (no GPU submission; ledger unchanged)"); + } let translate = load_translate_rows(&cfg.translate_ledger, cfg.backend); let only_air_set = cfg @@ -9319,7 +10879,23 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { } else { load_tech_keys(&cfg.tech_ledger) }; - let metal_rows = load_metal_rows(&cfg.metal_ledger); + let explicitly_requested_metal_rows = cfg + .only_air + .iter() + .cloned() + .chain( + only_air_set + .iter() + .flat_map(|hashes| hashes.iter().cloned()), + ) + .collect::>(); + let mut metal_rows = if cfg.backend == RunBackend::Metal { + HashMap::new() + } else if explicitly_requested_metal_rows.is_empty() { + load_metal_rows(&cfg.metal_ledger) + } else { + load_metal_rows_for_hashes(&cfg.metal_ledger, Some(&explicitly_requested_metal_rows)) + }; let moltenvk_rows = if cfg.backend == RunBackend::Vulkan { load_candidate_rows(&cfg.corpus_dir.join(RunBackend::MoltenVk.ledger_file_name())) } else { @@ -9339,6 +10915,13 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { }) .filter(|r| { if tech_row_filters { + if cfg.backend != RunBackend::Metal + && cfg.contains.as_deref() == Some("metal status=quarantine") + { + return metal_rows + .get(&r.air_sha256) + .is_some_and(|metal| metal.status == "quarantine"); + } return existing_rows .get(&r.air_sha256) .is_some_and(|row| tech_row_selected(cfg, row)); @@ -9347,6 +10930,73 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { }) .collect(); todo.sort_by(|a, b| a.label.cmp(&b.label)); + if cfg.backend == RunBackend::Metal { + let wanted = todo + .iter() + .map(|row| row.air_sha256.clone()) + .collect::>(); + metal_rows = load_metal_rows_for_hashes(&cfg.metal_ledger, Some(&wanted)); + } + if cfg.backend == RunBackend::Metal && cfg.preflight_only && !cfg.oneshot && !todo.is_empty() { + let before = todo.len(); + let wanted = todo + .iter() + .map(|row| row.air_sha256.clone()) + .collect::>(); + let source_refs = crate::corpus_shards::gather_source_refs_for_hashes( + &cfg.public_dir, + &cfg.local_corpus, + &wanted, + ) + .into_iter() + .map(|source| (source.air_sha256.clone(), source)) + .collect::>(); + let selected = std::sync::Mutex::new(Vec::new()); + // A single large AIR module can require hundreds of MiB while its full reachable CFG is + // parsed. Bound this phase independently from Apple-tool execution so an eight-core scan + // cannot multiply that peak past the host's memory limit. + let workers = 1; + let chunk_size = todo.len().div_ceil(workers); + std::thread::scope(|scope| { + for chunk in todo.chunks(chunk_size) { + let selected = &selected; + let source_refs = &source_refs; + let metal_rows = &metal_rows; + let local_corpus = &cfg.local_corpus; + scope.spawn(move || { + let mut local = Vec::new(); + for row in chunk { + if source_may_have_semantic_metal_preflight( + row, + metal_rows, + source_refs, + local_corpus, + ) { + local.push(row.clone()); + } + } + selected + .lock() + .expect("preflight source-filter mutex poisoned") + .extend(local); + }); + } + }); + todo = selected + .into_inner() + .expect("preflight source-filter mutex poisoned"); + todo.sort_by(|a, b| a.label.cmp(&b.label)); + // The parent needed historic plans only to derive loop/input facts. Some plans contain + // very large seed-layout vectors; retaining every selected quarantine row while Apple PSO + // children start can push an otherwise small preflight over the host memory limit. Each + // oneshot worker reloads its single row, so release the parent copies before spawning. + metal_rows.clear(); + metal_rows.shrink_to_fit(); + eprintln!( + "# preflight source-cycle filter: {before} → {} Apple-tool candidates", + todo.len() + ); + } let unbounded_todo_len = todo.len(); if cfg.skip > 0 { if cfg.skip >= todo.len() { @@ -9407,6 +11057,7 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { // Oneshot worker: run in-process (parent applies the wall timeout around this process). if cfg.oneshot { + install_oneshot_parent_watchdog(); let row = &todo[0]; let outcome = process_one(cfg, row, &metal_rows, &moltenvk_rows); eprintln!( @@ -9422,6 +11073,80 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { }; } + // Bulk reclassification of historic smoke rows is ledger-only. Spawning a worker per row + // would repeatedly load the large corpus ledgers and, more importantly, creates an accidental + // path back to GPU submission if the worker logic changes. Keep this parent-side and explicit. + if should_reclassify_historic_compare_none_without_source(cfg) + && todo.iter().all(|row| { + metal_rows + .get(&row.air_sha256) + .is_some_and(|metal| metal.compare == "none") + }) + { + let delta_ledger = run_delta_path(cfg); + let _ = fs::remove_file(&delta_ledger); + for row in &todo { + let metal = metal_rows + .get(&row.air_sha256) + .expect("bulk compare=none classification checked every row"); + if let Err(error) = + append_jsonl_delta_row(&delta_ledger, &historic_compare_none_quarantine_row(metal)) + { + eprintln!("# RESULT: failed to write bulk quarantine delta: {error}"); + return 1; + } + } + let merged = match merge_delta_into_ledger(&cfg.tech_ledger, &delta_ledger) { + Ok(merged) => merged, + Err(error) => { + eprintln!("# RESULT: failed to merge bulk quarantine delta: {error}"); + return 1; + } + }; + let _ = fs::remove_file(&delta_ledger); + eprintln!( + "# RESULT: ok=0 fail={} skip=0 timeout=0 merged_delta={merged} → {}", + todo.len(), + cfg.tech_ledger.display() + ); + return 1; + } + + if cfg.backend != RunBackend::Metal + && !cfg.compile_missing + && todo.iter().all(|row| { + metal_rows + .get(&row.air_sha256) + .is_some_and(|metal| metal.status == "quarantine") + }) + { + let delta_ledger = run_delta_path(cfg); + let _ = fs::remove_file(&delta_ledger); + for row in &todo { + if let Err(error) = append_jsonl_delta_row( + &delta_ledger, + &candidate_metal_quarantine_row(cfg.backend, row), + ) { + eprintln!("# RESULT: failed to write candidate quarantine delta: {error}"); + return 1; + } + } + let merged = match merge_delta_into_ledger(&cfg.tech_ledger, &delta_ledger) { + Ok(merged) => merged, + Err(error) => { + eprintln!("# RESULT: failed to merge candidate quarantine delta: {error}"); + return 1; + } + }; + let _ = fs::remove_file(&delta_ledger); + eprintln!( + "# RESULT: ok=0 fail=0 skip={} timeout=0 merged_delta={merged} → {}", + todo.len(), + cfg.tech_ledger.display() + ); + return 0; + } + // Parent owns the worker process groups. Ctrl-C / SIGTERM must SIGKILL them — workers // are started with process_group(0), so the terminal does not forward SIGINT to them. install_worker_signal_handlers(); @@ -9442,6 +11167,7 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { let n_skip = AtomicUsize::new(0); let n_timeout = AtomicUsize::new(0); let done = AtomicUsize::new(0); + let preflight_safe = std::sync::Mutex::new(Vec::::new()); let chunk_size = n_total.div_ceil(workers); eprintln!( @@ -9457,12 +11183,19 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { let n_skip = &n_skip; let n_timeout = &n_timeout; let done = &done; + let preflight_safe = &preflight_safe; scope.spawn(move || { for row in chunk { let outcome = run_case_subprocess(run_cfg, row); match outcome { ProcessOutcome::Ok => { n_ok.fetch_add(1, Ordering::Relaxed); + if cfg.preflight_only { + preflight_safe + .lock() + .expect("preflight safe-list mutex poisoned") + .push(row.air_sha256.clone()); + } } ProcessOutcome::Fail => { n_fail.fetch_add(1, Ordering::Relaxed); @@ -9492,7 +11225,44 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { } }); + if let Some(path) = cfg.preflight_safe_list.as_deref() { + let mut hashes = preflight_safe + .into_inner() + .expect("preflight safe-list mutex poisoned"); + hashes.sort_unstable(); + let mut text = hashes.join("\n"); + if !text.is_empty() { + text.push('\n'); + } + if let Err(error) = fs::write(path, text) { + eprintln!( + "# RESULT: failed to write preflight safe list {}: {error}", + path.display() + ); + return 1; + } + eprintln!( + "# preflight-safe-list {} rows={}", + path.display(), + hashes.len() + ); + } + let timeouts = n_timeout.load(Ordering::Relaxed); + if cfg.preflight_only { + let _ = fs::remove_file(&delta_ledger); + eprintln!( + "# RESULT: ok={} fail={} skip={} timeout={timeouts} merged_delta=0 (preflight; ledger unchanged)", + n_ok.load(Ordering::Relaxed), + n_fail.load(Ordering::Relaxed), + n_skip.load(Ordering::Relaxed), + ); + return if n_fail.load(Ordering::Relaxed) > 0 || timeouts > 0 { + 1 + } else { + 0 + }; + } let merged = match merge_delta_into_ledger(&cfg.tech_ledger, &delta_ledger) { Ok(n) => { let _ = fs::remove_file(&delta_ledger); @@ -9521,6 +11291,39 @@ pub fn run_driver(cfg: &RunConfig) -> i32 { } } +fn source_may_have_semantic_metal_preflight( + row: &TranslateRow, + metal_rows: &HashMap, + source_refs: &HashMap, + local_corpus: &Path, +) -> bool { + let Some(source_ref) = source_refs.get(&row.air_sha256) else { + return false; + }; + let Ok(source) = source_ref.load(local_corpus) else { + return false; + }; + let ll = metal2vulkan::tools::sanitize_ll_text_with_datalayout(&source.air_ll).0; + let Some(entry) = entry_name_from_ll(&ll) else { + return false; + }; + if invalid_standalone_metal_oracle_reason(&ll).is_some() + || unsafe_metal_submission_reason(&ll).is_some() + { + return false; + } + let (plan, fc_values) = metal_oracle_inputs(&ll, metal_rows.get(&row.air_sha256)); + let facts = loop_input_facts_for_plan(&ll, &entry, &plan, fc_values); + matches!( + crate::loop_budget::reachable_module_has_cfg_cycle_with_loop_input_facts( + &ll, + &entry, + facts.as_loop_input_facts(), + ), + Ok(false) + ) +} + fn run_delta_path(cfg: &RunConfig) -> PathBuf { let file = format!( "m2v-{}-{}-{}.delta.jsonl", @@ -9568,6 +11371,10 @@ fn should_skip_existing_metal_compare_none(cfg: &RunConfig, row: &MetalRow) -> b !cfg.force && row.status == "ok" && row.compare == "none" } +fn should_reclassify_historic_compare_none_without_source(cfg: &RunConfig) -> bool { + cfg.backend == RunBackend::Metal && !cfg.preflight_only && !cfg.remint_compare_none +} + /// Spawn this binary in `--oneshot` mode for one hash; kill after `timeout_secs`. fn run_case_subprocess(cfg: &RunConfig, row: &TranslateRow) -> ProcessOutcome { use std::process::{Command, Stdio}; @@ -9602,6 +11409,12 @@ fn run_case_subprocess(cfg: &RunConfig, row: &TranslateRow) -> ProcessOutcome { if cfg.compile_missing { cmd.arg("--compile-missing"); } + if cfg.preflight_only { + cmd.arg("--preflight-only"); + } + if cfg.remint_compare_none { + cmd.arg("--remint-compare-none"); + } // New process group so a timeout / Ctrl-C can kill metal-as / helper descendants. #[cfg(unix)] { @@ -9671,16 +11484,25 @@ fn run_case_subprocess(cfg: &RunConfig, row: &TranslateRow) -> ProcessOutcome { "# SLOW {} timed out after {}s", row.air_sha256, cfg.timeout_secs ); - // Honest warning: SIGKILL frees the CPU worker but cannot cancel an in-flight GPU - // kernel. The pre-submission loop-budget guard should make this unreachable for a - // GPU loop; reaching it means either a CPU-side tool hang or (if the machine is - // unresponsive) a wedged GPU that only a reboot recovers. - eprintln!( - "# WARN {} exceeded {}s — killing the CPU worker, but a committed Metal kernel \ - cannot be cancelled. If the machine is unresponsive, the GPU is wedged and a \ - reboot is the only recovery.", - row.air_sha256, cfg.timeout_secs - ); + if cfg.backend == RunBackend::Metal { + // Honest warning: SIGKILL frees the CPU worker but cannot cancel an in-flight + // Metal kernel. The pre-submission loop-budget guard should make this + // unreachable for a GPU loop; reaching it means either a CPU-side tool hang or + // (if the machine is unresponsive) a wedged GPU that only a reboot recovers. + eprintln!( + "# WARN {} exceeded {}s — killing the CPU worker, but a committed Metal \ + kernel cannot be cancelled. If the machine is unresponsive, the GPU is \ + wedged and a reboot is the only recovery.", + row.air_sha256, cfg.timeout_secs + ); + } else { + eprintln!( + "# WARN {} exceeded {}s — killing the {} worker process group", + row.air_sha256, + cfg.timeout_secs, + cfg.backend.program_name() + ); + } kill_worker(&mut child); let _ = child.wait(); write_timeout_or_error_row( @@ -9691,6 +11513,33 @@ fn run_case_subprocess(cfg: &RunConfig, row: &TranslateRow) -> ProcessOutcome { ); return ProcessOutcome::Timeout; } + #[cfg(target_os = "macos")] + Ok(None) + if cfg.preflight_only + && macos_process_resident_bytes(child.id()) + .is_some_and(|rss| rss > PREFLIGHT_WORKER_MAX_RESIDENT_BYTES) => + { + let rss = macos_process_resident_bytes(child.id()).unwrap_or(0); + eprintln!( + "# WARN {} Metal PSO preflight exceeded resident-memory ceiling: {} MiB > {} MiB", + row.air_sha256, + rss / (1024 * 1024), + PREFLIGHT_WORKER_MAX_RESIDENT_BYTES / (1024 * 1024), + ); + kill_worker(&mut child); + let _ = child.wait(); + write_timeout_or_error_row( + cfg, + row, + &format!( + "Metal PSO preflight exceeded resident-memory ceiling ({} MiB > {} MiB)", + rss / (1024 * 1024), + PREFLIGHT_WORKER_MAX_RESIDENT_BYTES / (1024 * 1024), + ), + "fallback", + ); + return ProcessOutcome::Fail; + } Ok(None) => { if !logged_slow && start.elapsed() >= slow_after { logged_slow = true; @@ -9711,6 +11560,54 @@ fn run_case_subprocess(cfg: &RunConfig, row: &TranslateRow) -> ProcessOutcome { } } +#[cfg(target_os = "macos")] +fn macos_process_resident_bytes(pid: u32) -> Option { + let mut info = std::mem::MaybeUninit::::zeroed(); + let size = std::mem::size_of::(); + // SAFETY: `info` points to `size` writable bytes and PROC_PIDTASKINFO initializes that exact + // structure on success. The queried pid is a live child owned by this process. + let written = unsafe { + libc::proc_pidinfo( + pid as libc::c_int, + libc::PROC_PIDTASKINFO, + 0, + info.as_mut_ptr().cast(), + size as libc::c_int, + ) + }; + if written != size as libc::c_int { + return None; + } + // SAFETY: the successful call above initialized the complete structure. + Some(unsafe { info.assume_init() }.pti_resident_size) +} + +fn install_oneshot_parent_watchdog() { + #[cfg(unix)] + { + // The parent normally owns timeout and signal cleanup. If macOS kills that small process + // under memory pressure, an Apple compiler call can otherwise continue as a multi-GiB + // orphan. The worker was spawned as its own process-group leader, so it can safely kill + // itself and every helper descendant when it is reparented. + let original_parent = unsafe { libc::getppid() }; + let own_pid = unsafe { libc::getpid() }; + std::thread::spawn(move || loop { + std::thread::sleep(std::time::Duration::from_millis(100)); + if unsafe { libc::getppid() } == original_parent { + continue; + } + unsafe { + if libc::getpgrp() == own_pid { + libc::kill(-own_pid, libc::SIGKILL); + } else { + libc::kill(own_pid, libc::SIGKILL); + } + } + break; + }); + } +} + fn worker_exit_error(status: std::process::ExitStatus) -> Option { if status.code() == Some(1) { return None; @@ -9895,7 +11792,7 @@ enum ProcessOutcome { } fn candidate_metal_status_precheck( - backend: RunBackend, + _backend: RunBackend, metal: &MetalRow, ) -> Option<(&'static str, String, ProcessOutcome)> { if metal.status == "quarantine" { @@ -9912,13 +11809,6 @@ fn candidate_metal_status_precheck( ProcessOutcome::Skip, )); } - if backend == RunBackend::MoltenVk && metal.compare == "none" { - return Some(( - "missing", - "metal golden compare=none is not a full semantic golden; rebank Metal row".into(), - ProcessOutcome::Skip, - )); - } None } @@ -10126,6 +12016,23 @@ fn process_one( metal_rows: &HashMap, moltenvk_rows: &HashMap, ) -> ProcessOutcome { + if should_reclassify_historic_compare_none_without_source(cfg) { + if let Some(metal) = metal_rows + .get(&tr.air_sha256) + .filter(|metal| metal.compare == "none") + { + // This is a ledger classification, not an oracle execution. Avoid resolving and + // re-inferring the source entirely: historic compare=none bytes are non-semantic by + // definition, and bulk resubmission has no safe way to promote them. A targeted remint + // starts from the source later with an explicitly reviewed plan. + let row = historic_compare_none_quarantine_row(metal); + if let Err(error) = append_result_row(cfg, &row) { + eprintln!(" write ledger: {error}"); + } + return ProcessOutcome::Fail; + } + } + let Some(src) = resolve_source( &tr.air_sha256, &tr.label, @@ -10160,6 +12067,44 @@ fn process_one( } } let (plan, fc_values) = metal_oracle_inputs(&ll, metal_rows.get(&tr.air_sha256)); + if let Some(reason) = invalid_standalone_metal_oracle_reason(&ll) { + if cfg.preflight_only { + eprintln!(" preflight refused before Metal PSO creation: {reason}"); + } else { + write_quarantine_row(cfg, tr, &src, &plan, stage, &entry, reason); + } + return ProcessOutcome::Fail; + } + if let Some(reason) = unsafe_metal_submission_reason(&ll) { + if cfg.preflight_only { + eprintln!(" preflight refused before Metal PSO creation: {reason}"); + } else { + write_quarantine_row(cfg, tr, &src, &plan, stage, &entry, reason); + } + return ProcessOutcome::Fail; + } + if cfg.preflight_only { + let facts = loop_input_facts_for_plan(&ll, &entry, &plan, fc_values.clone()); + match crate::loop_budget::reachable_module_has_cfg_cycle_with_loop_input_facts( + &ll, + &entry, + facts.as_loop_input_facts(), + ) { + Ok(true) => { + eprintln!( + " preflight skipped before Apple tools: source has a reachable CFG cycle" + ); + return ProcessOutcome::Skip; + } + Err(reason) => { + eprintln!( + " preflight skipped before Apple tools: source CFG analysis refused: {reason}" + ); + return ProcessOutcome::Skip; + } + Ok(false) => {} + } + } return run_metal(cfg, tr, &src, &ll, stage, &entry, &plan, &fc_values); } @@ -10168,6 +12113,7 @@ fn process_one( // skipped/not-comparable case in the parent runner. macro_rules! write_missing_candidate_and_skip { ($metal:expr, $golden:expr, $reason:expr) => {{ + let reason: String = ($reason).into(); if let Some(outcome) = try_run_vulkan_for_skipped_metal_compare( cfg, tr, @@ -10177,16 +12123,14 @@ fn process_one( &entry, $metal, moltenvk_rows, - &$reason, + &reason, ) { return outcome; } if cfg.compile_missing { - return compile_missing_candidate_smoke( - cfg, tr, &src, &ll, stage, $golden, $reason, - ); + return compile_missing_candidate_smoke(cfg, tr, &src, &ll, stage, $golden, reason); } - let row = candidate_status_row(cfg, tr, &src, "missing", $golden, Some($reason)); + let row = candidate_status_row(cfg, tr, &src, "missing", $golden, Some(reason)); let _ = append_result_row(cfg, &row); return ProcessOutcome::Skip; }}; @@ -10223,10 +12167,21 @@ fn process_one( let _ = append_result_row(cfg, &row); return outcome; } - if let Some(reason) = incompatible_function_constant_golden(&ll, metal) { - write_missing_candidate_and_skip!(metal, metal.output_sha256.clone(), reason); + if let Some(reason) = unsafe_metal_submission_reason(&ll) { + write_missing_candidate_and_skip!( + metal, + metal.output_sha256.clone(), + format!("metal golden is not a defined oracle: {reason}") + ); } - if let Some(reason) = incompatible_function_constant_texture_array_ref_golden(&ll, metal) { + if let Some(reason) = invalid_standalone_metal_oracle_reason(&ll) { + write_missing_candidate_and_skip!( + metal, + metal.output_sha256.clone(), + format!("metal golden is not a defined oracle: {reason}") + ); + } + if let Some(reason) = incompatible_function_constant_golden(&ll, metal) { write_missing_candidate_and_skip!(metal, metal.output_sha256.clone(), reason); } if let Some(reason) = incompatible_function_constant_private_pointer_table_golden(&ll, metal) { @@ -10304,11 +12259,6 @@ fn process_one( { write_missing_candidate_and_skip!(metal, metal.output_sha256.clone(), reason); } - if let Some(reason) = - incompatible_moltenvk_sampled_half_render_target_exact_golden(&ll, metal) - { - write_missing_candidate_and_skip!(metal, metal.output_sha256.clone(), reason); - } if let Some(reason) = incompatible_moltenvk_half_texture_output_exact_golden(&ll, metal) { write_missing_candidate_and_skip!(metal, metal.output_sha256.clone(), reason); } @@ -10326,11 +12276,6 @@ fn process_one( { write_missing_candidate_and_skip!(metal, metal.output_sha256.clone(), reason); } - if let Some(reason) = - incompatible_moltenvk_fast_raw_float_buffer_output_exact_golden(&ll, metal) - { - write_missing_candidate_and_skip!(metal, metal.output_sha256.clone(), reason); - } if let Some(reason) = incompatible_moltenvk_sampled_f32_cube_buffer_exact_golden(&ll, metal) { write_missing_candidate_and_skip!(metal, metal.output_sha256.clone(), reason); @@ -10462,16 +12407,60 @@ fn process_one( if let Some(reason) = incompatible_undefined_threadgroup_memory_golden(&ll, metal) { write_missing_candidate_and_skip!(metal, metal.output_sha256.clone(), reason); } + if metal.compare == "none" { + write_missing_candidate_and_skip!( + metal, + metal.output_sha256.clone(), + "metal golden compare=none is bounded smoke output, not a semantic oracle; rebank or \ + quarantine the Metal row" + ); + } let plan = metal.plan.clone(); run_candidate(cfg, tr, &src, &ll, stage, &entry, &plan, metal, None, None) } +fn historic_compare_none_quarantine_row(metal: &MetalRow) -> MetalRow { + let mut row = metal.clone(); + row.status = "quarantine".into(); + row.output_sha256 = None; + row.output_b64 = None; + row.error = Some( + "quarantined: historic compare=none row is bounded smoke, not a semantic Metal oracle; \ + targeted remint required" + .into(), + ); + row +} + +fn candidate_metal_quarantine_row(backend: RunBackend, tr: &TranslateRow) -> CandidateRow { + CandidateRow { + air_sha256: tr.air_sha256.clone(), + shard: tr.shard.clone(), + label: tr.label.clone(), + status: "quarantine".into(), + backend: backend.as_str().into(), + output_sha256: None, + output_b64: None, + golden_output_sha256: None, + spv_sha256: tr.spv_sha256.clone(), + tolerance: None, + observed: None, + error: Some("metal status=quarantine".into()), + } +} + fn write_failure_row(cfg: &RunConfig, tr: &TranslateRow, src: &SourceFile, err: &str) { append_status_row(cfg, tr, src, "fallback", "full", None, err.into()); } fn metal_oracle_inputs(ll: &str, metal: Option<&MetalRow>) -> (HarnessPlan, Vec<(usize, u64)>) { - let current_plan = infer_plan(ll); + let mut current_plan = infer_plan(ll); + if current_plan.dispatch_grid.iter().any(|&n| n > 1) + && requires_serial_dynamic_buffer_scatter_plan(ll, ¤t_plan) + { + current_plan.dispatch_grid = [1, 1, 1]; + current_plan.dispatch_tg = [1, 1, 1]; + } let plan = metal .and_then(banked_explicit_input_plan) .unwrap_or(current_plan); @@ -10481,6 +12470,13 @@ fn metal_oracle_inputs(ll: &str, metal: Option<&MetalRow>) -> (HarnessPlan, Vec< (plan, fc_values) } +fn oracle_input_specialization(ll: &str, plan: &HarnessPlan) -> Option { + (requires_serial_dynamic_buffer_scatter_plan(ll, plan) + && plan.dispatch_grid == [1, 1, 1] + && plan.dispatch_tg == [1, 1, 1]) + .then(|| INPUT_SPECIALIZATION_EXPLICIT.into()) +} + fn banked_function_constant_values(metal: &MetalRow) -> Option> { if let Some(fc_values) = metal.fc_values.as_deref() { if !fc_values.is_empty() { @@ -10504,7 +12500,6 @@ fn banked_explicit_input_plan(metal: &MetalRow) -> Option { /// (unbounded/uninstrumentable loop). `status=quarantine`, `compare=none`; counted as a failure /// outcome with a quarantine status. A committed Metal kernel cannot be cancelled, so quarantining /// is the only safe outcome — the case is recorded for visibility, not dispatched. -#[cfg(target_os = "macos")] fn write_quarantine_row( cfg: &RunConfig, tr: &TranslateRow, @@ -10540,13 +12535,6 @@ fn run_metal( plan: &HarnessPlan, fc_values: &[(usize, u64)], ) -> ProcessOutcome { - if stage == Stage::Fragment { - if let Some(reason) = unsupported_fragment_color_output_arity(ll) { - write_failure_row(cfg, tr, src, &reason); - return ProcessOutcome::Fail; - } - } - #[cfg(not(target_os = "macos"))] { let _ = (cfg, tr, src, ll, stage, entry, plan, fc_values); @@ -10587,9 +12575,10 @@ fn run_metal( &owned.inputs, ll, source_metallib.as_deref(), + !cfg.preflight_only, ) }); - let bytes = match result { + let mut bytes = match result { Ok(b) => b, Err(e) => { // The oracle refuses to submit work it cannot prove bounded (a committed Metal @@ -10603,11 +12592,31 @@ fn run_metal( return ProcessOutcome::Fail; } }; - // Instrumented (loopy) kernels are marked compare=none so candidate runners know to - // translate and execute the same bounded LL shape instead of the unguarded source text. - let compare = match crate::oracle_macos::last_oracle_compare_mode() { - crate::oracle_macos::OracleCompare::Full => "full", - crate::oracle_macos::OracleCompare::MetalOnly => "none", + if cfg.preflight_only { + let compare_mode = crate::oracle_macos::last_oracle_compare_mode(); + eprintln!( + " preflight ok: Metal PSO compiled; semantic={}; guard={compare_mode:?}; grid={:?}; tg={:?}; buffers={:?}; textures={:?}; output={:?}; no command buffer created", + compare_mode == crate::oracle_macos::OracleCompare::Full, + plan.dispatch_grid, + plan.dispatch_tg, + plan.buffers, + plan.textures, + plan.output, + ); + return if compare_mode == crate::oracle_macos::OracleCompare::Full { + ProcessOutcome::Ok + } else { + ProcessOutcome::Skip + }; + } + canonicalize_output_bytes(ll, plan, &mut bytes); + // GPU-submitted oracle runs must remain Full. MetalOnly is reserved for compile-only + // transformed modules, which return above without banking output bytes. + let (compare, plan_version) = match crate::oracle_macos::last_oracle_compare_mode() { + crate::oracle_macos::OracleCompare::Full => ("full", PLAN_VERSION), + crate::oracle_macos::OracleCompare::MetalOnly => { + ("none", SAFE_LOOP_BUDGET_PLAN_VERSION) + } }; let (fc_specialization, fc_values) = oracle_function_constant_row_fields(); let row = MetalRow { @@ -10617,7 +12626,7 @@ fn run_metal( status: "ok".into(), backend: "metal".into(), seed_profile: SEED_PROFILE.into(), - plan_version: PLAN_VERSION, + plan_version, plan: plan.clone(), input_sha256: Some(input_sha), output_sha256: Some(sha256_hex(&bytes)), @@ -10626,7 +12635,7 @@ fn run_metal( compare: compare.into(), fc_specialization, fc_values, - input_specialization: None, + input_specialization: oracle_input_specialization(ll, plan), stage: Some(format!("{stage:?}")), entry: Some(entry.into()), error: None, @@ -10746,10 +12755,11 @@ fn candidate_ll_for_metal_compare<'a>( } let loop_facts = loop_input_facts_for_metal_plan(ll, entry, metal); - match crate::loop_budget::classify_and_instrument_with_loop_input_facts( + match crate::loop_budget::classify_and_instrument_with_loop_input_facts_and_budget( ll, entry, loop_facts.as_loop_input_facts(), + loop_budget_for_metal_row(metal), ) { crate::loop_budget::GuardPlan::Instrumented(text) => Ok(Cow::Owned(text)), crate::loop_budget::GuardPlan::LoopFree => Ok(Cow::Borrowed(ll)), @@ -10991,7 +13001,7 @@ fn run_candidate( crate::runner_linux::execute_result(stage, candidate_ll, &spv, &owned.inputs, &tmp) })); let _ = fs::remove_dir_all(&tmp); - let candidate = match result { + let mut candidate = match result { Ok(Ok(b)) => b, Ok(Err(error)) => { let status = write_candidate_execution_error_row(cfg, tr, src, metal, &error); @@ -11007,6 +13017,7 @@ fn run_candidate( return ProcessOutcome::Fail; } }; + canonicalize_output_bytes(candidate_ll, plan, &mut candidate); let reference_metal; let compare_metal = if let Some(reference) = compare_reference.as_ref() { reference_metal = MetalRow { @@ -11086,6 +13097,50 @@ fn run_candidate( mod tests { use super::*; + #[test] + fn delta_merge_streams_replacements_and_keeps_last_delta_row() { + let dir = std::env::temp_dir().join(format!( + "metal2vulkan-streaming-ledger-{}-{}", + std::process::id(), + std::thread::current().name().unwrap_or("test") + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let ledger = dir.join("ledger.jsonl"); + let delta = dir.join("delta.jsonl"); + fs::write( + &ledger, + "# header\n{\"air_sha256\":\"a\",\"label\":\"a\",\"status\":\"old\"}\n{\"air_sha256\":\"b\",\"label\":\"b\",\"status\":\"keep\"}\n", + ) + .unwrap(); + fs::write( + &delta, + "{\"air_sha256\":\"a\",\"label\":\"a\",\"status\":\"first\"}\n{\"air_sha256\":\"a\",\"label\":\"a\",\"status\":\"last\"}\n{\"air_sha256\":\"c\",\"label\":\"c\",\"status\":\"new\"}\n", + ) + .unwrap(); + + assert_eq!(merge_delta_into_ledger(&ledger, &delta).unwrap(), 3); + let rows = load_jsonl_objects_by_hash_for_test(&ledger); + assert_eq!(rows.len(), 3); + assert_eq!(rows["a"]["status"], "last"); + assert_eq!(rows["b"]["status"], "keep"); + assert_eq!(rows["c"]["status"], "new"); + fs::remove_dir_all(dir).unwrap(); + } + + fn load_jsonl_objects_by_hash_for_test(path: &Path) -> HashMap { + fs::read_to_string(path) + .unwrap() + .lines() + .filter(|line| !line.starts_with('#')) + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter_map(|value| { + let hash = value.get("air_sha256")?.as_str()?.to_string(); + Some((hash, value)) + }) + .collect() + } + fn metal_row_for_compare(golden: &[u8], plan: HarnessPlan, stage: Option<&str>) -> MetalRow { MetalRow { air_sha256: "x".into(), @@ -11193,15 +13248,7 @@ mod tests { metal.output_sha256 = Some(sha256_hex(&[])); metal.compare = "none".into(); assert!(candidate_metal_status_precheck(RunBackend::Vulkan, &metal).is_none()); - let (status, reason, outcome) = - candidate_metal_status_precheck(RunBackend::MoltenVk, &metal) - .expect("MoltenVK compare=none precheck"); - assert_eq!(status, "missing"); - assert_eq!( - reason, - "metal golden compare=none is not a full semantic golden; rebank Metal row" - ); - assert_eq!(outcome, ProcessOutcome::Skip); + assert!(candidate_metal_status_precheck(RunBackend::MoltenVk, &metal).is_none()); } /// Minimal AIR-shaped snippet of an MPS-style GEMM: constant-space params struct + @@ -11725,6 +13772,279 @@ define void @kernel(ptr addrspace(2) %params, ptr addrspace(1) %queue) { } } + #[test] + fn bounded_control_float_matrix_fields_seed_as_identity() { + let ll = r#" +!1 = !{i32 0, i32 64, i32 0, !"float4x4", !"transform"} +"#; + let buffer_meta = r#"!0 = !{!"air.buffer", !"air.location_index", i32 3, !"air.struct_type_info", !1, !"air.arg_type_size", i32 64}"#; + let fields = bounded_control_seed_layout( + ll, + buffer_meta, + 64, + &HashSet::new(), + &HashSet::new(), + &HashSet::new(), + ); + assert_eq!(fields.len(), 16); + for column in 0..4 { + for row in 0..4 { + let offset = (column * 4 + row) * 4; + let field = fields + .iter() + .find(|field| field.offset == offset) + .expect("matrix lane"); + assert_eq!( + field.value, + Some(if column == row { 0x3f80_0000 } else { 0 }) + ); + } + } + } + + #[test] + fn bounded_control_struct_seeds_every_integer_vector_lane() { + let plan = infer_plan( + r#" +%struct.Controls = type { [23 x i32], <2 x i16>, i32 } + +define void @kernel(ptr addrspace(2) %controls, ptr addrspace(1) %out, i32 %tid) { + %field = getelementptr inbounds %struct.Controls, ptr addrspace(2) %controls, i64 0, i32 1 + %size = load <2 x i16>, ptr addrspace(2) %field, align 4 + %height16 = extractelement <2 x i16> %size, i64 1 + %height = zext i16 %height16 to i32 + %quotient = udiv i32 %tid, %height + store i32 %quotient, ptr addrspace(1) %out, align 4 + ret void +} + +!air.kernel = !{!0} +!0 = !{ptr @kernel, !1, !2} +!1 = !{} +!2 = !{!3, !5, !6} +!3 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 100, !"air.location_index", i32 7, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 100, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"Controls", !"air.arg_name", !"controls"} +!4 = !{i32 0, i32 4, i32 23, !"uint", !"values", i32 92, i32 4, i32 0, !"ushort2", !"size", i32 96, i32 4, i32 0, !"uint", !"count"} +!5 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!6 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"} +"#, + ); + let controls = plan + .buffers + .iter() + .find(|buffer| buffer.index == 7) + .unwrap(); + assert_eq!(controls.seed_mode, SEED_MODE_BOUNDED_CONTROL); + for offset in [92, 94] { + assert!( + controls.seed_layout.iter().any(|field| { + field.offset == offset && field.size == 2 && field.value.is_none() + }), + "missing ushort2 lane at {offset}: {:?}", + controls.seed_layout + ); + } + let bytes = bounded_control_buffer_bytes_with_layout(controls.len, &controls.seed_layout); + assert_eq!(u16::from_le_bytes(bytes[92..94].try_into().unwrap()), 16); + assert_eq!(u16::from_le_bytes(bytes[94..96].try_into().unwrap()), 16); + } + + #[test] + fn switch_control_struct_fields_use_explicit_case_values() { + let ll = r#" +%Params = type { i32, i32, i32, i32 } + +define void @frag(ptr addrspace(2) %params) { +entry: + %field0 = getelementptr inbounds %Params, ptr addrspace(2) %params, i64 0, i32 0 + %kind = load i32, ptr addrspace(2) %field0 + %field3 = getelementptr inbounds %Params, ptr addrspace(2) %params, i64 0, i32 3 + %mode = load i32, ptr addrspace(2) %field3 + %call = call i32 @helper(i32 %kind, i32 %mode) + ret void +} + +define internal i32 @helper(i32 %kind, i32 %mode) { +entry: + switch i32 %kind, label %kind_default [ + i32 0, label %kind_zero + i32 1, label %kind_one + ] +kind_zero: + ret i32 0 +kind_one: + ret i32 1 +kind_default: + switch i32 %mode, label %mode_default [ + i32 1, label %mode_one + i32 2, label %mode_two + ] +mode_one: + ret i32 1 +mode_two: + ret i32 2 +mode_default: + ret i32 0 +} + +!air.fragment = !{!0} +!0 = !{ptr @frag, !1, !2} +!1 = !{} +!2 = !{!3} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 16, !"air.arg_type_name", !"Params", !"air.arg_name", !"params"} +!4 = !{i32 0, i32 4, i32 0, !"uint", !"kind", i32 4, i32 4, i32 0, !"uint", !"x", i32 8, i32 4, i32 0, !"uint", !"y", i32 12, i32 4, i32 0, !"uint", !"mode"} +"#; + + let plan = infer_plan(ll); + let params = plan + .buffers + .iter() + .find(|buffer| buffer.index == 1) + .expect("params buffer"); + assert_eq!(bounded_control_u32_at(params, 0), Some(0)); + assert_eq!(bounded_control_u32_at(params, 12), Some(1)); + assert_eq!(bounded_control_u32_at(params, 4), Some(BOUNDED_CONTROL_DIM)); + + let bicubic_ll = format!( + "@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 562249, i64 0], align 8\n{ll}\ndeclare void @air.sample_texture_2d()\n" + ); + let bicubic_plan = infer_plan(&bicubic_ll); + let bicubic_params = bicubic_plan + .buffers + .iter() + .find(|buffer| buffer.index == 1) + .expect("bicubic params buffer"); + assert_eq!(bounded_control_u32_at(bicubic_params, 0), Some(0)); + assert_eq!(bounded_control_u32_at(bicubic_params, 12), Some(1)); + assert_eq!(bounded_control_u32_at(bicubic_params, 4), Some(0)); + } + + #[test] + fn raw_header_fields_that_bound_a_loop_are_seeded_to_one() { + let ll = r#" +define void @kernel(ptr addrspace(1) readonly %source, ptr addrspace(1) writeonly %out) { +entry: + %count_ptr = getelementptr inbounds i8, ptr addrspace(1) %source, i64 24 + %count = load i32, ptr addrspace(1) %count_ptr, align 4 + %stride_ptr = getelementptr inbounds i8, ptr addrspace(1) %source, i64 40 + %stride = load i32, ptr addrspace(1) %stride_ptr, align 4 + %base_ptr = getelementptr inbounds i8, ptr addrspace(1) %source, i64 80 + %base = load i64, ptr addrspace(1) %base_ptr, align 8 + %wide_count = zext i32 %count to i64 + %wide_stride = zext i32 %stride to i64 + %bytes = mul i64 %wide_count, %wide_stride + br label %loop +loop: + %remaining = phi i64 [ %bytes, %entry ], [ %next, %loop ] + %next = sub i64 %remaining, 1 + %done = icmp eq i64 %next, 0 + br i1 %done, label %exit, label %loop +exit: + ret void +} +!air.kernel = !{!0} +!0 = !{ptr @kernel, !1, !2} +!1 = !{} +!2 = !{!3, !4} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 1, !"air.arg_type_name", !"char", !"air.arg_name", !"source"} +!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_size", i32 1, !"air.arg_type_name", !"char", !"air.arg_name", !"out"} +"#; + let plan = infer_plan(ll); + let source = plan + .buffers + .iter() + .find(|buffer| buffer.index == 0) + .unwrap(); + assert_eq!(source.seed_mode, SEED_MODE_BOUNDED_CONTROL); + for (offset, size) in [(24, 4), (40, 4), (80, 8)] { + assert!( + source.seed_layout.iter().any(|field| { + field.offset == offset && field.size == size && field.value == Some(1) + }), + "missing safe raw field ({offset}, {size}): {:?}", + source.seed_layout + ); + } + } + + #[test] + fn raw_memcpy_byte_count_uses_one_full_vector() { + let ll = r#" +define void @kernel(ptr addrspace(1) readonly %source, ptr addrspace(1) writeonly %out) { +entry: + %base.ptr = getelementptr inbounds i8, ptr addrspace(1) %source, i64 160 + %base = load i64, ptr addrspace(1) %base.ptr, align 8 + %count.ptr = getelementptr inbounds i8, ptr addrspace(1) %source, i64 168 + %count = load i64, ptr addrspace(1) %count.ptr, align 8 + br label %loop +loop: + %remaining = phi i64 [ %count, %entry ], [ %next, %loop ] + %chunk = tail call i64 @air.min.u.i64(i64 %remaining, i64 1024) + call void @llvm.memcpy.p1.p1.i64(ptr addrspace(1) %out, ptr addrspace(1) %source, i64 %chunk, i1 false) + %next = sub i64 %remaining, %chunk + %done = icmp eq i64 %next, 0 + br i1 %done, label %exit, label %loop +exit: + ret void +} +declare i64 @air.min.u.i64(i64, i64) +declare void @llvm.memcpy.p1.p1.i64(ptr addrspace(1), ptr addrspace(1), i64, i1) +!air.kernel = !{!0} +!0 = !{ptr @kernel, !1, !2} +!1 = !{} +!2 = !{!3, !4} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 1, !"air.arg_type_name", !"char", !"air.arg_name", !"source"} +!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_size", i32 1, !"air.arg_type_name", !"char", !"air.arg_name", !"out"} +"#; + let plan = infer_plan(ll); + let source = plan + .buffers + .iter() + .find(|buffer| buffer.index == 0) + .unwrap(); + assert!(source + .seed_layout + .iter() + .any(|field| { field.offset == 160 && field.size == 8 && field.value == Some(1) })); + assert!(source.seed_layout.iter().any(|field| { + field.offset == 168 + && field.size == 8 + && field.value == Some(u64::from(BOUNDED_CONTROL_DIM)) + })); + } + + #[test] + fn air_min_preserves_loaded_loop_bound_provenance() { + let ll = r#" +define void @kernel(ptr addrspace(1) readonly %count) { +entry: + %loaded = load i32, ptr addrspace(1) %count, align 4 + %limit = tail call i32 @air.min.s.i32(i32 %loaded, i32 32) + br label %loop +loop: + %i = phi i32 [ 0, %entry ], [ %next, %loop ] + %next = add i32 %i, 1 + %keep = icmp slt i32 %next, %limit + br i1 %keep, label %loop, label %exit +exit: + ret void +} +declare i32 @air.min.s.i32(i32, i32) +!air.kernel = !{!0} +!0 = !{ptr @kernel, !1, !2} +!1 = !{} +!2 = !{!3} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_name", !"int", !"air.arg_name", !"count"} +"#; + let plan = infer_plan(ll); + let count = plan + .buffers + .iter() + .find(|buffer| buffer.index == 0) + .unwrap(); + assert_eq!(count.seed_mode, SEED_MODE_BOUNDED_CONTROL); + assert_eq!(count.seed_layout[0].value, Some(1)); + } + #[test] fn finite_struct_float_input_buffer_covers_default_dispatch() { let ll = r#" @@ -13857,10 +16177,45 @@ attributes #0 = { nounwind } assert!(reason.contains("rebank Metal row"), "{reason}"); } + #[test] + fn output_stride_compatibility_ignores_controls_too_narrow_for_required_stride() { + let buffer = PlanBuffer { + index: 5, + len: 8, + role: "Input".into(), + seed_mode: SEED_MODE_BOUNDED_CONTROL.into(), + seed_tag: 6, + seed_stride: None, + seed_layout: vec![ + ControlSeedField { + offset: 0, + size: 4, + value: Some(256), + }, + ControlSeedField { + offset: 4, + size: 1, + value: Some(0), + }, + ], + }; + let requirement = OutputStrideRequirement { + buffer: 5, + field_offset: Some(0), + store_bytes: 4, + min_row_bytes: 64, + }; + + assert!(!bounded_control_output_stride_too_small( + &buffer, + requirement + )); + } + #[test] fn output_stride_struct_field_is_sized_to_store_width() { let ll = r#" -%struct.Params = type { i32, i32, i32 } +%struct.Params = type { i32, i32, i32, i8 } define void @byte_output_stride_struct(ptr addrspace(1) %dst, ptr addrspace(2) %params, i32 %tid) local_unnamed_addr #0 { entry: @@ -13878,12 +16233,31 @@ entry: !1 = !{} !2 = !{!3, !4, !6} !3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_name", !"float", !"air.arg_name", !"dst"} -!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !5, !"air.arg_type_size", i32 12, !"air.arg_type_name", !"Params", !"air.arg_name", !"params"} -!5 = !{!"air.struct_type_info", i32 0, i32 4, i32 0, !"uint", !"m", i32 4, i32 4, i32 0, !"uint", !"n", i32 8, i32 4, i32 0, !"uint", !"rowBytes"} +!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !5, !"air.arg_type_size", i32 16, !"air.arg_type_name", !"Params", !"air.arg_name", !"params"} +!5 = !{!"air.struct_type_info", i32 0, i32 4, i32 0, !"uint", !"m", i32 4, i32 4, i32 0, !"uint", !"n", i32 8, i32 4, i32 0, !"uint", !"rowBytes", i32 12, i32 1, i32 0, !"bool", !"enabled"} !6 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"} attributes #0 = { nounwind } "#; + let inferred = infer_plan(ll); + let inferred_params = inferred + .buffers + .iter() + .find(|buffer| buffer.index == 1) + .expect("inferred params"); + assert_eq!( + packed_u32_control_field_offset(inferred_params, 2), + Some(8), + "{:?}", + inferred_params.seed_layout + ); + let requirements = output_stride_control_requirements(ll, 0, &inferred.buffers); + assert!( + requirements + .iter() + .any(|requirement| requirement.field_offset == Some(8)), + "{requirements:?}" + ); let plan = infer_plan(ll); let params = plan .buffers @@ -13895,6 +16269,10 @@ attributes #0 = { nounwind } .seed_layout .iter() .any(|field| field.offset == 8 && field.value == Some(64))); + assert!(params + .seed_layout + .iter() + .any(|field| field.offset == 12 && field.value != Some(64))); let metal = metal_row_for_compare(&[], plan, Some("Kernel")); assert!(incompatible_overlapping_output_stride_golden(ll, &metal).is_none()); @@ -14217,6 +16595,167 @@ declare i32 @air.atomic.global.add.u.i32(ptr addrspace(1) captures(none), i32, i .expect("buffer-loaded scatter indices are schedule-dependent"); assert!(reason.contains("dynamic buffer scatter"), "{reason}"); assert!(reason.contains("serial/smoke plan"), "{reason}"); + + let (serial_plan, _) = metal_oracle_inputs(ll, None); + assert_eq!(serial_plan.dispatch_grid, [1, 1, 1]); + assert_eq!(serial_plan.dispatch_tg, [1, 1, 1]); + assert_eq!( + oracle_input_specialization(ll, &serial_plan).as_deref(), + Some(INPUT_SPECIALIZATION_EXPLICIT) + ); + } + + #[test] + fn packed_loop_count_and_destination_scatter_gets_safe_explicit_plan() { + assert_eq!( + typed_gep_field_path( + "getelementptr inbounds %struct.Control, ptr addrspace(1) %points, i64 %tid64", + "points" + ), + Some(Vec::new()) + ); + let ll = r#" +%struct.Control = type { <2 x float>, float, half, half, i32 } +%struct.Vertex = type { [2 x float], [2 x float], [2 x float], half, half, half, half, half, half } + +define void @scatter(ptr addrspace(1) readonly %points, ptr addrspace(1) writeonly %out, i32 %tid) { +entry: + %tid64 = zext i32 %tid to i64 + %field = getelementptr inbounds %struct.Control, ptr addrspace(1) %points, i64 %tid64, i32 4 + %packed = load i32, ptr addrspace(1) %field, align 4 + %count = and i32 %packed, 65535 + %base = lshr i32 %packed, 16 + br label %loop +loop: + %i = phi i32 [ 0, %entry ], [ %next, %loop ] + call fastcc void @write_quad(i32 %base, ptr addrspace(1) %out) + %next = add i32 %i, 1 + %done = icmp eq i32 %next, %count + br i1 %done, label %exit, label %loop +exit: + ret void +} + +define internal fastcc void @write_quad(i32 %base, ptr addrspace(1) %out) { +entry: + %index = zext i32 %base to i64 + %dst = getelementptr inbounds %struct.Vertex, ptr addrspace(1) %out, i64 %index, i32 0, i64 0 + store float 1.000000e+00, ptr addrspace(1) %dst, align 4 + ret void +} + +!air.kernel = !{!0} +!0 = !{ptr @scatter, !1, !2} +!1 = !{} +!2 = !{!3, !5, !7} +!3 = !{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.struct_type_info", !4, !"air.arg_type_size", i32 24, !"air.arg_type_name", !"Control"} +!4 = !{i32 0, i32 8, i32 0, !"float2", !"a", i32 8, i32 4, i32 0, !"float", !"b", i32 12, i32 2, i32 0, !"half", !"c", i32 14, i32 2, i32 0, !"half", !"d", i32 16, i32 4, i32 0, !"uint", !"e", i32 18, i32 4, i32 0, !"uint", !"f"} +!5 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.struct_type_info", !6, !"air.arg_type_size", i32 36, !"air.arg_type_name", !"Vertex"} +!6 = !{i32 0, i32 8, i32 0, !"packed_float2", !"a", i32 24, i32 2, i32 0, !"half", !"b"} +!7 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint"} +"#; + + let inferred = infer_plan(ll); + let controls = inferred + .buffers + .iter() + .find(|buffer| buffer.index == 0) + .unwrap(); + assert!( + controls + .seed_layout + .iter() + .any(|field| { field.offset == 16 && field.size == 4 && field.value == Some(0) }), + "fields={:?} packed={:?} loop_bounds={:?}", + controls.seed_layout, + packed_loop_scatter_control_fields(ll), + buffers_with_loads_used_as_loop_bounds(ll) + ); + assert!(!controls.seed_layout.iter().any(|field| field.offset == 18)); + assert_eq!(inferred.output.len, Some(36 * DEFAULT_DISPATCH_GRID_X)); + + let (serial, _) = metal_oracle_inputs(ll, None); + assert_eq!(serial.dispatch_grid, [1, 1, 1]); + assert_eq!(serial.dispatch_tg, [1, 1, 1]); + assert_eq!( + oracle_input_specialization(ll, &serial).as_deref(), + Some(INPUT_SPECIALIZATION_EXPLICIT) + ); + let metal = metal_row_for_compare(&[], serial, Some("Kernel")); + assert!(incompatible_output_plan_golden(ll, &metal).is_none()); + } + + #[test] + fn packed_scatter_zeroes_rooted_entry_guard_before_any_cfg_cycle() { + let ll = r#" +%struct.Uniforms = type { i32, i32 } +%struct.Control = type { <2 x float>, float, half, half, i32 } + +define void @paint(ptr addrspace(2) readonly %uniforms, ptr addrspace(1) readonly %points, ptr addrspace(1) writeonly %out, i32 %tid) { +entry: + %countp = getelementptr inbounds %struct.Uniforms, ptr addrspace(2) %uniforms, i64 0, i32 1 + %count = load i32, ptr addrspace(2) %countp, align 4 + %active = icmp ult i32 %tid, %count + br i1 %active, label %work, label %exit +work: + %field = getelementptr inbounds %struct.Control, ptr addrspace(1) %points, i64 0, i32 4 + %packed = load i32, ptr addrspace(1) %field, align 4 + %iterations = and i32 %packed, 65535 + %base = lshr i32 %packed, 16 + br label %loop +loop: + %i = phi i32 [ 0, %work ], [ %next, %loop ] + call void @write(i32 %base, ptr addrspace(1) %out) + %next = add i32 %i, 1 + %done = icmp eq i32 %next, %iterations + br i1 %done, label %exit, label %loop +exit: + ret void +} + +define internal void @write(i32 %base, ptr addrspace(1) writeonly %out) { +entry: + %index = zext i32 %base to i64 + %dst = getelementptr i32, ptr addrspace(1) %out, i64 %index + store i32 1, ptr addrspace(1) %dst, align 4 + ret void +} + +!air.kernel = !{!0} +!0 = !{ptr @paint, !1, !2} +!1 = !{} +!2 = !{!3, !5, !7, !8} +!3 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_name", !"Uniforms"} +!4 = !{i32 0, i32 4, i32 0, !"uint", !"unused", i32 4, i32 4, i32 0, !"uint", !"count"} +!5 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 1, !"air.struct_type_info", !6, !"air.arg_type_size", i32 24, !"air.arg_type_name", !"Control"} +!6 = !{i32 0, i32 8, i32 0, !"float2", !"a", i32 8, i32 4, i32 0, !"float", !"b", i32 12, i32 2, i32 0, !"half", !"c", i32 14, i32 2, i32 0, !"half", !"d", i32 16, i32 4, i32 0, !"uint", !"packed"} +!7 = !{i32 2, !"air.buffer", !"air.location_index", i32 2, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_name", !"uint"} +!8 = !{i32 3, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint"} +"#; + + assert_eq!( + zero_exit_cycle_guard_struct_fields(ll), + HashSet::from([(0, 4, 4)]) + ); + let (plan, fc_values) = metal_oracle_inputs(ll, None); + let uniforms = plan + .buffers + .iter() + .find(|buffer| buffer.index == 0) + .unwrap(); + assert!(uniforms + .seed_layout + .iter() + .any(|field| { field.offset == 4 && field.size == 4 && field.value == Some(0) })); + let facts = loop_input_facts_for_plan(ll, "paint", &plan, fc_values); + assert_eq!( + crate::loop_budget::reachable_module_has_cfg_cycle_with_loop_input_facts( + ll, + "paint", + facts.as_loop_input_facts(), + ), + Ok(false) + ); } #[test] @@ -14779,6 +17318,49 @@ declare void @air.wg.barrier(i32, i32) let _ = std::fs::remove_dir_all(&tmp); } + #[test] + fn legacy_compare_none_row_uses_current_loop_budget() { + let mut metal = MetalRow { + air_sha256: "x".into(), + shard: None, + label: String::new(), + status: "ok".into(), + backend: "metal".into(), + seed_profile: SEED_PROFILE.into(), + plan_version: 1, + plan: infer_plan(LOOP_GUARDED_BDA_AS_POINTER_LL), + input_sha256: None, + output_sha256: Some(sha256_hex(&[])), + output_b64: Some(encode_output_b64(&[])), + spv_sha256: None, + compare: "none".into(), + fc_specialization: None, + fc_values: None, + input_specialization: None, + stage: Some("Kernel".into()), + entry: Some("bda_loop_guard".into()), + error: None, + }; + + assert_eq!( + loop_budget_for_metal_row(&metal), + crate::loop_budget::LOOP_BUDGET_BACKEDGES + ); + let quarantine = historic_compare_none_quarantine_row(&metal); + assert_eq!(quarantine.status, "quarantine"); + assert!(quarantine.output_sha256.is_none()); + assert!(quarantine.output_b64.is_none()); + assert!(quarantine + .error + .as_deref() + .is_some_and(|error| error.contains("not a semantic Metal oracle"))); + metal.compare = "full".into(); + assert_eq!( + loop_budget_for_metal_row(&metal), + crate::loop_budget::LEGACY_LOOP_BUDGET_BACKEDGES + ); + } + #[test] fn vulkan_candidate_translate_uses_plan_dispatch_shape() { let ll = r#" @@ -15844,6 +18426,49 @@ define void @kernel(ptr addrspace(1) %out) { assert!(tolerance.is_none()); } + #[test] + fn compare_none_preserves_a_valid_numeric_tolerance() { + let golden = 0x3c00u16.to_le_bytes(); + let candidate = 0x3c01u16.to_le_bytes(); + let metal = MetalRow { + air_sha256: "x".into(), + shard: None, + label: String::new(), + status: "ok".into(), + backend: "metal".into(), + seed_profile: SEED_PROFILE.into(), + plan_version: PLAN_VERSION, + plan: infer_plan(""), + input_sha256: None, + output_sha256: Some(sha256_hex(&golden)), + output_b64: Some(encode_output_b64(&golden)), + spv_sha256: None, + compare: "none".into(), + fc_specialization: None, + fc_values: None, + input_specialization: None, + stage: Some("Kernel".into()), + entry: None, + error: None, + }; + let ll = r#" +define half @k(half %x) #0 { ret half %x } +attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } +"#; + let (status, observed, tolerance) = compare_candidate_to_metal( + &candidate, + &metal, + &sha256_hex(&candidate), + metal.output_sha256.as_deref().unwrap_or_default(), + DataFormat::R16Float, + Some(ll), + ); + + assert_eq!(status, "tolerance"); + assert_eq!(observed.and_then(|margin| margin.max_ulp), Some(1)); + assert!(tolerance.is_some()); + } + #[test] fn fast_float_integer_render_target_allows_byte_quantization_tolerance() { let ll = r#" @@ -15955,6 +18580,18 @@ define void @kernel(ptr addrspace(1) %out) { assert_eq!(format, DataFormat::Rgba32Float); } + #[test] + fn array_wrapped_writable_float_texture_uses_r32_format() { + assert_eq!( + texture_format_from_air_type(Some("array, 8>")), + "R32Float" + ); + assert_eq!( + texture_format_from_air_type(Some("array, 8>")), + "Rgba32Float" + ); + } + #[test] fn matrix_half_buffer_air_type_uses_float_output_lanes() { let ll = r#" @@ -16228,67 +18865,6 @@ define void @kernel() { assert!(incompatible_function_constant_golden(ll, &metal).is_none()); } - #[test] - fn function_constant_texture_array_ref_view_family_requires_rebank() { - let ll = r#" -@_ZL33_tex_loc = internal addrspace(2) global i32 1, align 4 -@_ZL33_arr_loc = internal addrspace(2) global i32 33, align 4 -@fc0 = internal addrspace(2) global i8 1, align 1 -@fc1 = internal addrspace(2) global i8 1, align 1 - -define void @kernel(ptr addrspace(1) %a, ptr addrspace(1) %b) { - ret void -} - -!air.kernel = !{!0} -!0 = !{ptr @kernel, !1, !2} -!1 = !{} -!2 = !{!3, !5} -!3 = !{i32 0, !"air.function_constant", !4, !"air.texture", !"air.location_index", ptr addrspace(2) @_ZL33_tex_loc, i32 1, !"air.sample", !"air.arg_type_name", !"array_ref>", !"air.arg_name", !"plain"} -!4 = !{ptr addrspace(2) @fc0, !"bool", !"usePlain", i32 1, i1 true} -!5 = !{i32 1, !"air.function_constant", !6, !"air.texture", !"air.location_index", ptr addrspace(2) @_ZL33_arr_loc, i32 1, !"air.sample", !"air.arg_type_name", !"array_ref>", !"air.arg_name", !"arrayed"} -!6 = !{ptr addrspace(2) @fc1, !"bool", !"useArray", i32 2, i1 true} -"#; - let mut metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - metal.fc_specialization = Some(FC_SPECIALIZATION_VALUES.into()); - metal.fc_values = Some(vec![ - FunctionConstantValueJson { index: 1, value: 1 }, - FunctionConstantValueJson { index: 2, value: 1 }, - ]); - - let reason = incompatible_function_constant_texture_array_ref_golden(ll, &metal) - .expect("mixed FC texture array_ref view family"); - assert!(reason.contains("texture metadata"), "{reason}"); - assert!(reason.contains("image-view"), "{reason}"); - - metal.compare = "none".into(); - let reason = incompatible_function_constant_texture_array_ref_golden(ll, &metal) - .expect("mixed FC texture array_ref smoke view family"); - assert!(reason.contains("image-view"), "{reason}"); - - let read_ll = r#" -@fc0 = internal addrspace(2) global i8 1, align 1 -@fc1 = internal addrspace(2) global i8 1, align 1 - -define void @kernel(ptr addrspace(1) %arrayed, ptr addrspace(1) %plain, ptr addrspace(1) %out) { - ret void -} - -!air.kernel = !{!0} -!0 = !{ptr @kernel, !1, !2} -!1 = !{} -!2 = !{!3, !5, !7} -!3 = !{i32 0, !"air.function_constant", !4, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d_array", !"air.arg_name", !"arrayed"} -!4 = !{ptr addrspace(2) @fc0, !"bool", !"useArrayed", i32 1, i1 true} -!5 = !{i32 1, !"air.function_constant", !6, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"plain"} -!6 = !{ptr addrspace(2) @fc1, !"bool", !"usePlain", i32 2, i1 true} -!7 = !{i32 2, !"air.texture", !"air.location_index", i32 1, i32 1, !"air.write", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"out"} -"#; - let reason = incompatible_function_constant_texture_array_ref_golden(read_ll, &metal) - .expect("mixed FC read texture view family"); - assert!(reason.contains("texture2d_array"), "{reason}"); - } - #[test] fn function_constant_private_pointer_table_golden_is_missing() { let ll = r#" @@ -17290,7 +19866,7 @@ attributes #0 = { "no-nans-fp-math"="true" } } #[test] - fn sampled_fast_pow_f32_texture_golden_is_missing() { + fn sampled_fast_pow_f32_texture_uses_numeric_tolerance() { let ll = r#" define <4 x half> @frag(ptr addrspace(1) %tex) #0 { %s = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) null, <2 x float> zeroinitializer, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) @@ -17317,13 +19893,11 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); - let reason = incompatible_sampled_fast_pow_texture_golden(ll, &metal) - .expect("sampled fast pow texture golden"); - assert!(reason.contains("fast_pow"), "{reason}"); + assert!(incompatible_sampled_fast_pow_texture_golden(ll, &metal).is_none()); } #[test] - fn sampled_f32_domain_math_texture_golden_is_missing() { + fn sampled_f32_domain_math_texture_uses_numeric_tolerance() { let ll = r#" define float @frag(ptr addrspace(1) %tex, <2 x float> %uv) #0 { %s = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) null, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) @@ -17349,9 +19923,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); - let reason = incompatible_sampled_f32_domain_math_texture_golden(ll, &metal) - .expect("sampled f32 domain math texture golden"); - assert!(reason.contains("finite f32 texture"), "{reason}"); + assert!(incompatible_sampled_f32_domain_math_texture_golden(ll, &metal).is_none()); } #[test] @@ -17518,7 +20090,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } } #[test] - fn sampled_f32_texture_output_golden_is_missing() { + fn sampled_f32_texture_output_uses_numeric_tolerance() { let ll = r#" define void @k(<2 x i16> %gid, ptr addrspace(1) %src, ptr addrspace(1) %dst, <2 x float> %uv) { %s = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %src, ptr addrspace(2) null, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) @@ -17539,9 +20111,7 @@ declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - let reason = incompatible_sampled_f32_texture_output_golden(ll, &metal) - .expect("sampled f32 texture output golden"); - assert!(reason.contains("f32 texture output"), "{reason}"); + assert!(incompatible_sampled_f32_texture_output_golden(ll, &metal).is_none()); } #[test] @@ -17691,7 +20261,7 @@ exit: } #[test] - fn finite_struct_half_div_fragment_golden_is_missing() { + fn finite_struct_half_div_fragment_uses_numeric_tolerance() { let ll = r#" define <4 x half> @frag(ptr addrspace(1) %coeff, <4 x half> %color) #0 { %p = getelementptr inbounds half, ptr addrspace(1) %coeff, i64 0 @@ -17720,9 +20290,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); - let reason = incompatible_finite_struct_half_fragment_golden(ll, &metal) - .expect("finite-struct half fragment golden"); - assert!(reason.contains("fast half division"), "{reason}"); + assert!(incompatible_finite_struct_half_fragment_golden(ll, &metal).is_none()); } #[test] @@ -17784,48 +20352,7 @@ define void @vert(ptr addrspace(1) %tex) { } #[test] - fn moltenvk_sampled_half_render_target_exact_golden_is_missing() { - let ll = r#" -define <4 x half> @frag(ptr addrspace(1) %tex, <2 x float> %uv) #0 { - %s = tail call { <4 x half>, i8 } @air.sample_texture_2d.v4f16(ptr addrspace(1) %tex, ptr addrspace(2) null, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) - %v = extractvalue { <4 x half>, i8 } %s, 0 - %d = tail call fast half @air.dot.v4f16(<4 x half> %v, <4 x half> %v) - %out = insertelement <4 x half> %v, half %d, i64 3 - ret <4 x half> %out -} - -declare { <4 x half>, i8 } @air.sample_texture_2d.v4f16(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32) -declare half @air.dot.v4f16(<4 x half>, <4 x half>) -attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } - -!air.fragment = !{!0} -!0 = !{ptr @frag, !1, !2} -!1 = !{!3} -!2 = !{!4, !5} -!3 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"} -!4 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"tex"} -!5 = !{i32 1, !"air.fragment_input", !"air.arg_type_name", !"float2", !"air.arg_name", !"uv"} -"#; - - let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); - let reason = incompatible_moltenvk_sampled_half_render_target_exact_golden(ll, &metal) - .expect("MoltenVK sampled half render-target exact golden"); - assert!(reason.contains("finite f16 texture"), "{reason}"); - assert!( - reason.contains("MoltenVK exact byte comparison"), - "{reason}" - ); - - let mut compare_none = metal; - compare_none.compare = "none".into(); - assert!( - incompatible_moltenvk_sampled_half_render_target_exact_golden(ll, &compare_none) - .is_none() - ); - } - - #[test] - fn moltenvk_half_texture_output_exact_golden_is_missing() { + fn moltenvk_half_texture_output_uses_numeric_tolerance() { let ll = r#" define void @kernel(ptr addrspace(1) readonly %src, ptr addrspace(1) %out, <2 x i16> %gid) #0 { %sam = tail call ptr addrspace(2) @air.get_read_sampler() @@ -17851,10 +20378,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - let reason = incompatible_moltenvk_half_texture_output_exact_golden(ll, &metal) - .expect("MoltenVK half texture-output exact golden"); - assert!(reason.contains("finite f16 texture data"), "{reason}"); - assert!(reason.contains("texture write rounding"), "{reason}"); + assert!(incompatible_moltenvk_half_texture_output_exact_golden(ll, &metal).is_none()); let fragment_metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); assert!( @@ -17863,7 +20387,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } } #[test] - fn moltenvk_storage_f32_texture_output_exact_golden_is_missing() { + fn moltenvk_storage_f32_texture_output_uses_numeric_tolerance() { let ll = r#" define void @kernel(ptr addrspace(1) readonly %src, ptr addrspace(1) %out, <2 x i32> %gid) #0 { %read = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly %src, ptr addrspace(2) null, <2 x i32> %gid, <2 x i32> zeroinitializer, i32 0, i32 1) @@ -17890,17 +20414,13 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - let reason = incompatible_moltenvk_storage_f32_texture_output_exact_golden(ll, &metal) - .expect("MoltenVK storage f32 texture-output exact golden"); - assert!(reason.contains("finite f32 storage texture"), "{reason}"); assert!( - reason.contains("MoltenVK exact byte comparison"), - "{reason}" + incompatible_moltenvk_storage_f32_texture_output_exact_golden(ll, &metal).is_none() ); } #[test] - fn moltenvk_storage_r32_imageblock_texture_output_exact_golden_is_missing() { + fn moltenvk_storage_r32_imageblock_texture_output_uses_numeric_tolerance() { let ll = r#" %"struct.metal::_imageblock_base.92" = type { ptr addrspace(4) } @@ -17936,14 +20456,13 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } let mut metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); metal.plan.output.format = "R32Float".into(); - let reason = incompatible_moltenvk_storage_f32_texture_output_exact_golden(ll, &metal) - .expect("MoltenVK storage R32 imageblock exact golden"); - assert!(reason.contains("finite f32 storage texture"), "{reason}"); - assert!(reason.contains("texture read/write rounding"), "{reason}"); + assert!( + incompatible_moltenvk_storage_f32_texture_output_exact_golden(ll, &metal).is_none() + ); } #[test] - fn moltenvk_sampled_f32_render_target_exact_golden_is_missing() { + fn moltenvk_sampled_f32_render_target_uses_numeric_tolerance() { let ll = r#" define <4 x float> @frag(ptr addrspace(1) %tex, <2 x float> %uv) #0 { %s = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) null, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) @@ -17964,10 +20483,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); - let reason = incompatible_moltenvk_sampled_f32_render_target_exact_golden(ll, &metal) - .expect("MoltenVK sampled f32 render-target exact golden"); - assert!(reason.contains("finite f32 texture"), "{reason}"); - assert!(reason.contains("render-target rounding"), "{reason}"); + assert!(incompatible_moltenvk_sampled_f32_render_target_exact_golden(ll, &metal).is_none()); } #[test] @@ -18003,7 +20519,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } } #[test] - fn moltenvk_fast_f32_buffer_output_exact_golden_is_missing() { + fn moltenvk_fast_f32_buffer_output_uses_numeric_tolerance() { let ll = r#" define void @kernel(ptr addrspace(1) %out, ptr addrspace(2) %control, i32 %idx) #0 { %c = load i32, ptr addrspace(2) %control, align 4 @@ -18028,14 +20544,11 @@ attributes #0 = { "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "uns let mut metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); metal.plan.output.format = "Rgba32Float".into(); metal.plan.buffers[0].seed_mode = SEED_MODE_FINITE_FLOAT32.into(); - let reason = incompatible_moltenvk_fast_f32_buffer_output_exact_golden(ll, &metal) - .expect("MoltenVK fast f32 buffer-output exact golden"); - assert!(reason.contains("finite f32 buffer output"), "{reason}"); - assert!(reason.contains("denorm flushing"), "{reason}"); + assert!(incompatible_moltenvk_fast_f32_buffer_output_exact_golden(ll, &metal).is_none()); } #[test] - fn moltenvk_fast_f32_input_buffer_exact_golden_is_missing() { + fn moltenvk_fast_f32_input_buffer_uses_numeric_tolerance() { let ll = r#" define void @kernel(ptr addrspace(1) %a, ptr addrspace(1) %b, ptr addrspace(1) %out) #0 { %x = load float, ptr addrspace(1) %a, align 4 @@ -18060,17 +20573,11 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } let mut metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); metal.plan.output.format = "F32".into(); - let reason = incompatible_moltenvk_fast_f32_input_buffer_exact_golden(ll, &metal) - .expect("MoltenVK finite f32 input buffer exact golden"); - assert!(reason.contains("finite f32 buffer inputs"), "{reason}"); - assert!( - reason.contains("MoltenVK exact byte comparison"), - "{reason}" - ); + assert!(incompatible_moltenvk_fast_f32_input_buffer_exact_golden(ll, &metal).is_none()); } #[test] - fn moltenvk_fast_half_buffer_output_exact_golden_is_missing() { + fn moltenvk_fast_half_buffer_output_uses_numeric_tolerance() { let ll = r#" define void @kernel(ptr addrspace(1) %src, ptr addrspace(1) %out) #0 { %h = load half, ptr addrspace(1) %src, align 2 @@ -18096,14 +20603,11 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } let mut metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); metal.plan.output.format = "R16Float".into(); - let reason = incompatible_moltenvk_fast_half_buffer_output_exact_golden(ll, &metal) - .expect("MoltenVK fast half buffer-output exact golden"); - assert!(reason.contains("finite f16 buffer output"), "{reason}"); - assert!(reason.contains("half conversion"), "{reason}"); + assert!(incompatible_moltenvk_fast_half_buffer_output_exact_golden(ll, &metal).is_none()); } #[test] - fn moltenvk_fast_half_render_target_exact_golden_is_missing() { + fn moltenvk_fast_half_render_target_uses_numeric_tolerance() { let ll = r#" define <4 x half> @frag(half %x) #0 { %s = tail call fast half @air.fast_sqrt.f16(half %x) @@ -18123,14 +20627,11 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); - let reason = incompatible_moltenvk_fast_half_render_target_exact_golden(ll, &metal) - .expect("MoltenVK fast half render-target exact golden"); - assert!(reason.contains("fast_sqrt"), "{reason}"); - assert!(reason.contains("render-target rounding"), "{reason}"); + assert!(incompatible_moltenvk_fast_half_render_target_exact_golden(ll, &metal).is_none()); } #[test] - fn moltenvk_fast_raw_float_buffer_output_exact_golden_is_missing() { + fn fast_raw_float_buffer_output_executes_with_exact_default() { let ll = r#" define void @kernel(ptr addrspace(1) %out, float %x, i32 %idx) #0 { %dst = getelementptr float, ptr addrspace(1) %out, i32 %idx @@ -18149,16 +20650,24 @@ attributes #0 = { "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "uns !5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"idx"} "#; - let mut metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - metal.plan.output.format = "RawBytes".into(); - let reason = incompatible_moltenvk_fast_raw_float_buffer_output_exact_golden(ll, &metal) - .expect("MoltenVK fast raw float buffer-output exact golden"); - assert!(reason.contains("raw buffer bytes"), "{reason}"); - assert!(reason.contains("signed-zero"), "{reason}"); + assert!(raw_buffer_writes_float_derived_bytes(ll)); + assert!(tolerance_for_context(DataFormat::RawBytes, Some(ll)).is_none()); } #[test] - fn moltenvk_packed_unorm_raw_float_buffer_output_exact_golden_is_missing() { + fn integer_vector_store_is_not_classified_as_float_derived_raw_bytes() { + let ll = r#" +define void @kernel(ptr addrspace(1) %out, <4 x i32> %value) #0 { + store <4 x i32> %value, ptr addrspace(1) %out, align 16 + ret void +} +attributes #0 = { "no-nans-fp-math"="true" } +"#; + assert!(!raw_buffer_writes_float_derived_bytes(ll)); + } + + #[test] + fn packed_unorm_raw_float_buffer_output_uses_byte_tolerance() { let ll = r#" define void @kernel(ptr addrspace(1) %src, ptr addrspace(1) %out, i32 %idx) #0 { %srcp = getelementptr i32, ptr addrspace(1) %src, i32 %idx @@ -18184,12 +20693,13 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } !5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"idx"} "#; - let mut metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - metal.plan.output.format = "RawBytes".into(); - let reason = incompatible_moltenvk_fast_raw_float_buffer_output_exact_golden(ll, &metal) - .expect("MoltenVK packed unorm raw float buffer-output exact golden"); - assert!(reason.contains("raw buffer bytes"), "{reason}"); - assert!(reason.contains("float denorm"), "{reason}"); + assert!(raw_buffer_writes_float_derived_bytes(ll)); + assert_eq!( + tolerance_for_context(DataFormat::RawBytes, Some(ll)) + .as_ref() + .and_then(|tolerance| tolerance.max_abs), + Some(1.0) + ); } #[test] @@ -18295,7 +20805,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } } #[test] - fn sampled_fast_powr_integer_render_target_golden_is_missing() { + fn sampled_fast_powr_integer_render_target_uses_numeric_tolerance() { let ll = r#" define i32 @frag(<2 x float> %uv, ptr addrspace(1) %tex, ptr addrspace(2) %sampler) #0 { %s = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %tex, ptr addrspace(2) %sampler, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) @@ -18326,13 +20836,11 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); - let reason = incompatible_sampled_fast_pow_texture_golden(ll, &metal) - .expect("sampled fast powr texture golden"); - assert!(reason.contains("fast_pow/fast_powr"), "{reason}"); + assert!(incompatible_sampled_fast_pow_texture_golden(ll, &metal).is_none()); } #[test] - fn sampled_f32_dynamic_lod_render_target_golden_is_missing() { + fn sampled_f32_dynamic_lod_render_target_uses_numeric_tolerance() { let ll = r#" define <4 x float> @frag(<2 x float> %uv, ptr addrspace(1) %src, ptr addrspace(1) %mask) #0 { %mask_sample = tail call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %mask, ptr addrspace(2) null, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0) @@ -18363,9 +20871,15 @@ attributes #0 = { "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); - let reason = incompatible_sampled_f32_dynamic_lod_render_target_golden(ll, &metal) - .expect("sampled f32 dynamic LOD render-target golden"); - assert!(reason.contains("dynamic LOD"), "{reason}"); + assert!(incompatible_sampled_f32_dynamic_lod_render_target_golden(ll, &metal).is_none()); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_process_resident_bytes_reports_current_process() { + assert!( + macos_process_resident_bytes(std::process::id()).is_some_and(|resident| resident > 0) + ); } #[test] @@ -18442,7 +20956,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } } #[test] - fn fragment_fast_pow_rsqrt_render_target_golden_is_missing() { + fn fragment_fast_pow_rsqrt_render_target_uses_numeric_tolerance() { let ll = r#" define <4 x float> @frag(float %x) #0 { %r = tail call fast float @air.fast_rsqrt.f32(float %x) @@ -18464,10 +20978,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Fragment")); - let reason = incompatible_fragment_fast_pow_rsqrt_render_target_golden(ll, &metal) - .expect("fragment fast pow/rsqrt render-target golden"); - assert!(reason.contains("fast_pow"), "{reason}"); - assert!(reason.contains("fast_rsqrt"), "{reason}"); + assert!(incompatible_fragment_fast_pow_rsqrt_render_target_golden(ll, &metal).is_none()); } #[test] @@ -18524,7 +21035,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } } #[test] - fn sampled_half_domain_sensitive_texture_golden_is_missing() { + fn sampled_half_domain_sensitive_texture_uses_numeric_tolerance() { let ll = r#" @__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 34901797601050697, i64 0], align 8 @@ -18561,9 +21072,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - let reason = incompatible_sampled_half_domain_sensitive_texture_golden(ll, &metal) - .expect("sampled half domain-sensitive texture golden"); - assert!(reason.contains("domain-sensitive math"), "{reason}"); + assert!(incompatible_sampled_half_domain_sensitive_texture_golden(ll, &metal).is_none()); } #[test] @@ -18635,13 +21144,11 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - let reason = incompatible_sampled_half_linear_filter_texture_golden(ll, &metal) - .expect("sampled half linear imageblock texture golden"); - assert!(reason.contains("imageblock"), "{reason}"); + assert!(incompatible_sampled_half_linear_filter_texture_golden(ll, &metal).is_none()); } #[test] - fn sampled_half_linear_scaled_texture_golden_is_missing() { + fn sampled_half_linear_scaled_texture_uses_numeric_tolerance() { let ll = r#" @__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 34901797601055817, i64 0], align 8 @@ -18676,14 +21183,11 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - let reason = incompatible_sampled_half_linear_filter_texture_golden(ll, &metal) - .expect("sampled half scaled linear texture golden"); - assert!(reason.contains("buffer-scaled coordinates"), "{reason}"); - assert!(reason.contains("f16 texture output"), "{reason}"); + assert!(incompatible_sampled_half_linear_filter_texture_golden(ll, &metal).is_none()); } #[test] - fn sampled_half_gather_imageblock_texture_golden_is_missing() { + fn sampled_half_gather_imageblock_texture_uses_numeric_tolerance() { let ll = r#" @__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 34901797601050697, i64 0], align 8 @@ -18715,9 +21219,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - let reason = incompatible_sampled_half_linear_filter_texture_golden(ll, &metal) - .expect("sampled half gather imageblock texture golden"); - assert!(reason.contains("gathers finite f16"), "{reason}"); + assert!(incompatible_sampled_half_linear_filter_texture_golden(ll, &metal).is_none()); } #[test] @@ -18906,9 +21408,7 @@ attributes #0 = { "no-nans-fp-math"="true" "unsafe-fp-math"="true" } "#; let metal = metal_row_for_compare(&[], infer_plan(ll), Some("Kernel")); - let reason = incompatible_sampled_half_linear_filter_texture_golden(ll, &metal) - .expect("sampled half runtime sampler threadgroup texture golden"); - assert!(reason.contains("runtime sampler"), "{reason}"); + assert!(incompatible_sampled_half_linear_filter_texture_golden(ll, &metal).is_none()); } #[test] @@ -19341,7 +21841,7 @@ attributes #0 = { "no-nans-fp-math"="true" } assert!(execution_status_is_success(RunBackend::Vulkan, "ok")); assert!(execution_status_is_success(RunBackend::Vulkan, "tolerance")); assert!(execution_status_is_success(RunBackend::Vulkan, "smoke")); - assert!(!execution_status_is_success( + assert!(execution_status_is_success( RunBackend::MoltenVk, "tolerance" )); @@ -19353,15 +21853,12 @@ attributes #0 = { "no-nans-fp-math"="true" } } #[test] - fn moltenvk_compare_policy_requires_exact_output() { + fn moltenvk_compare_policy_accepts_tolerance_but_rejects_smoke() { let mut status = "tolerance".to_string(); let mut error = None; enforce_backend_compare_policy(RunBackend::MoltenVk, &mut status, &mut error); - assert_eq!(status, "failure"); - assert_eq!( - error.as_deref(), - Some("MoltenVK output differs from Metal; exact byte match required") - ); + assert_eq!(status, "tolerance"); + assert!(error.is_none()); let mut status = "tolerance".to_string(); let mut error = None; @@ -19374,6 +21871,15 @@ attributes #0 = { "no-nans-fp-math"="true" } enforce_backend_compare_policy(RunBackend::MoltenVk, &mut status, &mut error); assert_eq!(status, "failure"); assert_eq!(error.as_deref(), Some("existing smoke reason")); + + let mut status = "smoke".to_string(); + let mut error = None; + enforce_backend_compare_policy(RunBackend::MoltenVk, &mut status, &mut error); + assert_eq!(status, "failure"); + assert_eq!( + error.as_deref(), + Some("MoltenVK compare=none smoke row has no semantic Metal golden") + ); } #[test] @@ -19461,9 +21967,11 @@ attributes #0 = { "no-nans-fp-math"="true" } status: "fallback".into(), label: "local/foo.ll".into(), error: Some("vulkan execute panicked: create compute pipeline".into()), + compare: "none".into(), signature: "create compute pipeline".into(), }; assert!(tech_row_selected(&cfg, &row)); + assert!(row.matches_text("compare=none")); let mut success = row.clone(); success.status = "tolerance".into(); @@ -19493,6 +22001,17 @@ attributes #0 = { "no-nans-fp-math"="true" } cfg.force = false; cfg.only_status = Some("ok".into()); assert!(cfg.reruns_existing_backend_rows()); + + assert!(should_reclassify_historic_compare_none_without_source(&cfg)); + cfg.remint_compare_none = true; + assert!(!should_reclassify_historic_compare_none_without_source( + &cfg + )); + cfg.remint_compare_none = false; + cfg.preflight_only = true; + assert!(!should_reclassify_historic_compare_none_without_source( + &cfg + )); } #[test] @@ -19893,6 +22412,87 @@ define void @"persona::ksDepthDilate"(ptr addrspace(2) %0) { ); } + #[test] + fn fragment_imageblock_input_is_distinguished_from_output_only_metadata() { + let input = r#" +!air.fragment = !{!0} +!0 = !{ptr @fragment_main, !1, !4} +!1 = !{!2, !3} +!2 = !{!"air.imageblock_data", !"air.imageblock_data_size", i32 16} +!3 = !{!"air.depth", !"air.arg_type_name", !"float"} +!4 = !{!5} +!5 = !{i32 0, !"air.imageblock_data", !"air.imageblock_data_size", i32 16} +"#; + let output_only = r#" +!air.fragment = !{!0} +!0 = !{ptr @fragment_main, !1, !2} +!1 = !{} +!2 = !{!3} +!3 = !{i32 0, !"air.imageblock_data", !"air.imageblock_data_size", i32 16} +"#; + + assert!(fragment_has_uninitialized_imageblock_input(input)); + assert!(!fragment_has_uninitialized_imageblock_input(output_only)); + assert_eq!( + unsafe_metal_submission_reason(input), + Some(UNINITIALIZED_FRAGMENT_IMAGEBLOCK_REASON) + ); + } + + #[test] + fn post_tessellation_vertex_is_refused_before_standalone_metal_preflight() { + let post_tessellation_vertex = r#" +!air.vertex = !{!0} +!0 = !{ptr @post_vertex, !1, !2, !5} +!1 = !{!"air.position", !"air.arg_type_name", !"float4"} +!2 = !{!3} +!3 = !{i32 0, !"air.patch_control_point_input", !4} +!4 = !{!"air.patch_control_point_function", ptr @control_point} +!5 = !{!"air.patch", !"triangle", !"air.patch_control_point", i32 3} +"#; + assert_eq!( + invalid_standalone_metal_oracle_reason(post_tessellation_vertex), + Some(POST_TESSELLATION_VERTEX_ORACLE_REASON) + ); + assert!(invalid_standalone_metal_oracle_reason( + &post_tessellation_vertex.replace("air.patch_control_point_input", "air.attribute") + ) + .is_none()); + } + + #[test] + fn unsafe_submission_classification_uses_resource_and_control_structure() { + let barrier = r#" +@packed.MTL_FC_INIT_1_j = externally_initialized constant i32 undef, section "air.fc_initializer" +define void @k() { call void @air.wg.barrier(i32 2, i32 1) ret void } +!1 = !{i32 0, !"air.function_constant", !9, !"air.buffer", !"air.address_space", i32 3, !"air.arg_name", !"a"} +!2 = !{i32 1, !"air.function_constant", !9, !"air.buffer", !"air.address_space", i32 3, !"air.arg_name", !"b"} +"#; + assert!( + unsafe_metal_submission_reason(barrier) + .is_some_and(|reason| reason.contains("coherent allocation/use")), + "{barrier}" + ); + assert!(unsafe_metal_submission_reason(&barrier.replace( + "!2 = !{i32 1, !\"air.function_constant\", !9, !\"air.buffer\", !\"air.address_space\", i32 3, !\"air.arg_name\", !\"b\"}", + "" + )) + .is_none()); + + let mut resource_union = "x".repeat(300_000); + resource_union.push_str( + "\n@packed.MTL_FC_INIT_2_j = externally_initialized constant i32 undef, section \"air.fc_initializer\"\n", + ); + for index in 0..8 { + resource_union.push_str(&format!( + "!{} = !{{i32 {index}, !\"air.function_constant\", !99, !\"air.texture\", !\"air.arg_type_name\", !\"array_ref>\"}}\n", + index + 10 + )); + } + assert!(unsafe_metal_submission_reason(&resource_union) + .is_some_and(|reason| reason.contains("aggregate GPU-time bound")),); + } + #[test] fn unresolved_visible_refs_are_classified_as_unsupported() { let err = "newComputePipelineStateWithFunction(topkv): \ @@ -19973,7 +22573,39 @@ fragment shader color output does not have enough components for the pixel forma } #[test] - fn unsupported_rgb_fragment_color_output_is_preflighted() { + fn atomic_append_u32_output_is_canonicalized_as_an_unordered_list() { + let ll = r#" +define void @append(i32 %tid, ptr addrspace(1) %out, ptr addrspace(1) %counter) { + %slot = call i32 @air.atomic.global.add.s.i32(ptr addrspace(1) %counter, i32 1, i32 0, i32 2, i1 true) + %wide = zext i32 %slot to i64 + %dst = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %wide + store i32 %tid, ptr addrspace(1) %dst, align 4 + ret void +} +declare i32 @air.atomic.global.add.s.i32(ptr addrspace(1), i32, i32, i32, i1) +!air.kernel = !{!0} +!0 = !{ptr @append, !1, !2} +!1 = !{} +!2 = !{!3, !4, !5} +!3 = !{i32 0, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"} +!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.write", !"air.address_space", i32 1, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!5 = !{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_name", !"atomic_uint", !"air.arg_name", !"counter"} +"#; + let plan = infer_plan(ll); + let mut bytes = [3u32, 1, 2, 0] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect::>(); + canonicalize_unordered_atomic_append_output(ll, &plan, &mut bytes); + let words = bytes + .chunks_exact(4) + .map(|word| u32::from_le_bytes(word.try_into().unwrap())) + .collect::>(); + assert_eq!(words, vec![0, 1, 2, 3]); + } + + #[test] + fn rgb_fragment_color_output_canonicalizes_only_attachment_padding() { let ll = r#" define <3 x half> @inputStreamColorBlitFragment() { ret <3 x half> zeroinitializer @@ -19986,15 +22618,19 @@ define <3 x half> @inputStreamColorBlitFragment() { !18 = !{} "#; - let reason = - unsupported_fragment_color_output_arity(ll).expect("half3 color should be unsupported"); - assert!(reason.contains("render target location 0"), "{reason}"); - assert!(reason.contains("\"half3\""), "{reason}"); - assert!(reason.contains("no renderable RGB"), "{reason}"); + let plan = infer_plan(ll); + let mut bytes = vec![ + 1, 2, 3, 4, 5, 6, 0xaa, 0xbb, 7, 8, 9, 10, 11, 12, 0xcc, 0xdd, + ]; + canonicalize_fragment_render_target_padding(ll, &plan, &mut bytes); + assert_eq!( + bytes, + vec![1, 2, 3, 4, 5, 6, 0, 0, 7, 8, 9, 10, 11, 12, 0, 0] + ); } #[test] - fn supported_rgba_fragment_color_output_is_not_preflighted() { + fn rgba_fragment_color_output_is_not_canonicalized() { let ll = r#" define <4 x half> @frag() { ret <4 x half> zeroinitializer @@ -20007,7 +22643,31 @@ define <4 x half> @frag() { !18 = !{} "#; - assert!(unsupported_fragment_color_output_arity(ll).is_none()); + let plan = infer_plan(ll); + let mut bytes = vec![1, 2, 3, 4, 5, 6, 7, 8]; + canonicalize_fragment_render_target_padding(ll, &plan, &mut bytes); + assert_eq!(bytes, vec![1, 2, 3, 4, 5, 6, 7, 8]); + } + + #[test] + fn integer_rgb_fragment_output_uses_four_byte_padding_lane() { + let ll = r#" +define <3 x i32> @frag() { + ret <3 x i32> zeroinitializer +} + +!air.fragment = !{!15} +!15 = !{ptr @frag, !16, !18} +!16 = !{!17} +!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"int3"} +!18 = !{} +"#; + + let plan = infer_plan(ll); + let mut bytes = (1u8..=16).collect::>(); + canonicalize_fragment_render_target_padding(ll, &plan, &mut bytes); + assert_eq!(&bytes[..12], &(1u8..=12).collect::>()); + assert_eq!(&bytes[12..], &[0, 0, 0, 0]); } #[test] diff --git a/validation/src/corpus_shards.rs b/validation/src/corpus_shards.rs index 36d10dec6..32e51d466 100644 --- a/validation/src/corpus_shards.rs +++ b/validation/src/corpus_shards.rs @@ -266,6 +266,94 @@ pub fn gather_source_refs(public_dir: &Path, corpus_root: &Path) -> Vec, +) -> Vec { + let wanted_shards = wanted + .iter() + .map(|hash| shard_name_for_hash(hash)) + .collect::>(); + let mut out = gather_public_source_refs(public_dir, public_dir, "public", "synthetic") + .into_iter() + .filter(|source| wanted.contains(&source.air_sha256)) + .collect::>(); + for path in existing_shard_paths(corpus_root) { + let shard = path + .file_name() + .and_then(|s| s.to_str()) + .map(str::to_string) + .unwrap_or_else(|| "shard_unknown.jsonl".into()); + if !wanted_shards.contains(&shard) { + continue; + } + let Ok(file) = File::open(&path) else { + continue; + }; + let mut reader = BufReader::new(file); + let mut offset = 0u64; + let mut line = Vec::new(); + loop { + line.clear(); + let Ok(read) = reader.read_until(b'\n', &mut line) else { + break; + }; + if read == 0 { + break; + } + let len = trim_line_ending_len(&line); + if let Some(hash) = compact_json_string_field(&line[..len], b"air_sha256") { + if wanted.contains(hash) { + out.push(SourceRef { + air_sha256: hash.to_string(), + label: format!("local/{hash}.ll"), + kind: "private".into(), + shard: Some(shard.clone()), + storage: SourceStorage::ShardRow { + shard: shard.clone(), + byte_offset: offset, + byte_len: len, + }, + }); + } + } + offset += read as u64; + } + } + out +} + +pub(crate) fn compact_json_string_field<'a>(line: &'a [u8], field: &[u8]) -> Option<&'a str> { + let field_start = line.windows(field.len() + 2).position(|window| { + window.first() == Some(&b'"') + && window.get(1..=field.len()) == Some(field) + && window.last() == Some(&b'"') + })?; + let mut cursor = field_start + field.len() + 2; + while line.get(cursor).is_some_and(u8::is_ascii_whitespace) { + cursor += 1; + } + if line.get(cursor) != Some(&b':') { + return None; + } + cursor += 1; + while line.get(cursor).is_some_and(u8::is_ascii_whitespace) { + cursor += 1; + } + if line.get(cursor) != Some(&b'"') { + return None; + } + cursor += 1; + let end = line[cursor..].iter().position(|byte| *byte == b'"')? + cursor; + std::str::from_utf8(&line[cursor..end]).ok() +} + pub fn gather_shard_source_refs(corpus_root: &Path) -> Vec { let mut out = Vec::new(); for path in existing_shard_paths(corpus_root) { diff --git a/validation/src/corpus_triage.rs b/validation/src/corpus_triage.rs index 1a048f5b3..adcd3489f 100644 --- a/validation/src/corpus_triage.rs +++ b/validation/src/corpus_triage.rs @@ -200,7 +200,7 @@ mod tests { use super::*; #[test] - fn tolerance_success_depends_on_candidate_backend() { + fn tolerance_is_success_for_both_candidate_backends() { let row = TriageRow { kind: LedgerKind::Vulkan, air_sha256: "a".repeat(64), @@ -220,7 +220,7 @@ mod tests { kind: LedgerKind::MoltenVk, ..row }; - assert!(!moltenvk.is_success()); + assert!(moltenvk.is_success()); } #[test] diff --git a/validation/src/loop_budget.rs b/validation/src/loop_budget.rs index 59869e982..510c7adf9 100644 --- a/validation/src/loop_budget.rs +++ b/validation/src/loop_budget.rs @@ -30,7 +30,11 @@ use std::collections::{HashMap, HashSet}; /// marks instrumented kernels as `compare=none`; this cap is therefore a validation liveness guard, /// not a product semantic contract. Keep it large enough for bounded harness work but small enough /// that runaway SIMT reductions do not run into the corpus worker's wall timeout. -pub const LOOP_BUDGET_BACKEDGES: i32 = 1 << 18; +pub const LOOP_BUDGET_BACKEDGES: i32 = 1 << 12; +/// Cap used only when reproducing an already-banked semantic `plan_version < 3` Metal golden. +/// Historic `compare=none` rows are non-semantic and always use the safer cap above before they are +/// quarantined; their smoke bytes do not justify replaying the older, much larger budget. +pub const LEGACY_LOOP_BUDGET_BACKEDGES: i32 = 1 << 18; /// Result of classifying one module (entry + all defined functions). #[derive(Debug, Clone, PartialEq, Eq)] @@ -51,6 +55,8 @@ pub struct LoopInputFacts<'a> { pub arg_float_values: &'a [(String, f64)], pub arg_upper_bounds: &'a [(String, i128)], pub arg_field_values: &'a [(String, Vec, i128)], + /// Exact integer values loaded through constant byte (`getelementptr i8`) offsets. + pub arg_byte_values: &'a [(String, usize, i128)], pub arg_vector_values: &'a [(String, usize, i128)], pub arg_vector_upper_bounds: &'a [(String, usize, i128)], pub texture_extents: &'a [(String, [i128; 3])], @@ -145,6 +151,53 @@ pub fn classify_and_instrument_with_loop_input_facts( entry: &str, input_facts: LoopInputFacts<'_>, ) -> GuardPlan { + classify_and_instrument_with_loop_input_facts_and_budget( + module_text, + entry, + input_facts, + LOOP_BUDGET_BACKEDGES, + ) +} + +/// Return whether the entry's reachable static call graph contains any reachable CFG cycle. +/// +/// Unlike [`classify_and_instrument_with_loop_input_facts`], this does not erase loops whose trip +/// count appears small under the supplied facts. It is the conservative semantic-oracle gate: +/// proving termination is not the same as proving an aggregate GPU-time bound, especially for +/// nested loops and large loop bodies. +pub fn reachable_module_has_cfg_cycle_with_loop_input_facts( + module_text: &str, + entry: &str, + input_facts: LoopInputFacts<'_>, +) -> Result { + let lines = module_text.lines().collect::>(); + let funcs = find_functions(&lines); + if funcs.is_empty() { + return Ok(false); + } + let facts = LoopFacts::from_module(&lines, &input_facts); + let parsed = funcs + .iter() + .map(|function| parse_func_preserving_loops(&lines, function, &facts)) + .collect::, _>>()?; + let reachable = reachable_functions_from_entry(&parsed, entry); + Ok(parsed + .iter() + .filter(|function| reachable.contains(function.name.as_str())) + .any(|function| !function.back_edges.is_empty())) +} + +/// Classify and instrument using an explicit back-edge cap. This exists so candidate runners can +/// reproduce older banked Metal goldens while new oracle executions use the safer current cap. +pub fn classify_and_instrument_with_loop_input_facts_and_budget( + module_text: &str, + entry: &str, + input_facts: LoopInputFacts<'_>, + loop_budget_backedges: i32, +) -> GuardPlan { + if loop_budget_backedges <= 0 { + return GuardPlan::Quarantine("loop back-edge budget must be positive".into()); + } let _ = entry; let lines: Vec<&str> = module_text.lines().collect(); let funcs = find_functions(&lines); @@ -233,7 +286,7 @@ pub fn classify_and_instrument_with_loop_input_facts( out.push(line.to_string()); } } else { - match transform_func(&lines, f, pf, opaque_ptr) { + match transform_func(&lines, f, pf, opaque_ptr, loop_budget_backedges) { Ok(func_lines) => out.extend(func_lines), Err(reason) => return GuardPlan::Quarantine(reason), } @@ -411,6 +464,7 @@ struct LoopFacts { arg_ints: HashMap, arg_floats: HashMap, arg_field_ints: HashMap<(String, Vec), i128>, + arg_byte_ints: HashMap<(String, usize), i128>, arg_upper_bounds: HashMap, arg_vector_ints: HashMap<(String, usize), i128>, arg_vector_upper_bounds: HashMap<(String, usize), i128>, @@ -445,6 +499,13 @@ impl LoopFacts { ) }) .collect::>(); + let arg_byte_ints = input_facts + .arg_byte_values + .iter() + .map(|(name, offset, value)| { + ((name.trim_start_matches('%').to_string(), *offset), *value) + }) + .collect::>(); let arg_vector_ints = input_facts .arg_vector_values .iter() @@ -466,6 +527,7 @@ impl LoopFacts { arg_ints, arg_floats, arg_field_ints, + arg_byte_ints, arg_upper_bounds, arg_vector_ints, arg_vector_upper_bounds, @@ -542,6 +604,7 @@ impl LoopFacts { arg_ints, arg_floats, arg_field_ints, + arg_byte_ints, arg_upper_bounds, arg_vector_ints, arg_vector_upper_bounds, @@ -557,6 +620,7 @@ impl LoopFacts { && self.arg_ints.is_empty() && self.arg_floats.is_empty() && self.arg_field_ints.is_empty() + && self.arg_byte_ints.is_empty() && self.arg_upper_bounds.is_empty() && self.arg_vector_ints.is_empty() && self.arg_vector_upper_bounds.is_empty() @@ -576,6 +640,7 @@ impl LoopFacts { arg_ints: self.arg_ints.clone(), arg_floats: self.arg_floats.clone(), arg_field_ints: self.arg_field_ints.clone(), + arg_byte_ints: self.arg_byte_ints.clone(), arg_upper_bounds, arg_vector_ints: self.arg_vector_ints.clone(), arg_vector_upper_bounds: self.arg_vector_upper_bounds.clone(), @@ -884,6 +949,23 @@ struct CallSite { } fn parse_func(lines: &[&str], f: &FuncSpan, facts: &LoopFacts) -> Result { + parse_func_with_loop_elision(lines, f, facts, true) +} + +fn parse_func_preserving_loops( + lines: &[&str], + f: &FuncSpan, + facts: &LoopFacts, +) -> Result { + parse_func_with_loop_elision(lines, f, facts, false) +} + +fn parse_func_with_loop_elision( + lines: &[&str], + f: &FuncSpan, + facts: &LoopFacts, + elide_small_loops: bool, +) -> Result { let body = &lines[f.define_idx + 1..f.close_idx]; let blocks = parse_blocks(body, &f.name)?; @@ -913,7 +995,9 @@ fn parse_func(lines: &[&str], f: &FuncSpan, facts: &LoopFacts) -> Result>(); let loop_has_workgroup_barrier = back_edges.iter().any(|&(src, dst)| { natural_loop_nodes(&succ_idx, src, dst) @@ -1553,6 +1637,7 @@ fn transform_func( f: &FuncSpan, pf: &ParsedFunc, opaque_ptr: bool, + loop_budget_backedges: i32, ) -> Result, String> { let body_src = &lines[f.define_idx + 1..f.close_idx]; let mut body: Vec = body_src.iter().map(|s| s.to_string()).collect(); @@ -1686,7 +1771,7 @@ fn transform_func( }; let init = vec![ format!(" {budget} = alloca i32, align 4"), - format!(" store i32 {LOOP_BUDGET_BACKEDGES}, {ptr} {budget}, align 4"), + format!(" store i32 {loop_budget_backedges}, {ptr} {budget}, align 4"), ]; let mut emitted_body = Vec::with_capacity( body.len() + init.len() + guards_after.len() * 6 + budget_before.len() * 5 + 2, @@ -1741,7 +1826,156 @@ fn small_fixed_trip_loop( let const_loop = counted_const_loop(body, blocks, src, dst); let symbolic = counted_small_symbolic_loop(body, blocks, facts, src, dst); let consteval = counted_consteval_loop(body, blocks, facts, src, dst); - bool_toggle || const_loop || symbolic || consteval + let min_chunk = bounded_min_chunk_descending_loop(body, blocks, facts, src, dst); + bool_toggle || const_loop || symbolic || consteval || min_chunk +} + +/// Recognize `remaining -= min(remaining, positive_chunk)` loops. This is a common AIR memcpy / +/// tiled-copy shape. With a concrete small initial value and a positive chunk it reaches zero in a +/// bounded number of iterations without needing validation-only IR instrumentation. +fn bounded_min_chunk_descending_loop( + body: &[&str], + blocks: &[Block], + facts: &LoopFacts, + src: usize, + dst: usize, +) -> bool { + let header = &blocks[dst]; + let latch = &blocks[src]; + let Some(src_label) = latch.label.as_deref() else { + return false; + }; + let Some(dst_label) = header.label.as_deref() else { + return false; + }; + let latch_lines = block_lines(body, latch).collect::>(); + let Some(branch) = latch_lines + .iter() + .rev() + .copied() + .find(|line| line.trim_start().starts_with("br i1 ")) + else { + return false; + }; + let Some(backedge_on_true) = branch_backedge_on_true(branch, dst_label) else { + return false; + }; + let Some(condition) = branch_condition(branch) else { + return false; + }; + let Some(condition_line) = latch_lines + .iter() + .copied() + .find(|line| result_name(line).as_deref() == Some(condition.as_str())) + else { + return false; + }; + let Some((predicate, condition_lhs, condition_rhs)) = parse_icmp_value_operands(condition_line) + else { + return false; + }; + let continues_while_nonzero = + (predicate == "ne" && backedge_on_true) || (predicate == "eq" && !backedge_on_true); + if !continues_while_nonzero { + return false; + } + + let lines = body.to_vec(); + for ty in ["i32", "i64"] { + let bit_width = ty.trim_start_matches('i').parse::().unwrap_or(64); + for phi_line in + block_lines(body, header).filter(|line| line.contains(&format!(" = phi {ty} "))) + { + let Some(phi) = parse_integer_phi(phi_line, src_label, ty) else { + continue; + }; + let condition_lhs = condition_lhs.trim_start_matches('%'); + let condition_rhs = condition_rhs.trim_start_matches('%'); + if !((condition_lhs == phi.recur && condition_rhs == "0") + || (condition_rhs == phi.recur && condition_lhs == "0")) + { + continue; + } + let Some(recur_line) = lines + .iter() + .copied() + .find(|line| result_name(line).as_deref() == Some(phi.recur.as_str())) + else { + continue; + }; + let Some((_, sub_rhs)) = recur_line.split_once(" = sub ") else { + continue; + }; + let operands = sub_rhs + .split([',', ' ']) + .filter(|token| !token.is_empty()) + .collect::>(); + let Some(type_pos) = operands.iter().position(|token| *token == ty) else { + continue; + }; + let Some(base) = operands + .get(type_pos + 1) + .map(|token| token.trim_start_matches('%')) + else { + continue; + }; + let Some(chunk) = operands + .get(type_pos + 2) + .map(|token| token.trim_start_matches('%')) + else { + continue; + }; + if base != phi.name { + continue; + } + let Some(chunk_line) = lines + .iter() + .copied() + .find(|line| result_name(line).as_deref() == Some(chunk)) + else { + continue; + }; + if !chunk_line.contains("@air.min.") { + continue; + } + let Some(args) = chunk_line + .split_once(" = ") + .and_then(|(_, rhs)| call_arg_tokens(rhs)) + else { + continue; + }; + if args.len() < 2 { + continue; + } + let lhs = args[0].trim_start_matches('%'); + let rhs = args[1].trim_start_matches('%'); + let bound = if lhs == phi.name { + rhs + } else if rhs == phi.name { + lhs + } else { + continue; + }; + let Some(initial) = + small_integer_upper_bound_with_facts(&lines, facts, &phi.init, bit_width) + else { + continue; + }; + let Some(chunk) = + exact_positive_value(&lines, facts, bound, bit_width, &mut Vec::new()) + else { + continue; + }; + if initial < 0 || chunk <= 0 { + continue; + } + let trips = (initial.max(1) + chunk - 1) / chunk; + if (1..=256).contains(&trips) { + return true; + } + } + } + false } fn bool_toggle_loop(body: &[&str], blocks: &[Block], src: usize, dst: usize) -> bool { @@ -3654,15 +3888,27 @@ fn consteval_int_values(body: &[&str], facts: &LoopFacts) -> HashMap HashMap HashMap, +) -> Option<(String, String, usize)> { + if !line.contains(" = getelementptr ") || !line.contains(" i8,") { + return None; + } + let result = result_name(line)?; + let (arg, after_arg) = pointer_operand_and_tail_after(line, "ptr addrspace(") + .or_else(|| pointer_operand_and_tail_after(line, "addrspace("))?; + for raw in after_arg.split(',') { + let mut parts = raw.split_whitespace(); + let Some(ty) = parts.next() else { + continue; + }; + let Some(value) = parts.next() else { + continue; + }; + if !ty.starts_with('i') || !ty[1..].chars().all(|ch| ch.is_ascii_digit()) { + continue; + } + let offset = operand_const_value(value.trim_end_matches(','), values)?; + return Some((result, arg, usize::try_from(offset).ok()?)); + } + None +} + +fn first_percent_name(text: &str) -> Option { + let (_, tail) = text.split_once('%')?; + let name = tail + .split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '.' && ch != '_') + .next()?; + (!name.is_empty()).then(|| name.to_string()) +} + fn extractelement_result_vector_lane(line: &str) -> Option<(String, String, usize)> { let result = result_name(line)?; let (_, rhs) = line.split_once(" = extractelement <")?; @@ -5803,6 +6104,14 @@ define void @k(ptr addrspace(1) %0) { } "; assert_eq!(classify_and_instrument(ll, "k"), GuardPlan::LoopFree); + assert_eq!( + reachable_module_has_cfg_cycle_with_loop_input_facts( + ll, + "k", + LoopInputFacts::default(), + ), + Ok(false) + ); } #[test] @@ -5841,6 +6150,109 @@ define void @spin(ptr addrspace(1) %0) { ); } + #[test] + fn explicit_budget_is_embedded_and_must_be_positive() { + let ll = "\ +define void @spin(ptr addrspace(1) %0) { + br label %1 +1: + br label %1 +} +"; + let out = match classify_and_instrument_with_loop_input_facts_and_budget( + ll, + "spin", + LoopInputFacts::default(), + 7, + ) { + GuardPlan::Instrumented(text) => text, + other => panic!("expected Instrumented, got {other:?}"), + }; + assert!(out.contains("store i32 7, ptr %m2v.bd"), "{out}"); + assert_eq!( + classify_and_instrument_with_loop_input_facts_and_budget( + ll, + "spin", + LoopInputFacts::default(), + 0, + ), + GuardPlan::Quarantine("loop back-edge budget must be positive".into()) + ); + } + + #[test] + fn exact_raw_byte_field_proves_one_iteration_loop_bounded() { + let ll = r#" +define void @kernel(ptr addrspace(1) %source) { +entry: + %count.ptr = getelementptr inbounds i8, ptr addrspace(1) %source, i64 24 + %count.cast = bitcast ptr addrspace(1) %count.ptr to ptr addrspace(1) + %count = load i32, ptr addrspace(1) %count.cast, align 4 + br label %loop +loop: + %remaining = phi i32 [ %count, %entry ], [ %next, %loop ] + %next = sub i32 %remaining, 1 + %done = icmp eq i32 %next, 0 + br i1 %done, label %exit, label %loop +exit: + ret void +} +"#; + let byte_values = [("source".to_string(), 24, 1)]; + let facts_input = LoopInputFacts { + arg_byte_values: &byte_values, + ..LoopInputFacts::default() + }; + let lines = ll.lines().collect::>(); + let facts = LoopFacts::from_module(&lines, &facts_input); + let function = find_functions(&lines).remove(0); + let values = + consteval_int_values(&lines[function.define_idx + 1..function.close_idx], &facts); + assert_eq!(values.get("count"), Some(&1), "{values:?}"); + assert_eq!( + classify_and_instrument_with_loop_input_facts(ll, "kernel", facts_input,), + GuardPlan::LoopFree + ); + } + + #[test] + fn exact_raw_header_proves_min_chunk_descending_loop_bounded() { + let ll = r#" +define void @kernel(ptr addrspace(1) %source) { +entry: + %count.ptr = getelementptr inbounds i8, ptr addrspace(1) %source, i64 24 + %count = load i32, ptr addrspace(1) %count.ptr, align 4 + %wide = zext i32 %count to i64 + %bytes = shl i64 %wide, 4 + br label %loop +loop: + %remaining = phi i64 [ %bytes, %entry ], [ %next, %loop ] + %chunk = tail call i64 @air.min.u.i64(i64 %remaining, i64 1024) + %next = sub i64 %remaining, %chunk + %done = icmp eq i64 %next, 0 + br i1 %done, label %exit, label %loop +exit: + ret void +} +declare i64 @air.min.u.i64(i64, i64) +"#; + let byte_values = [("source".to_string(), 24, 1)]; + let facts_input = LoopInputFacts { + arg_byte_values: &byte_values, + ..LoopInputFacts::default() + }; + let lines = ll.lines().collect::>(); + let facts = LoopFacts::from_module(&lines, &facts_input); + let function = find_functions(&lines).remove(0); + let body = &lines[function.define_idx + 1..function.close_idx]; + let values = consteval_int_values(body, &facts); + assert_eq!(values.get("bytes"), Some(&16), "{values:?}"); + assert_eq!( + classify_and_instrument_with_loop_input_facts(ll, "kernel", facts_input,), + GuardPlan::LoopFree + ); + } + #[test] fn phi_predecessor_is_renamed_on_split_edge() { // Loop header `%loop` has a phi over {entry, latch}; the latch back-edge must have its phi @@ -6943,6 +7355,15 @@ declare i32 @air.atomic.local.add.u.i32(ptr addrspace(3), i32, i32, i32, i1) GuardPlan::LoopFree => {} other => panic!("expected fixed loops to be treated as bounded, got {other:?}"), } + assert_eq!( + reachable_module_has_cfg_cycle_with_loop_input_facts( + ll, + "fixed", + LoopInputFacts::default(), + ), + Ok(true), + "semantic safety gate must retain even proven finite CFG cycles" + ); } #[test] diff --git a/validation/src/oracle_macos.rs b/validation/src/oracle_macos.rs index 7c05e0e45..cc9752fcc 100644 --- a/validation/src/oracle_macos.rs +++ b/validation/src/oracle_macos.rs @@ -12,7 +12,7 @@ use base64::engine::general_purpose::STANDARD as BASE64; use base64::Engine as _; use core::ffi::c_void; use core::ptr::NonNull; -use metal2vulkan::meta::{FragRole, KernRole, VertRole}; +use metal2vulkan::meta::{FragRole, KernRole, VertOutRole, VertRole}; use objc2::rc::{autoreleasepool, Retained}; use objc2::runtime::ProtocolObject; use objc2_foundation::{NSArray, NSString, NSURL}; @@ -52,6 +52,7 @@ using namespace metal; struct Metal2VulkanValidationVertexOut { float4 position [[position]]; float2 coord [[user(coord)]]; + uint viewport [[viewport_array_index]]; }; vertex Metal2VulkanValidationVertexOut metal2vulkan_validation_fullscreen_vertex(uint vid [[vertex_id]]) { @@ -68,6 +69,7 @@ vertex Metal2VulkanValidationVertexOut metal2vulkan_validation_fullscreen_vertex Metal2VulkanValidationVertexOut out; out.position = float4(positions[vid], 0.0, 1.0); out.coord = coords[vid]; + out.viewport = 0; return out; } "#; @@ -88,6 +90,7 @@ pub fn execute_metallib_blob( inputs: &crate::Inputs, sanitized_ll: &str, source_metallib: Option<&Path>, + submit_gpu: bool, ) -> Vec { autoreleasepool(|_| { let tmp = scratch_dir_for("oracle-metallib"); @@ -122,17 +125,28 @@ pub fn execute_metallib_blob( .unwrap_or_else(|e| panic!("m2v-quarantine: metal-objdump failed: {e}")); let missing_visible_refs = missing_visible_function_reference_names(sanitized_ll, &module_text); - let zero_init = if sanitized_ll.contains("addrspace(3)") { - insert_threadgroup_zero_init(&module_text, function_name) + let rgb_widened = if stage == Stage::Fragment { + widen_fragment_rgb_entry(&module_text, function_name, sanitized_ll) } else { None }; - let analysis_text = zero_init.as_deref().unwrap_or(&module_text); + let structural_text = rgb_widened.as_deref().unwrap_or(&module_text); + let zero_init = if sanitized_ll.contains("addrspace(3)") { + insert_threadgroup_zero_init(structural_text, function_name) + } else { + None + }; + let analysis_text = zero_init.as_deref().unwrap_or(structural_text); let arg_values = exact_scalar_arg_values(analysis_text, function_name, inputs); let arg_float_values = exact_float_arg_values(analysis_text, function_name, inputs); let arg_upper_bounds = launch_scalar_arg_upper_bounds(analysis_text, function_name, inputs); let arg_field_values = exact_struct_arg_values(analysis_text, function_name, inputs); + let arg_byte_values = crate::corpus_run::exact_raw_integer_buffer_arg_byte_values( + analysis_text, + function_name, + inputs, + ); let arg_vector_values = exact_launch_vector_arg_values(analysis_text, function_name, inputs); let buffer_arg_vector_values = @@ -174,20 +188,36 @@ pub fn execute_metallib_blob( function_name, inputs, )); + let loop_input_facts = || crate::loop_budget::LoopInputFacts { + fc_values: &loop_guard_fc_values, + arg_values: &arg_values, + arg_float_values: &arg_float_values, + arg_upper_bounds: &arg_upper_bounds, + arg_field_values: &arg_field_values, + arg_byte_values: &arg_byte_values, + arg_vector_values: &arg_vector_values, + arg_vector_upper_bounds: &arg_vector_upper_bounds, + texture_extents: &texture_extents, + imageblock_extent, + }; + let has_reachable_cfg_cycle = + crate::loop_budget::reachable_module_has_cfg_cycle_with_loop_input_facts( + analysis_text, + function_name, + loop_input_facts(), + ) + .unwrap_or_else(|reason| panic!("m2v-quarantine: {reason}")); + if has_reachable_cfg_cycle && submit_gpu { + panic!( + "m2v-quarantine: reachable CFG cycle lacks a quantitative aggregate GPU-work \ + bound; semantic Metal submission refused" + ); + } + match crate::loop_budget::classify_and_instrument_with_loop_input_facts( analysis_text, function_name, - crate::loop_budget::LoopInputFacts { - fc_values: &loop_guard_fc_values, - arg_values: &arg_values, - arg_float_values: &arg_float_values, - arg_upper_bounds: &arg_upper_bounds, - arg_field_values: &arg_field_values, - arg_vector_values: &arg_vector_values, - arg_vector_upper_bounds: &arg_vector_upper_bounds, - texture_extents: &texture_extents, - imageblock_extent, - }, + loop_input_facts(), ) { crate::loop_budget::GuardPlan::Quarantine(reason) => { if !missing_visible_refs.is_empty() { @@ -207,8 +237,16 @@ pub fn execute_metallib_blob( unresolved_visible_function_references_message(&missing_visible_refs) ); } - // Candidate runners use compare=none to apply the same loop-budget transform before - // translating their SPIR-V, so the golden and candidate both cover bounded work. + if submit_gpu { + // The guard makes submission finite, but reaching its synthetic exit does not + // prove the original kernel terminated or preserve a semantic output oracle. + // Keep the compile-only preflight path below, but never bank bounded-smoke + // bytes as a successful Metal golden. + panic!( + "m2v-quarantine: kernel requires loop-budget instrumentation; bounded smoke \ + output is not a semantic Metal oracle" + ); + } set_oracle_compare(OracleCompare::MetalOnly); let text = substitute_imageblock_air_calls(&text, imageblock_extent); match link_module_text_with_rename_retry( @@ -225,11 +263,22 @@ pub fn execute_metallib_blob( } } crate::loop_budget::GuardPlan::LoopFree => { - if let Some(text) = zero_init { + if has_reachable_cfg_cycle { + // A legacy small-trip proof may leave the module byte-identical, but without + // an aggregate work estimate it is compile-only, not a semantic submission. + set_oracle_compare(OracleCompare::MetalOnly); + } + if let Some(text) = zero_init.as_deref().or(rgb_widened.as_deref()) { if text.contains("@air.load.implicit_imageblock.") { + if submit_gpu { + panic!( + "m2v-quarantine: implicit imageblock substitution is compile-only; \ + transformed output is not a semantic Metal oracle" + ); + } set_oracle_compare(OracleCompare::MetalOnly); } - let text = substitute_imageblock_air_calls(&text, imageblock_extent); + let text = substitute_imageblock_air_calls(text, imageblock_extent); match link_module_text_with_rename_retry( &text, &air_path, @@ -324,6 +373,7 @@ pub fn execute_metallib_blob( &effective_name, inputs, Some(sanitized_ll), + submit_gpu, ), Stage::Fragment => execute_render_fragment_library( &device, @@ -331,6 +381,7 @@ pub fn execute_metallib_blob( &effective_name, inputs, Some(sanitized_ll), + submit_gpu, ), Stage::Vertex => execute_vertex_library( &device, @@ -338,6 +389,7 @@ pub fn execute_metallib_blob( &effective_name, inputs, Some(sanitized_ll), + submit_gpu, ), } }) @@ -496,10 +548,9 @@ fn link_module_text_with_rename_retry( } } -/// How a candidate backend (`corpus-run-vulkan` / `-moltenvk`) should prepare this oracle golden. -/// Set per-case by [`execute_metallib_blob`]: a kernel that needed loop-budget instrumentation is -/// [`OracleCompare::MetalOnly`] because candidate runners must translate a guarded LL copy before -/// dispatching on Vulkan / MoltenVK. +/// Whether this invocation can produce a semantic oracle. Set per-case by +/// [`execute_metallib_blob`]: [`OracleCompare::MetalOnly`] identifies a compile-only transformed +/// module that must not be submitted or banked as candidate comparison evidence. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum OracleCompare { Full, @@ -2050,6 +2101,7 @@ fn execute_compute_library( entry: &str, inputs: &Inputs, sanitized_ll: Option<&str>, + submit_gpu: bool, ) -> Vec { let function = new_specialized_function(library, entry, sanitized_ll); let stage_inputs = sanitized_ll.map(compute_stage_inputs).unwrap_or_default(); @@ -2096,6 +2148,9 @@ fn execute_compute_library( ) }) }); + if !submit_gpu { + return Vec::new(); + } let queue = device .newCommandQueue() .expect("MTLDevice::newCommandQueue returned nil"); @@ -2367,6 +2422,260 @@ fn unresolved_visible_function_references_message(names: &[String]) -> String { out } +fn fragment_rgb_output_types(sanitized_ll: &str) -> Option<(&'static str, &'static str)> { + let meta = metal2vulkan::meta::parse_air_fragment_meta(sanitized_ll)?; + let mut location_zero_types = meta + .render_target_members + .iter() + .filter(|(_, location)| *location == 0) + .filter_map(|(member, _)| meta.render_target_type_name(*member)); + let type_name = location_zero_types.next()?; + if location_zero_types.any(|other| other != type_name) { + return None; + } + match type_name { + "half3" => Some(("half3", "half")), + "float3" => Some(("float3", "float")), + "ushort3" => Some(("ushort3", "i16")), + "short3" => Some(("short3", "i16")), + "uint3" => Some(("uint3", "i32")), + "int3" => Some(("int3", "i32")), + _ => None, + } +} + +/// Widen a three-component fragment entry to a four-component Metal attachment interface. +/// Only the entry ABI and its location-zero render-target metadata change; helper functions keep +/// their original types. The added lane is zero and is discarded by corpus output +/// canonicalization, so all shader-defined RGB bytes remain an exact oracle. +fn widen_fragment_rgb_entry( + module_text: &str, + function_name: &str, + sanitized_ll: &str, +) -> Option { + let (air_type, scalar_type) = fragment_rgb_output_types(sanitized_ll)?; + let narrow_type = format!("<3 x {scalar_type}>"); + let wide_type = format!("<4 x {scalar_type}>"); + let mut in_entry = false; + let mut widened_header = false; + let mut widened_returns = 0usize; + let mut widened_metadata = 0usize; + let mut widened_entry_metadata_refs = 0usize; + let mut out = String::with_capacity(module_text.len() + 256); + + for line in module_text.lines() { + let mut emitted = false; + if !in_entry + && defined_function_name(line).as_deref() == Some(function_name) + && line + .find('@') + .is_some_and(|at| line[..at].contains(&narrow_type)) + { + let at = line.find('@').expect("entry definition contains @"); + let type_pos = line[..at].rfind(&narrow_type)?; + out.push_str(&line[..type_pos]); + out.push_str(&wide_type); + out.push_str(&line[type_pos + narrow_type.len()..]); + out.push('\n'); + in_entry = true; + widened_header = true; + emitted = true; + } else if in_entry { + let indent_len = line.len() - line.trim_start().len(); + let trimmed = line.trim_start(); + let return_prefix = format!("ret {narrow_type} "); + if let Some(value_and_metadata) = trimmed.strip_prefix(&return_prefix) { + let (value, metadata) = value_and_metadata + .split_once(", !") + .map_or((value_and_metadata, None), |(value, metadata)| { + (value, Some(metadata)) + }); + let value_name = format!("%m2v.rgb.wide.{widened_returns}"); + let indent = &line[..indent_len]; + out.push_str(indent); + out.push_str(&value_name); + out.push_str(" = shufflevector "); + out.push_str(&narrow_type); + out.push(' '); + out.push_str(value.trim()); + out.push_str(", "); + out.push_str(&narrow_type); + out.push_str(" zeroinitializer, <4 x i32> \n"); + out.push_str(indent); + out.push_str("ret "); + out.push_str(&wide_type); + out.push(' '); + out.push_str(&value_name); + if let Some(metadata) = metadata { + out.push_str(", !"); + out.push_str(metadata); + } + out.push('\n'); + widened_returns += 1; + emitted = true; + } + if trimmed == "}" { + in_entry = false; + } + } + + if emitted { + continue; + } + if line.trim_start().starts_with('!') && symbol_reference_pos(line, function_name).is_some() + { + let at = symbol_reference_pos(line, function_name) + .expect("entry metadata reference was just found"); + if let Some(type_pos) = line[..at].rfind(&narrow_type) { + out.push_str(&line[..type_pos]); + out.push_str(&wide_type); + out.push_str(&line[type_pos + narrow_type.len()..]); + out.push('\n'); + } else { + // Opaque-pointer LLVM metadata spells the entry reference `ptr @entry`; there is + // no function type to rewrite, but the reference still proves we found the entry + // metadata node whose render-target child is widened below. + out.push_str(line); + out.push('\n'); + } + widened_entry_metadata_refs += 1; + } else if line.contains(r#"!"air.render_target""#) + && metadata_i32_after(line, "air.render_target") == Some(0) + && line.contains(&format!(r#"!"{air_type}""#)) + { + out.push_str(&line.replacen( + &format!(r#"!"{air_type}""#), + &format!(r#"!"{}4""#, air_type.trim_end_matches('3')), + 1, + )); + out.push('\n'); + widened_metadata += 1; + } else { + out.push_str(line); + out.push('\n'); + } + } + + if widened_header + && widened_returns != 0 + && widened_metadata != 0 + && widened_entry_metadata_refs != 0 + { + return Some(out); + } + widen_fragment_rgb_aggregate_entry( + module_text, + function_name, + air_type, + &narrow_type, + &wide_type, + ) +} + +fn widen_fragment_rgb_aggregate_entry( + module_text: &str, + function_name: &str, + air_type: &str, + narrow_type: &str, + wide_type: &str, +) -> Option { + let header = module_text.lines().find(|line| { + defined_function_name(line).as_deref() == Some(function_name) + && line + .find('@') + .is_some_and(|at| line[..at].contains("<{") && line[..at].contains(narrow_type)) + })?; + let at = header.find('@')?; + let aggregate_start = header[..at].rfind("<{")?; + let aggregate_end = header[aggregate_start..at].rfind("}>")? + aggregate_start + 2; + let narrow_aggregate = &header[aggregate_start..aggregate_end]; + let wide_aggregate = narrow_aggregate.replacen(narrow_type, wide_type, 1); + if wide_aggregate == narrow_aggregate { + return None; + } + + let mut in_entry = false; + let mut widened_insert = 0usize; + let mut widened_metadata = 0usize; + let mut entry_metadata_refs = 0usize; + let mut out = String::with_capacity(module_text.len() + 256); + for line in module_text.lines() { + if !in_entry && defined_function_name(line).as_deref() == Some(function_name) { + out.push_str(&line.replacen(narrow_aggregate, &wide_aggregate, 1)); + out.push('\n'); + in_entry = true; + continue; + } + if in_entry { + let trimmed = line.trim_start(); + let insert_marker = format!(", {narrow_type} "); + if trimmed.contains(" = insertvalue ") + && trimmed.ends_with(", 0") + && trimmed.contains(&insert_marker) + { + let value_start = line.find(&insert_marker)? + insert_marker.len(); + let value_end = line.rfind(", 0")?; + let value = line[value_start..value_end].trim(); + let indent = &line[..line.len() - trimmed.len()]; + let wide_value = format!("%m2v.rgb.aggregate.wide.{widened_insert}"); + out.push_str(indent); + out.push_str(&wide_value); + out.push_str(" = shufflevector "); + out.push_str(narrow_type); + out.push(' '); + out.push_str(value); + out.push_str(", "); + out.push_str(narrow_type); + out.push_str(" zeroinitializer, <4 x i32> \n"); + let replaced = line + .replacen(narrow_aggregate, &wide_aggregate, 1) + .replacen( + &format!("{insert_marker}{value}"), + &format!(", {wide_type} {wide_value}"), + 1, + ); + out.push_str(&replaced); + out.push('\n'); + widened_insert += 1; + continue; + } + out.push_str(&line.replace(narrow_aggregate, &wide_aggregate)); + out.push('\n'); + if trimmed == "}" { + in_entry = false; + } + continue; + } + if line.trim_start().starts_with('!') && symbol_reference_pos(line, function_name).is_some() + { + out.push_str(&line.replace(narrow_aggregate, &wide_aggregate)); + out.push('\n'); + entry_metadata_refs += 1; + } else if line.contains(r#"!"air.render_target""#) + && metadata_i32_after(line, "air.render_target") == Some(0) + && line.contains(&format!(r#"!"{air_type}""#)) + { + out.push_str(&line.replacen( + &format!(r#"!"{air_type}""#), + &format!(r#"!"{}4""#, air_type.trim_end_matches('3')), + 1, + )); + out.push('\n'); + widened_metadata += 1; + } else { + out.push_str(line); + out.push('\n'); + } + } + (widened_insert != 0 && widened_metadata != 0 && entry_metadata_refs != 0).then_some(out) +} + +fn symbol_reference_pos(line: &str, symbol: &str) -> Option { + line.match_indices('@').find_map(|(pos, _)| { + (symbol_after_at(&line[pos..]).as_deref() == Some(symbol)).then_some(pos) + }) +} + fn defined_function_names(module_text: &str) -> Vec { module_text .lines() @@ -2483,6 +2792,7 @@ fn execute_render_fragment_library( fragment_entry: &str, inputs: &Inputs, sanitized_ll: Option<&str>, + submit_gpu: bool, ) -> Vec { let (format, extent) = match inputs.output { Output::RenderTarget { format, extent } => (format, extent), @@ -2541,6 +2851,9 @@ fn execute_render_fragment_library( let pipeline = device .newRenderPipelineStateWithDescriptor_error(&pipeline_descriptor) .unwrap_or_else(|e| panic!("newRenderPipelineStateWithDescriptor({fragment_entry}): {e}")); + if !submit_gpu { + return Vec::new(); + } let depth_stencil_state = writes_depth.then(|| make_depth_stencil_state(device)); let target = make_render_target(device, format, extent); @@ -2790,6 +3103,7 @@ struct FragmentInput { } fn validation_vertex_src_for_fragment(sanitized_ll: Option<&str>) -> String { + let distinct_float3_inputs = sanitized_ll.is_some_and(fragment_requires_distinct_float3_inputs); let inputs = sanitized_ll .map(fragment_inputs) .unwrap_or_default() @@ -2815,6 +3129,7 @@ struct Metal2VulkanValidationVertexOut { "#, ); src.push_str(&format!(" float4 {position_field} [[position]];\n")); + src.push_str(" uint metal2vulkan_viewport [[viewport_array_index]];\n"); for (index, input) in inputs.iter().enumerate() { src.push_str(&format!( " {} {}{};\n", @@ -2844,8 +3159,11 @@ vertex Metal2VulkanValidationVertexOut metal2vulkan_validation_fullscreen_vertex src.push_str(&format!( " out.{position_field} = float4(positions[vid], 0.0, 1.0);\n" )); + src.push_str(" out.metal2vulkan_viewport = 0;\n"); for (index, input) in inputs.iter().enumerate() { - let value = validation_vertex_value(&input.type_name).expect("input type was filtered"); + let value = + validation_vertex_value_for_input(&input.type_name, index, distinct_float3_inputs) + .expect("input type was filtered"); src.push_str(&format!(" out.{} = {value};\n", field_names[index])); } src.push_str( @@ -2967,6 +3285,31 @@ fn validation_vertex_value(type_name: &str) -> Option<&'static str> { }) } +fn validation_vertex_value_for_input( + type_name: &str, + index: usize, + distinct_float3_inputs: bool, +) -> Option<&'static str> { + if type_name == "float3" && distinct_float3_inputs && index > 0 { + return Some("float3(coord, 1.0f)"); + } + validation_vertex_value(type_name) +} + +fn fragment_requires_distinct_float3_inputs(ll: &str) -> bool { + ll.lines() + .filter(|line| { + line.contains(r#""air.fragment_input""#) + && line.contains("!\"air.arg_type_name\", !\"float3\"") + }) + .count() + >= 2 + && ll.contains("@air.fast_rsqrt.f32") + && ll + .lines() + .any(|line| line.trim_start().contains(" = fsub ") && line.contains("<3 x float>")) +} + fn metadata_string_after(line: &str, marker: &str) -> Option { let marker = format!("!\"{marker}\", !\""); let tail = line.get(line.find(&marker)? + marker.len()..)?; @@ -2989,6 +3332,7 @@ fn execute_vertex_library( entry: &str, inputs: &Inputs, sanitized_ll: Option<&str>, + submit_gpu: bool, ) -> Vec { let (index, len) = match inputs.output { Output::Buffer { index, len, .. } => (index, len), @@ -3007,6 +3351,7 @@ fn execute_vertex_library( .expect("validation empty fragment function not found"); let vertex_inputs = sanitized_ll.map(vertex_inputs).unwrap_or_default(); + let writes_point_size = sanitized_ll.is_some_and(vertex_writes_point_size); let vertex_input_buffer_index = free_attribute_buffer_index(inputs); let pipeline_descriptor = MTLRenderPipelineDescriptor::new(); pipeline_descriptor.setVertexFunction(Some(&function)); @@ -3021,10 +3366,15 @@ fn execute_vertex_library( } else { pipeline_descriptor.setFragmentFunction(Some(&fragment_function)); } - // Standalone vertex validation also draws a triangle below; declare the topology for layered - // vertex outputs such as render_target_array_index. + // Metal requires a point topology when the vertex ABI writes [[point_size]]. Other standalone + // vertex cases retain the validation harness's triangle draw. Derive this from !air.vertex + // output roles so the oracle follows the shader interface rather than an entry-point name. unsafe { - pipeline_descriptor.setInputPrimitiveTopology(MTLPrimitiveTopologyClass::Triangle); + pipeline_descriptor.setInputPrimitiveTopology(if writes_point_size { + MTLPrimitiveTopologyClass::Point + } else { + MTLPrimitiveTopologyClass::Triangle + }); } let vertex_descriptor = if vertex_inputs.is_empty() { None @@ -3039,6 +3389,9 @@ fn execute_vertex_library( let pipeline = device .newRenderPipelineStateWithDescriptor_error(&pipeline_descriptor) .unwrap_or_else(|e| panic!("newRenderPipelineStateWithDescriptor({entry}): {e}")); + if !submit_gpu { + return Vec::new(); + } let _vertex_descriptor = vertex_descriptor; let target = make_render_target(device, DataFormat::Rgba8Unorm, inputs.render.target); @@ -3093,7 +3446,11 @@ fn execute_vertex_library( unsafe { encoder.setVertexSamplerState_atIndex(Some(&*default_sampler), 0); encoder.drawPrimitives_vertexStart_vertexCount( - MTLPrimitiveType::Triangle, + if writes_point_size { + MTLPrimitiveType::Point + } else { + MTLPrimitiveType::Triangle + }, 0, inputs.render.vertex_count as usize, ); @@ -3126,6 +3483,11 @@ fn execute_vertex_library( } } +fn vertex_writes_point_size(sanitized_ll: &str) -> bool { + metal2vulkan::meta::parse_air_vertex_meta(sanitized_ll) + .is_some_and(|meta| meta.output_roles.contains(&VertOutRole::PointSize)) +} + fn entry_function_returns_void(sanitized_ll: &str, entry: &str) -> bool { for line in sanitized_ll.lines() { let trimmed = line.trim_start(); @@ -4465,6 +4827,84 @@ define void @k(i32 %tgid, ptr addrspace(1) %queue) { ); } + #[test] + fn rgb_fragment_entry_is_widened_without_changing_rgb_helpers() { + let sanitized_ll = r#" +define <3 x half> @frag() { + ret <3 x half> zeroinitializer +} +!air.fragment = !{!15} +!15 = !{ptr @frag, !16, !18} +!16 = !{!17} +!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half3"} +!18 = !{} +"#; + let module_text = r#"; ModuleID = 'rgb' +define <3 x half> @frag(i1 %condition) { +entry: + br i1 %condition, label %left, label %right +left: + ret <3 x half> zeroinitializer +right: + ret <3 x half> +} +define internal <3 x half> @helper() { + ret <3 x half> zeroinitializer +} +!15 = !{<3 x half> (i1)* @frag, !16, !18} +!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half3"} +"#; + + let widened = widen_fragment_rgb_entry(module_text, "frag", sanitized_ll) + .expect("RGB fragment entry should widen"); + assert!(widened.contains("define <4 x half> @frag")); + assert_eq!(widened.matches("ret <4 x half> %m2v.rgb.wide.").count(), 2); + assert!(widened.contains("<3 x half> zeroinitializer, <4 x i32>")); + assert!(widened.contains("define internal <3 x half> @helper()")); + assert!(widened.contains("!15 = !{<4 x half> (i1)* @frag")); + assert!(widened.contains(r#"!"air.arg_type_name", !"half4""#)); + } + + #[test] + fn rgb_member_of_fragment_return_struct_is_widened() { + let ll = r#" +define <{ <3 x half>, half }> @frag() { + %rgb = insertvalue <{ <3 x half>, half }> undef, <3 x half> zeroinitializer, 0 + %rgba = insertvalue <{ <3 x half>, half }> %rgb, half 0xH3C00, 1 + ret <{ <3 x half>, half }> %rgba +} +!air.fragment = !{!15} +!15 = !{ptr @frag, !16, !19} +!16 = !{!17, !18} +!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half3"} +!18 = !{!"air.render_target", i32 1, i32 0, !"air.arg_type_name", !"half"} +!19 = !{} +"#; + + let widened = widen_fragment_rgb_entry(ll, "frag", ll) + .expect("aggregate RGB fragment entry should widen"); + assert!(widened.contains("define <{ <4 x half>, half }> @frag")); + assert!(widened.contains("%m2v.rgb.aggregate.wide.0 = shufflevector <3 x half>")); + assert!(widened.contains( + "insertvalue <{ <4 x half>, half }> undef, <4 x half> %m2v.rgb.aggregate.wide.0, 0" + )); + assert!(widened.contains("ret <{ <4 x half>, half }> %rgba")); + assert!(widened.contains(r#"!"air.arg_type_name", !"half4""#)); + } + + #[test] + fn rgba_fragment_entry_does_not_need_oracle_widening() { + let ll = r#" +define <4 x half> @frag() { ret <4 x half> zeroinitializer } +!air.fragment = !{!15} +!15 = !{ptr @frag, !16, !18} +!16 = !{!17} +!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"} +!18 = !{} +"#; + assert!(widen_fragment_rgb_entry(ll, "frag", ll).is_none()); + } + #[test] fn dynamic_resource_location_fcs_use_minimal_positive_values() { let ll = r#" @@ -4596,6 +5036,24 @@ define void @k(i32 %tgid, ptr addrspace(1) %queue) { assert!(src.contains("out.position = float3(coord, 0.5f);")); } + #[test] + fn validation_vertex_separates_duplicate_float3_rsqrt_inputs() { + let ll = r#" +define void @frag(<3 x float> %a, <3 x float> %b) { + %delta = fsub fast <3 x float> %a, %b + %len2 = tail call fast float @air.dot.v3f32(<3 x float> %delta, <3 x float> %delta) + %inv = tail call fast float @air.fast_rsqrt.f32(float %len2) + ret void +} +declare float @air.fast_rsqrt.f32(float) +!20 = !{i32 0, !"air.fragment_input", !"generated(a)", !"air.arg_type_name", !"float3", !"air.arg_name", !"a"} +!21 = !{i32 1, !"air.fragment_input", !"generated(b)", !"air.arg_type_name", !"float3", !"air.arg_name", !"b"} +"#; + let src = validation_vertex_src_for_fragment(Some(ll)); + assert!(src.contains("out.a = float3(coord, 0.5f);")); + assert!(src.contains("out.b = float3(coord, 1.0f);")); + } + #[test] fn validation_vertex_emits_flat_integer_and_bool_inputs() { let ll = r#" @@ -4799,6 +5257,29 @@ define void @progressTrackVertex(ptr addrspace(1) %out) { assert!(!entry_function_returns_void(ll, "missing")); } + #[test] + fn vertex_point_topology_follows_air_output_role() { + let point_ll = r#" +!air.vertex = !{!0} +!0 = !{ptr @vmain, !1, !4} +!1 = !{!2, !3} +!2 = !{!"air.position", !"air.arg_type_name", !"float4"} +!3 = !{!"air.point_size", !"air.arg_type_name", !"float"} +!4 = !{} +"#; + let triangle_ll = r#" +!air.vertex = !{!0} +!0 = !{ptr @vmain, !1, !3} +!1 = !{!2} +!2 = !{!"air.position", !"air.arg_type_name", !"float4"} +!3 = !{} +"#; + + assert!(vertex_writes_point_size(point_ll)); + assert!(!vertex_writes_point_size(triangle_ll)); + assert!(!vertex_writes_point_size("!air.vertex = !{}")); + } + /// End-to-end on the real Apple toolchain, but WITHOUT dispatching to the GPU: compile a kernel /// with a data-dependent (effectively unbounded) loop to AIR, disassemble it, run the loop-budget /// instrumentation, and prove `metal-as` + `metallib` accept the instrumented module. This is the diff --git a/validation/src/runner_linux.rs b/validation/src/runner_linux.rs index 73fce4d3e..3185443bc 100644 --- a/validation/src/runner_linux.rs +++ b/validation/src/runner_linux.rs @@ -37,6 +37,7 @@ use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, Standar use vulkano::pipeline::compute::ComputePipelineCreateInfo; use vulkano::pipeline::graphics::color_blend::{ AttachmentBlend, BlendFactor, BlendOp, ColorBlendAttachmentState, ColorBlendState, + ColorComponents, }; use vulkano::pipeline::graphics::depth_stencil::{CompareOp, DepthState, DepthStencilState}; use vulkano::pipeline::graphics::input_assembly::InputAssemblyState; @@ -197,6 +198,16 @@ pub(crate) fn fragment_writes_color_location(spv: &[u8], location: u32) -> bool } fn fragment_color_output_locations(spv: &[u8]) -> Vec { + fragment_color_output_component_counts(spv) + .into_keys() + .collect() +} + +fn fragment_color_output_component_counts(spv: &[u8]) -> HashMap { + const OP_TYPE_INT: u32 = 21; + const OP_TYPE_FLOAT: u32 = 22; + const OP_TYPE_VECTOR: u32 = 23; + const OP_TYPE_STRUCT: u32 = 30; const OP_TYPE_POINTER: u32 = 32; const OP_VARIABLE: u32 = 59; const OP_DECORATE: u32 = 71; @@ -205,10 +216,12 @@ fn fragment_color_output_locations(spv: &[u8]) -> Vec { const STORAGE_CLASS_OUTPUT: u32 = 3; let Ok(words) = bytes_to_words(spv) else { - return Vec::new(); + return HashMap::new(); }; let mut variable_locations = HashMap::new(); - let mut member_locations: HashMap> = HashMap::new(); + let mut member_locations = HashMap::new(); + let mut type_component_counts = HashMap::new(); + let mut struct_member_types: HashMap> = HashMap::new(); let mut pointer_pointees = HashMap::new(); let mut output_variables = Vec::new(); let mut index = 5usize; @@ -217,9 +230,21 @@ fn fragment_color_output_locations(spv: &[u8]) -> Vec { let word_count = (word >> 16) as usize; let opcode = word & 0xffff; if word_count == 0 || index + word_count > words.len() { - return Vec::new(); + return HashMap::new(); } match opcode { + OP_TYPE_INT | OP_TYPE_FLOAT if word_count >= 3 => { + type_component_counts.insert(words[index + 1], 1); + } + OP_TYPE_VECTOR if word_count >= 4 => { + type_component_counts.insert(words[index + 1], words[index + 3]); + } + OP_TYPE_STRUCT if word_count >= 2 => { + struct_member_types.insert( + words[index + 1], + words[index + 2..index + word_count].to_vec(), + ); + } OP_TYPE_POINTER if word_count >= 4 => { pointer_pointees.insert(words[index + 1], words[index + 3]); } @@ -230,31 +255,41 @@ fn fragment_color_output_locations(spv: &[u8]) -> Vec { variable_locations.insert(words[index + 1], words[index + 3]); } OP_MEMBER_DECORATE if word_count >= 5 && words[index + 3] == DECORATION_LOCATION => { - member_locations - .entry(words[index + 1]) - .or_default() - .push(words[index + 4]); + member_locations.insert((words[index + 1], words[index + 2]), words[index + 4]); } _ => {} } index += word_count; } - let mut out = output_variables - .into_iter() - .flat_map(|(variable_id, pointer_type_id)| { - let direct = variable_locations.get(&variable_id).copied().into_iter(); - let members = pointer_pointees - .get(&pointer_type_id) - .and_then(|pointee_id| member_locations.get(pointee_id)) - .into_iter() - .flatten() - .copied(); - direct.chain(members).collect::>() - }) - .collect::>(); - out.sort_unstable(); - out.dedup(); + let mut out = HashMap::new(); + for (variable_id, pointer_type_id) in output_variables { + let Some(&pointee_id) = pointer_pointees.get(&pointer_type_id) else { + continue; + }; + if let Some(&location) = variable_locations.get(&variable_id) { + if let Some(&count) = type_component_counts.get(&pointee_id) { + out.entry(location) + .and_modify(|seen: &mut u32| *seen = (*seen).max(count)) + .or_insert(count); + } + continue; + } + let Some(member_types) = struct_member_types.get(&pointee_id) else { + continue; + }; + for (member, type_id) in member_types.iter().copied().enumerate() { + let Some(&location) = member_locations.get(&(pointee_id, member as u32)) else { + continue; + }; + let Some(&count) = type_component_counts.get(&type_id) else { + continue; + }; + out.entry(location) + .and_modify(|seen: &mut u32| *seen = (*seen).max(count)) + .or_insert(count); + } + } out } @@ -1230,8 +1265,12 @@ pub fn device_and_queue_result( if physical_device.supported_features().sample_rate_shading { enabled_features.sample_rate_shading = true; } + if physical_device.supported_features().independent_blend { + enabled_features.independent_blend = true; + } let enabled_extensions = DeviceExtensions { ext_shader_atomic_float: true, + ext_filter_cubic: physical_device.supported_extensions().ext_filter_cubic, ext_shader_stencil_export: physical_device .supported_extensions() .ext_shader_stencil_export, @@ -1280,7 +1319,7 @@ fn compute_pipeline(device: Arc, spv: &[u8]) -> Result Option { None } -fn color_blend_attachment(blend: BlendMode) -> ColorBlendAttachmentState { - match blend { +fn color_blend_attachment( + blend: BlendMode, + output_component_count: Option, +) -> ColorBlendAttachmentState { + let color_write_mask = match output_component_count { + Some(1) => ColorComponents::R, + Some(2) => ColorComponents::R | ColorComponents::G, + Some(3) => ColorComponents::R | ColorComponents::G | ColorComponents::B, + _ => ColorComponents::all(), + }; + let mut state = match blend { BlendMode::Replace => ColorBlendAttachmentState::default(), BlendMode::SourceOver => ColorBlendAttachmentState { blend: Some(AttachmentBlend { @@ -1937,7 +1994,9 @@ fn color_blend_attachment(blend: BlendMode) -> ColorBlendAttachmentState { }), ..ColorBlendAttachmentState::default() }, - } + }; + state.color_write_mask = color_write_mask; + state } fn shader_stage(device: Arc, spv: &[u8]) -> PipelineShaderStageCreateInfo { @@ -2881,6 +2940,19 @@ fn texture_binding_req_for_index( }) } +fn placeholder_texture_binding_req_for_index( + reqs: &HashMap, + index: u32, +) -> Option<&TextureBindingReq> { + reqs.values() + .filter(|req| { + index >= req.index && index < req.index.saturating_add(req.descriptor_count.max(1)) + }) + // An explicit storage-image format is a hard SPIR-V constraint; a sampled-image scalar + // class is only a format-family hint. Prefer the former when descriptor arrays overlap. + .min_by_key(|req| (req.image_format.is_none(), !req.needs_storage, req.index)) +} + fn texture_binding_mutable_format_flag( reqs: &HashMap, index: u32, @@ -3270,16 +3342,18 @@ fn append_texture_placeholders( spv: &[u8], textures: &mut Vec, ) { - for req in required_texture_bindings(device, spv).into_values() { - let view_type = req.image_view_type.unwrap_or(ImageViewType::Dim2d); - let (image_type, array_layers, flags) = placeholder_image_shape(view_type); - let format = placeholder_format(&req); - let extent = [1u32, 1, 1]; - let usage = ImageUsage::TRANSFER_DST - | ImageUsage::TRANSFER_SRC - | texture_binding_image_usage(Some(&req)); + let reqs = required_texture_bindings(device, spv); + for req in reqs.values() { for offset in 0..req.descriptor_count { let index = req.index + offset; + let image_req = placeholder_texture_binding_req_for_index(&reqs, index).unwrap_or(req); + let view_type = image_req.image_view_type.unwrap_or(ImageViewType::Dim2d); + let (image_type, array_layers, flags) = placeholder_image_shape(view_type); + let format = placeholder_format(image_req); + let extent = [1u32, 1, 1]; + let usage = ImageUsage::TRANSFER_DST + | ImageUsage::TRANSFER_SRC + | texture_binding_image_usage_for_index(&reqs, index); if textures.iter().any(|texture| texture.index == index) { continue; } @@ -3380,8 +3454,18 @@ fn texture_view_for_req( } _ => {} } - ImageView::new(texture.image.clone(), view_info) - .unwrap_or_else(|e| panic!("create descriptor texture view {}: {e}", texture.index)) + let descriptor_format = view_info.format; + ImageView::new(texture.image.clone(), view_info).unwrap_or_else(|e| { + panic!( + "create descriptor texture view {} (image_format={:?}, descriptor_format={:?}, \ + image_flags={:?}, requirement={:?}): {e:?}", + texture.index, + texture.image.format(), + descriptor_format, + texture.image.flags(), + req + ) + }) } fn descriptor_view_format(parent_format: Format, req: Option<&TextureBindingReq>) -> Format { @@ -3822,9 +3906,21 @@ fn descriptor_set( let static_samplers = static_sampler_binding_states(sanitized_ll) .into_iter() .map(|(binding, state)| { - let sampler = Sampler::new(device.clone(), state.create_info()).unwrap_or_else(|e| { + let mut create_info = state.create_info(); + // The product lowers every supported AIR bicubic sample to explicit Catmull-Rom + // fetches, but its now-dead static sampler descriptor can remain in the reflected + // layout. MoltenVK does not expose EXT_filter_cubic, so use a legal placeholder for + // that unobserved descriptor. Unsupported bicubic shapes fail translation above. + if create_info.min_filter == Filter::Cubic + && !device.enabled_extensions().ext_filter_cubic + && !device.enabled_extensions().img_filter_cubic + { + create_info.min_filter = Filter::Nearest; + create_info.mag_filter = Filter::Nearest; + } + let sampler = Sampler::new(device.clone(), create_info).unwrap_or_else(|e| { panic!( - "create static sampler for AIR word {:#x} binding {binding}: {e}", + "create static sampler for AIR word {:#x} binding {binding}: {e:?}", state.word ) }); @@ -3978,10 +4074,10 @@ impl StaticSamplerState { decode_air_sampler_address((word >> 3) & 0x7), decode_air_sampler_address((word >> 6) & 0x7), ], - filter: if word & 0x0a00 == 0x0a00 { - Filter::Linear - } else { - Filter::Nearest + filter: match ((word >> 11) & 0x3, (word >> 9) & 0x3) { + (2, 2) => Filter::Cubic, + (1, 1) => Filter::Linear, + _ => Filter::Nearest, }, unnormalized_coordinates: word & 0x8000 != 0, } @@ -4197,6 +4293,28 @@ mod tests { words.iter().flat_map(|word| word.to_le_bytes()).collect() } + #[test] + fn fragment_rgb_output_limits_color_write_mask_to_declared_components() { + let mut words = vec![0x0723_0203, 0x0001_0300, 0, 8, 0]; + words.extend(spirv_inst(22, &[1, 16])); // %1 = OpTypeFloat 16 + words.extend(spirv_inst(23, &[2, 1, 3])); // %2 = OpTypeVector %1 3 + words.extend(spirv_inst(32, &[3, 3, 2])); // %3 = Output pointer to %2 + words.extend(spirv_inst(59, &[3, 4, 3])); // %4 = output variable + words.extend(spirv_inst(71, &[4, 30, 0])); // Location 0 + let spv = spirv_bytes(&words); + + assert_eq!( + fragment_color_output_component_counts(&spv).get(&0), + Some(&3) + ); + let state = color_blend_attachment(BlendMode::Replace, Some(3)); + assert_eq!( + state.color_write_mask, + ColorComponents::R | ColorComponents::G | ColorComponents::B + ); + assert!(!state.color_write_mask.intersects(ColorComponents::A)); + } + #[test] fn fragment_render_target_attachment_formats_include_all_mrt_locations() { let ll = r#" @@ -4515,6 +4633,38 @@ mod tests { assert!(!texture_binding_image_usage_for_index(&reqs, 5).intersects(ImageUsage::SAMPLED)); } + #[test] + fn overlapping_texture_array_requirements_combine_image_usage() { + let sampled = TextureBindingReq { + index: 0, + descriptor_count: 128, + needs_sampled: true, + needs_storage: false, + image_format: None, + image_scalar_type: Some(NumericType::Float), + image_view_type: Some(ImageViewType::Dim2d), + }; + let storage = TextureBindingReq { + index: 8, + descriptor_count: 128, + needs_sampled: false, + needs_storage: true, + image_format: Some(Format::R32_SFLOAT), + image_scalar_type: Some(NumericType::Float), + image_view_type: Some(ImageViewType::Dim2d), + }; + let reqs = HashMap::from([(0, sampled), (8, storage)]); + + let usage = texture_binding_image_usage_for_index(&reqs, 16); + + assert!(usage.intersects(ImageUsage::SAMPLED)); + assert!(usage.intersects(ImageUsage::STORAGE)); + assert_eq!( + placeholder_texture_binding_req_for_index(&reqs, 16).map(|req| req.index), + Some(8) + ); + } + #[test] fn reflected_sampled_image_array_requirement_overrides_later_texture_format() { let req = TextureBindingReq { @@ -4631,6 +4781,18 @@ mod tests { assert!(!states[0].unnormalized_coordinates); } + #[test] + fn static_sampler_state_decodes_bicubic_filter_bits() { + let states = static_sampler_states( + r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 562249, i64 0], align 8"#, + ); + + assert_eq!(states.len(), 1); + assert_eq!(states[0].address_mode, [SamplerAddressMode::ClampToEdge; 3]); + assert_eq!(states[0].filter, Filter::Cubic); + assert!(states[0].unnormalized_coordinates); + } + #[test] fn static_sampler_binding_skips_runtime_sampler_slots() { let states = static_sampler_binding_states(