Harden AIR translation and consumer validation

Expand structural image, buffer, control-flow, and passthrough lowering, including driver-safe relooper limits and regression coverage.\n\nExpose buffer extent, type, and refined access in reflection v4 for downstream consumers.\n\nHarden corpus oracle planning and loop safety, quarantine non-semantic rows, and refresh the affected translation and execution ledgers.\n\nVerified with cargo fmt --all, workspace clippy with warnings denied, and serial product and validation test suites.
This commit is contained in:
Anees Iqbal committed 2026-08-10 11:44:46 +02:00
1 parent 2e297dc887
commit 3fbe8e516b
35 files changed
+5970 -777

No files matched your search

+6 -2
View File
@@ -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 |
+28 -5
View File
@@ -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
+30 -2
View File
@@ -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:
+3 -2
View File
@@ -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()
+1 -6
View File
@@ -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
+76
View File
@@ -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<u32, u32>,
/// `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<u32, u32>,
/// `param_idx -> AIR buffer argument type name` for every stage.
pub buffer_type_names: HashMap<u32, String>,
/// `param_idx -> declared AIR read/write qualifier`.
pub buffer_accesses: HashMap<u32, BufferAccess>,
/// `param_idx -> AIR texture argument type name`, e.g. `texture2d<uint, read>`.
pub texture_type_names: HashMap<u32, String>,
/// 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<u32, u32>,
pub buffer_object_sizes: HashMap<u32, u32>,
pub buffer_type_names: HashMap<u32, String>,
pub buffer_accesses: HashMap<u32, BufferAccess>,
/// `param_idx -> AIR texture argument type name`, e.g. `texture2d<uint, read>`.
pub texture_type_names: HashMap<u32, String>,
}
@@ -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<u32, u32>,
/// `param_idx -> air.buffer_size` when AIR declares one exact reference-object extent.
pub buffer_object_sizes: HashMap<u32, u32>,
/// `param_idx -> AIR buffer argument type name`, e.g. `char`, `void`, or a struct name.
pub buffer_type_names: HashMap<u32, String>,
/// `param_idx -> declared AIR read/write qualifier`.
pub buffer_accesses: HashMap<u32, BufferAccess>,
/// `param_idx -> AIR texture argument type name`, e.g. `texture2d<uint, read>`.
pub texture_type_names: HashMap<u32, String>,
/// 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> {
string_after_marker(body, "air.arg_type_name")
}
fn declared_buffer_access(body: &str) -> Option<BufferAccess> {
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> {
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,
})
}
+24 -7
View File
@@ -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))
}
+43 -5
View File
@@ -451,6 +451,28 @@ impl Emitter {
instructions: &mut Vec<Instruction>,
) -> 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(())
+7 -2
View File
@@ -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());
+5
View File
@@ -98,6 +98,10 @@ pub(super) struct Emitter {
param_values: HashSet<String>,
inline_parameter_substitutions: Vec<(Word, Word)>,
raw_buffer_params: HashSet<String>,
/// 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<String>,
@@ -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(),
-19
View File
@@ -165,25 +165,6 @@ impl Emitter {
instructions: &mut Vec<Instruction>,
) -> Result<bool, String> {
match call.callee.as_str() {
// `air.get_null_texture_<dim>()` 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_<dim>(%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
+496 -1
View File
@@ -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<Word, Instruction> = 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<Word, Instruction> = module
.types_global_values
.iter()
.filter_map(|inst| inst.result_id.map(|id| (id, inst.clone())))
.collect();
let value_types: HashMap<Word, Word> = 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<Word> = module
.types_global_values
.iter()
.filter_map(|inst| inst.result_id)
.collect();
let mut positions = HashMap::new();
let mut uses: HashMap<Word, Vec<UseSite>> = 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::<Vec<_>>();
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<UseSite>,
},
}
#[derive(Clone)]
struct PhiPlan {
site: Site,
result: Word,
arms: Vec<(Word, Word)>,
consumers: Vec<PhiConsumer>,
}
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<Word> = 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::<Vec<_>>();
new_constants.sort_by_key(|inst| inst.result_id);
module
.types_global_values
.splice(first_variable..first_variable, new_constants);
let mut replacements = HashMap::<Site, Vec<Instruction>>::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<HashSet<usize>> {
let labels = function
.blocks
.iter()
.map(|block| block.label.as_ref().and_then(|label| label.result_id))
.collect::<Vec<_>>();
let by_label = labels
.iter()
.enumerate()
.filter_map(|(index, label)| label.map(|label| (label, index)))
.collect::<HashMap<_, _>>();
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::<Vec<_>>(),
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::<HashSet<_>>();
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,
+7
View File
@@ -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
}
+56 -5
View File
@@ -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<Word> {
/// 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
+12 -15
View File
@@ -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,
+52
View File
@@ -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#"
+22 -10
View File
@@ -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]
+1 -1
View File
@@ -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);
+268 -1
View File
@@ -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<Instruction>,
) -> Result<Word, String> {
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<Instruction>) -> [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<Instruction>| {
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<Instruction>| {
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,
+18
View File
@@ -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<u32> {
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::<std::collections::HashSet<_>>();
(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)
}
+10 -15
View File
@@ -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<Word, String> {
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).
+99 -12
View File
@@ -62,6 +62,7 @@ fn emit_float_value(
prefix: &str,
idx: usize,
lanes: u32,
distinct_float3: bool,
) -> Result<String, String> {
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<String>, prefix: &str, idx: usize, ty: &PassTy
id
}
fn passthrough_vertex_spvasm(meta: &meta::FragMeta) -> Result<String, String> {
fn passthrough_vertex_spvasm(
meta: &meta::FragMeta,
distinct_float3_inputs: bool,
) -> Result<String, String> {
let has_viewport_index = meta
.roles
.iter()
.any(|(_, role)| matches!(role, meta::FragRole::ViewportArrayIndex));
let mut locs: Vec<u32> = meta
.roles
.iter()
@@ -130,6 +141,9 @@ fn passthrough_vertex_spvasm(meta: &meta::FragMeta) -> Result<String, String> {
let mut out_types: BTreeSet<String> = 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<String, String> {
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<String, String> {
));
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<String, String> {
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<String, String> {
}
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<String, String> {
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<Vec<u8>, 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}");
}
}
+10 -6
View File
@@ -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<Vec<u8>> {
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();
+221 -18
View File
@@ -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<u32>,
/// For a buffer: the declared AIR argument byte size, when the metadata carries one.
pub declared_size: Option<u32>,
/// 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<BufferExtent>,
/// For a buffer with `air.struct_type_info`: the reconstructed AIR aggregate layout.
pub type_layout: Option<AirType>,
/// The AIR argument type name (`texture2d<uint, read>`, 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(&quoted))
})?;
let byte_start = ll
.lines()
.take(start)
.map(|line| line.len() + 1)
.sum::<usize>();
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(&quoted))?;
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<Vec<[u64; 2]>, String> {
let mut globals = std::collections::HashMap::<String, [u64; 2]>::new();
let mut nodes = std::collections::HashMap::<u32, String>::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<u32>) -> Option<ResourceAccess> {
match address_space {
Some(ADDRESS_SPACE_CONSTANT) => Some(ResourceAccess::ReadOnly),
_ => None,
fn buffer_extent(
object_size: Option<u32>,
declared_size: Option<u32>,
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<BufferAccess>,
address_space: Option<u32>,
) -> Option<ResourceAccess> {
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<u32>) -> ResourceBinding {
param_index,
address_space: None,
declared_size: None,
extent: None,
type_layout: None,
type_name: None,
texture_shape: None,
+48 -1
View File
@@ -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<float, write>".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);
+2 -29
View File
@@ -40,12 +40,6 @@ fn load_relooper_module(bytes: &[u8]) -> Result<Module, String> {
Ok(module)
}
fn load_relooper_module_capped(bytes: &[u8], max_blocks: usize) -> Result<Module, String> {
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<Vec<u8>> {
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<Vec<u8>> {
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,
Binary file not shown.
Binary file not shown.
Binary file not shown.
+3187 -527
View File
File diff suppressed because it is too large. Load diff
+88
View File
@@ -266,6 +266,94 @@ pub fn gather_source_refs(public_dir: &Path, corpus_root: &Path) -> Vec<SourceRe
sources
}
/// Build lightweight source references only for the requested AIR hashes.
///
/// Unlike [`gather_source_refs`], this does not deserialize every multi-megabyte shard row merely
/// to discover its hash. The corpus runners use it when a ledger filter has already selected the
/// relevant rows, keeping a full recovery scan's memory proportional to one shard row.
pub fn gather_source_refs_for_hashes(
public_dir: &Path,
corpus_root: &Path,
wanted: &HashSet<String>,
) -> Vec<SourceRef> {
let wanted_shards = wanted
.iter()
.map(|hash| shard_name_for_hash(hash))
.collect::<HashSet<_>>();
let mut out = gather_public_source_refs(public_dir, public_dir, "public", "synthetic")
.into_iter()
.filter(|source| wanted.contains(&source.air_sha256))
.collect::<Vec<_>>();
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<SourceRef> {
let mut out = Vec::new();
for path in existing_shard_paths(corpus_root) {
+2 -2
View File
@@ -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]
+426 -5
View File
@@ -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<i32>, 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<bool, String> {
let lines = module_text.lines().collect::<Vec<_>>();
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::<Result<Vec<_>, _>>()?;
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<String, i128>,
arg_floats: HashMap<String, f64>,
arg_field_ints: HashMap<(String, Vec<i32>), i128>,
arg_byte_ints: HashMap<(String, usize), i128>,
arg_upper_bounds: HashMap<String, i128>,
arg_vector_ints: HashMap<(String, usize), i128>,
arg_vector_upper_bounds: HashMap<(String, usize), i128>,
@@ -445,6 +499,13 @@ impl LoopFacts {
)
})
.collect::<HashMap<_, _>>();
let arg_byte_ints = input_facts
.arg_byte_values
.iter()
.map(|(name, offset, value)| {
((name.trim_start_matches('%').to_string(), *offset), *value)
})
.collect::<HashMap<_, _>>();
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<ParsedFunc, String> {
parse_func_with_loop_elision(lines, f, facts, true)
}
fn parse_func_preserving_loops(
lines: &[&str],
f: &FuncSpan,
facts: &LoopFacts,
) -> Result<ParsedFunc, String> {
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<ParsedFunc, String> {
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<ParsedF
let back_edges = back_edges(&succ_idx)
.into_iter()
.filter(|&(src, dst)| reachable[src] && reachable[dst])
.filter(|&(src, dst)| !small_fixed_trip_loop(body, &blocks, facts, src, dst))
.filter(|&(src, dst)| {
!elide_small_loops || !small_fixed_trip_loop(body, &blocks, facts, src, dst)
})
.collect::<Vec<_>>();
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<Vec<String>, String> {
let body_src = &lines[f.define_idx + 1..f.close_idx];
let mut body: Vec<String> = 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::<Vec<_>>();
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::<u32>().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::<Vec<_>>();
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<String, i12
let mut values = facts.arg_ints.clone();
let mut pointer_values = HashMap::new();
let mut pointer_field_paths = HashMap::new();
let mut pointer_byte_offsets = HashMap::new();
let mut pointer_arg_aliases = HashMap::new();
let mut vector_values = HashMap::new();
for line in body {
if let Some(pointer) = store_dest_pointer(line) {
pointer_values.remove(&pointer);
pointer_field_paths.remove(&pointer);
pointer_byte_offsets.remove(&pointer);
pointer_arg_aliases.remove(&pointer);
continue;
}
if let Some((result, arg, offset)) = byte_gep_result_arg_offset(line, &values) {
pointer_byte_offsets.insert(
result.trim_start_matches('%').to_string(),
(arg.clone(), offset),
);
if let Some(&value) = facts.arg_byte_ints.get(&(arg, offset)) {
pointer_values.insert(result.trim_start_matches('%').to_string(), value);
}
continue;
}
if let Some((result, arg, path)) = gep_result_arg_field_path(line, &values) {
pointer_field_paths.insert(
result.trim_start_matches('%').to_string(),
@@ -3673,6 +3919,26 @@ fn consteval_int_values(body: &[&str], facts: &LoopFacts) -> HashMap<String, i12
}
continue;
}
if line.contains(" = bitcast ") {
if let Some(result) = result_name(line) {
let rhs = line.split_once('=').map(|(_, rhs)| rhs).unwrap_or("");
if let Some(source) = first_percent_name(rhs) {
if let Some(value) = pointer_values.get(&source).copied() {
pointer_values.insert(result.clone(), value);
}
if let Some(field) = pointer_field_paths.get(&source).cloned() {
pointer_field_paths.insert(result.clone(), field);
}
if let Some(byte) = pointer_byte_offsets.get(&source).cloned() {
pointer_byte_offsets.insert(result.clone(), byte);
}
if let Some(alias) = pointer_arg_aliases.get(&source).cloned() {
pointer_arg_aliases.insert(result, alias);
}
}
}
continue;
}
if let Some((result, arg)) = gep_result_arg_root_alias(line, &values) {
pointer_arg_aliases.insert(result.trim_start_matches('%').to_string(), arg);
continue;
@@ -3797,6 +4063,41 @@ fn consteval_int_values(body: &[&str], facts: &LoopFacts) -> HashMap<String, i12
values
}
fn byte_gep_result_arg_offset(
line: &str,
values: &HashMap<String, i128>,
) -> 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<String> {
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::<Vec<_>>();
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::<Vec<_>>();
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]
+509 -28
View File
@@ -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<u8> {
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<u8> {
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<String> {
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> <i32 0, i32 1, i32 2, i32 3>\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<String> {
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> <i32 0, i32 1, i32 2, i32 3>\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<usize> {
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<String> {
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<u8> {
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<String> {
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<u8> {
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> <half 0xH3C00, half 0xH4000, half 0xH4200>
}
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
+208 -46
View File
@@ -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<u32> {
fragment_color_output_component_counts(spv)
.into_keys()
.collect()
}
fn fragment_color_output_component_counts(spv: &[u8]) -> HashMap<u32, u32> {
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<u32> {
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<u32, Vec<u32>> = HashMap::new();
let mut member_locations = HashMap::new();
let mut type_component_counts = HashMap::new();
let mut struct_member_types: HashMap<u32, Vec<u32>> = 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<u32> {
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<u32> {
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::<Vec<_>>()
})
.collect::<Vec<_>>();
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<Device>, spv: &[u8]) -> Result<Arc<ComputePipeli
None,
ComputePipelineCreateInfo::stage_layout(stage, layout),
)
.map_err(|error| format!("create compute pipeline: {error}"))
.map_err(|error| format!("create compute pipeline: {error} ({error:?})"))
}
#[derive(Clone, Debug)]
@@ -1333,10 +1372,19 @@ fn graphics_pipeline(
create_info.color_blend_state = if target.color_attachment_formats.is_empty() {
None
} else {
Some(ColorBlendState::with_attachment_states(
target.color_attachment_formats.len() as u32,
color_blend_attachment(blend),
))
let component_counts = fragment_color_output_component_counts(fragment_spv);
let attachments = target
.color_attachment_formats
.iter()
.enumerate()
.map(|(location, _)| {
color_blend_attachment(blend, component_counts.get(&(location as u32)).copied())
})
.collect();
Some(ColorBlendState {
attachments,
..Default::default()
})
};
let color_attachment_formats = target
.color_attachment_formats
@@ -1923,8 +1971,17 @@ fn vertex_validation_viewport_state() -> Option<ViewportState> {
None
}
fn color_blend_attachment(blend: BlendMode) -> ColorBlendAttachmentState {
match blend {
fn color_blend_attachment(
blend: BlendMode,
output_component_count: Option<u32>,
) -> 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<Device>, spv: &[u8]) -> PipelineShaderStageCreateInfo {
@@ -2881,6 +2940,19 @@ fn texture_binding_req_for_index(
})
}
fn placeholder_texture_binding_req_for_index(
reqs: &HashMap<u32, TextureBindingReq>,
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<u32, TextureBindingReq>,
index: u32,
@@ -3270,16 +3342,18 @@ fn append_texture_placeholders(
spv: &[u8],
textures: &mut Vec<TextureResource>,
) {
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(