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:
1 parent
2e297dc887
commit
3fbe8e516b
35 files changed
+5970
-777
No files matched your search
+3
-2
@@ -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
@@ -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
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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
@@ -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,
|
||||
|
||||
@@ -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#"
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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("ed))
|
||||
})?;
|
||||
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("ed))?;
|
||||
let open = function[symbol..].find('(')? + symbol;
|
||||
let mut depth = 0u32;
|
||||
let mut close = None;
|
||||
for (offset, character) in function[open..].char_indices() {
|
||||
match character {
|
||||
'(' => depth += 1,
|
||||
')' => {
|
||||
depth = depth.checked_sub(1)?;
|
||||
if depth == 0 {
|
||||
close = Some(open + offset);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let close = close?;
|
||||
let header_end = function[close + 1..].find('{')? + close + 1;
|
||||
let args = split_top_level_llvm(&function[open + 1..close]);
|
||||
let tail = &function[header_end + 1..];
|
||||
let body_end = tail.find("\n}").unwrap_or(tail.len());
|
||||
Some((args, &tail[..body_end]))
|
||||
}
|
||||
|
||||
fn split_top_level_llvm(text: &str) -> Vec<&str> {
|
||||
let mut out = Vec::new();
|
||||
let mut start = 0usize;
|
||||
let mut depth = 0i32;
|
||||
for (index, character) in text.char_indices() {
|
||||
match character {
|
||||
'(' | '[' | '{' | '<' => depth += 1,
|
||||
')' | ']' | '}' | '>' => depth -= 1,
|
||||
',' if depth == 0 => {
|
||||
out.push(text[start..index].trim());
|
||||
start = index + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !text[start..].trim().is_empty() {
|
||||
out.push(text[start..].trim());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn percent_tokens(text: &str) -> Vec<&str> {
|
||||
text.split('%')
|
||||
.skip(1)
|
||||
.filter_map(|tail| {
|
||||
let token = tail
|
||||
.split(|character: char| {
|
||||
!(character.is_ascii_alphanumeric() || character == '_' || character == '.')
|
||||
})
|
||||
.next()?;
|
||||
(!token.is_empty()).then_some(token)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn ssa_token_occurs(text: &str, name: &str) -> bool {
|
||||
percent_tokens(text).contains(&name)
|
||||
}
|
||||
|
||||
fn llvm_arg_has_attribute(arg: &str, attribute: &str) -> bool {
|
||||
arg.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
|
||||
.any(|token| token == attribute)
|
||||
}
|
||||
|
||||
fn parse_static_sampler_constants(ll: &str) -> Result<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
@@ -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
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user