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
+3187
-527
File diff suppressed because it is too large.
Load diff
@@ -266,6 +266,94 @@ pub fn gather_source_refs(public_dir: &Path, corpus_root: &Path) -> Vec<SourceRe
|
||||
sources
|
||||
}
|
||||
|
||||
/// Build lightweight source references only for the requested AIR hashes.
|
||||
///
|
||||
/// Unlike [`gather_source_refs`], this does not deserialize every multi-megabyte shard row merely
|
||||
/// to discover its hash. The corpus runners use it when a ledger filter has already selected the
|
||||
/// relevant rows, keeping a full recovery scan's memory proportional to one shard row.
|
||||
pub fn gather_source_refs_for_hashes(
|
||||
public_dir: &Path,
|
||||
corpus_root: &Path,
|
||||
wanted: &HashSet<String>,
|
||||
) -> Vec<SourceRef> {
|
||||
let wanted_shards = wanted
|
||||
.iter()
|
||||
.map(|hash| shard_name_for_hash(hash))
|
||||
.collect::<HashSet<_>>();
|
||||
let mut out = gather_public_source_refs(public_dir, public_dir, "public", "synthetic")
|
||||
.into_iter()
|
||||
.filter(|source| wanted.contains(&source.air_sha256))
|
||||
.collect::<Vec<_>>();
|
||||
for path in existing_shard_paths(corpus_root) {
|
||||
let shard = path
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| "shard_unknown.jsonl".into());
|
||||
if !wanted_shards.contains(&shard) {
|
||||
continue;
|
||||
}
|
||||
let Ok(file) = File::open(&path) else {
|
||||
continue;
|
||||
};
|
||||
let mut reader = BufReader::new(file);
|
||||
let mut offset = 0u64;
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
line.clear();
|
||||
let Ok(read) = reader.read_until(b'\n', &mut line) else {
|
||||
break;
|
||||
};
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
let len = trim_line_ending_len(&line);
|
||||
if let Some(hash) = compact_json_string_field(&line[..len], b"air_sha256") {
|
||||
if wanted.contains(hash) {
|
||||
out.push(SourceRef {
|
||||
air_sha256: hash.to_string(),
|
||||
label: format!("local/{hash}.ll"),
|
||||
kind: "private".into(),
|
||||
shard: Some(shard.clone()),
|
||||
storage: SourceStorage::ShardRow {
|
||||
shard: shard.clone(),
|
||||
byte_offset: offset,
|
||||
byte_len: len,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
offset += read as u64;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn compact_json_string_field<'a>(line: &'a [u8], field: &[u8]) -> Option<&'a str> {
|
||||
let field_start = line.windows(field.len() + 2).position(|window| {
|
||||
window.first() == Some(&b'"')
|
||||
&& window.get(1..=field.len()) == Some(field)
|
||||
&& window.last() == Some(&b'"')
|
||||
})?;
|
||||
let mut cursor = field_start + field.len() + 2;
|
||||
while line.get(cursor).is_some_and(u8::is_ascii_whitespace) {
|
||||
cursor += 1;
|
||||
}
|
||||
if line.get(cursor) != Some(&b':') {
|
||||
return None;
|
||||
}
|
||||
cursor += 1;
|
||||
while line.get(cursor).is_some_and(u8::is_ascii_whitespace) {
|
||||
cursor += 1;
|
||||
}
|
||||
if line.get(cursor) != Some(&b'"') {
|
||||
return None;
|
||||
}
|
||||
cursor += 1;
|
||||
let end = line[cursor..].iter().position(|byte| *byte == b'"')? + cursor;
|
||||
std::str::from_utf8(&line[cursor..end]).ok()
|
||||
}
|
||||
|
||||
pub fn gather_shard_source_refs(corpus_root: &Path) -> Vec<SourceRef> {
|
||||
let mut out = Vec::new();
|
||||
for path in existing_shard_paths(corpus_root) {
|
||||
|
||||
@@ -200,7 +200,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tolerance_success_depends_on_candidate_backend() {
|
||||
fn tolerance_is_success_for_both_candidate_backends() {
|
||||
let row = TriageRow {
|
||||
kind: LedgerKind::Vulkan,
|
||||
air_sha256: "a".repeat(64),
|
||||
@@ -220,7 +220,7 @@ mod tests {
|
||||
kind: LedgerKind::MoltenVk,
|
||||
..row
|
||||
};
|
||||
assert!(!moltenvk.is_success());
|
||||
assert!(moltenvk.is_success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -30,7 +30,11 @@ use std::collections::{HashMap, HashSet};
|
||||
/// marks instrumented kernels as `compare=none`; this cap is therefore a validation liveness guard,
|
||||
/// not a product semantic contract. Keep it large enough for bounded harness work but small enough
|
||||
/// that runaway SIMT reductions do not run into the corpus worker's wall timeout.
|
||||
pub const LOOP_BUDGET_BACKEDGES: i32 = 1 << 18;
|
||||
pub const LOOP_BUDGET_BACKEDGES: i32 = 1 << 12;
|
||||
/// Cap used only when reproducing an already-banked semantic `plan_version < 3` Metal golden.
|
||||
/// Historic `compare=none` rows are non-semantic and always use the safer cap above before they are
|
||||
/// quarantined; their smoke bytes do not justify replaying the older, much larger budget.
|
||||
pub const LEGACY_LOOP_BUDGET_BACKEDGES: i32 = 1 << 18;
|
||||
|
||||
/// Result of classifying one module (entry + all defined functions).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -51,6 +55,8 @@ pub struct LoopInputFacts<'a> {
|
||||
pub arg_float_values: &'a [(String, f64)],
|
||||
pub arg_upper_bounds: &'a [(String, i128)],
|
||||
pub arg_field_values: &'a [(String, Vec<i32>, i128)],
|
||||
/// Exact integer values loaded through constant byte (`getelementptr i8`) offsets.
|
||||
pub arg_byte_values: &'a [(String, usize, i128)],
|
||||
pub arg_vector_values: &'a [(String, usize, i128)],
|
||||
pub arg_vector_upper_bounds: &'a [(String, usize, i128)],
|
||||
pub texture_extents: &'a [(String, [i128; 3])],
|
||||
@@ -145,6 +151,53 @@ pub fn classify_and_instrument_with_loop_input_facts(
|
||||
entry: &str,
|
||||
input_facts: LoopInputFacts<'_>,
|
||||
) -> GuardPlan {
|
||||
classify_and_instrument_with_loop_input_facts_and_budget(
|
||||
module_text,
|
||||
entry,
|
||||
input_facts,
|
||||
LOOP_BUDGET_BACKEDGES,
|
||||
)
|
||||
}
|
||||
|
||||
/// Return whether the entry's reachable static call graph contains any reachable CFG cycle.
|
||||
///
|
||||
/// Unlike [`classify_and_instrument_with_loop_input_facts`], this does not erase loops whose trip
|
||||
/// count appears small under the supplied facts. It is the conservative semantic-oracle gate:
|
||||
/// proving termination is not the same as proving an aggregate GPU-time bound, especially for
|
||||
/// nested loops and large loop bodies.
|
||||
pub fn reachable_module_has_cfg_cycle_with_loop_input_facts(
|
||||
module_text: &str,
|
||||
entry: &str,
|
||||
input_facts: LoopInputFacts<'_>,
|
||||
) -> Result<bool, String> {
|
||||
let lines = module_text.lines().collect::<Vec<_>>();
|
||||
let funcs = find_functions(&lines);
|
||||
if funcs.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let facts = LoopFacts::from_module(&lines, &input_facts);
|
||||
let parsed = funcs
|
||||
.iter()
|
||||
.map(|function| parse_func_preserving_loops(&lines, function, &facts))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let reachable = reachable_functions_from_entry(&parsed, entry);
|
||||
Ok(parsed
|
||||
.iter()
|
||||
.filter(|function| reachable.contains(function.name.as_str()))
|
||||
.any(|function| !function.back_edges.is_empty()))
|
||||
}
|
||||
|
||||
/// Classify and instrument using an explicit back-edge cap. This exists so candidate runners can
|
||||
/// reproduce older banked Metal goldens while new oracle executions use the safer current cap.
|
||||
pub fn classify_and_instrument_with_loop_input_facts_and_budget(
|
||||
module_text: &str,
|
||||
entry: &str,
|
||||
input_facts: LoopInputFacts<'_>,
|
||||
loop_budget_backedges: i32,
|
||||
) -> GuardPlan {
|
||||
if loop_budget_backedges <= 0 {
|
||||
return GuardPlan::Quarantine("loop back-edge budget must be positive".into());
|
||||
}
|
||||
let _ = entry;
|
||||
let lines: Vec<&str> = module_text.lines().collect();
|
||||
let funcs = find_functions(&lines);
|
||||
@@ -233,7 +286,7 @@ pub fn classify_and_instrument_with_loop_input_facts(
|
||||
out.push(line.to_string());
|
||||
}
|
||||
} else {
|
||||
match transform_func(&lines, f, pf, opaque_ptr) {
|
||||
match transform_func(&lines, f, pf, opaque_ptr, loop_budget_backedges) {
|
||||
Ok(func_lines) => out.extend(func_lines),
|
||||
Err(reason) => return GuardPlan::Quarantine(reason),
|
||||
}
|
||||
@@ -411,6 +464,7 @@ struct LoopFacts {
|
||||
arg_ints: HashMap<String, i128>,
|
||||
arg_floats: HashMap<String, f64>,
|
||||
arg_field_ints: HashMap<(String, Vec<i32>), i128>,
|
||||
arg_byte_ints: HashMap<(String, usize), i128>,
|
||||
arg_upper_bounds: HashMap<String, i128>,
|
||||
arg_vector_ints: HashMap<(String, usize), i128>,
|
||||
arg_vector_upper_bounds: HashMap<(String, usize), i128>,
|
||||
@@ -445,6 +499,13 @@ impl LoopFacts {
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
let arg_byte_ints = input_facts
|
||||
.arg_byte_values
|
||||
.iter()
|
||||
.map(|(name, offset, value)| {
|
||||
((name.trim_start_matches('%').to_string(), *offset), *value)
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
let arg_vector_ints = input_facts
|
||||
.arg_vector_values
|
||||
.iter()
|
||||
@@ -466,6 +527,7 @@ impl LoopFacts {
|
||||
arg_ints,
|
||||
arg_floats,
|
||||
arg_field_ints,
|
||||
arg_byte_ints,
|
||||
arg_upper_bounds,
|
||||
arg_vector_ints,
|
||||
arg_vector_upper_bounds,
|
||||
@@ -542,6 +604,7 @@ impl LoopFacts {
|
||||
arg_ints,
|
||||
arg_floats,
|
||||
arg_field_ints,
|
||||
arg_byte_ints,
|
||||
arg_upper_bounds,
|
||||
arg_vector_ints,
|
||||
arg_vector_upper_bounds,
|
||||
@@ -557,6 +620,7 @@ impl LoopFacts {
|
||||
&& self.arg_ints.is_empty()
|
||||
&& self.arg_floats.is_empty()
|
||||
&& self.arg_field_ints.is_empty()
|
||||
&& self.arg_byte_ints.is_empty()
|
||||
&& self.arg_upper_bounds.is_empty()
|
||||
&& self.arg_vector_ints.is_empty()
|
||||
&& self.arg_vector_upper_bounds.is_empty()
|
||||
@@ -576,6 +640,7 @@ impl LoopFacts {
|
||||
arg_ints: self.arg_ints.clone(),
|
||||
arg_floats: self.arg_floats.clone(),
|
||||
arg_field_ints: self.arg_field_ints.clone(),
|
||||
arg_byte_ints: self.arg_byte_ints.clone(),
|
||||
arg_upper_bounds,
|
||||
arg_vector_ints: self.arg_vector_ints.clone(),
|
||||
arg_vector_upper_bounds: self.arg_vector_upper_bounds.clone(),
|
||||
@@ -884,6 +949,23 @@ struct CallSite {
|
||||
}
|
||||
|
||||
fn parse_func(lines: &[&str], f: &FuncSpan, facts: &LoopFacts) -> Result<ParsedFunc, String> {
|
||||
parse_func_with_loop_elision(lines, f, facts, true)
|
||||
}
|
||||
|
||||
fn parse_func_preserving_loops(
|
||||
lines: &[&str],
|
||||
f: &FuncSpan,
|
||||
facts: &LoopFacts,
|
||||
) -> Result<ParsedFunc, String> {
|
||||
parse_func_with_loop_elision(lines, f, facts, false)
|
||||
}
|
||||
|
||||
fn parse_func_with_loop_elision(
|
||||
lines: &[&str],
|
||||
f: &FuncSpan,
|
||||
facts: &LoopFacts,
|
||||
elide_small_loops: bool,
|
||||
) -> Result<ParsedFunc, String> {
|
||||
let body = &lines[f.define_idx + 1..f.close_idx];
|
||||
let blocks = parse_blocks(body, &f.name)?;
|
||||
|
||||
@@ -913,7 +995,9 @@ fn parse_func(lines: &[&str], f: &FuncSpan, facts: &LoopFacts) -> Result<ParsedF
|
||||
let back_edges = back_edges(&succ_idx)
|
||||
.into_iter()
|
||||
.filter(|&(src, dst)| reachable[src] && reachable[dst])
|
||||
.filter(|&(src, dst)| !small_fixed_trip_loop(body, &blocks, facts, src, dst))
|
||||
.filter(|&(src, dst)| {
|
||||
!elide_small_loops || !small_fixed_trip_loop(body, &blocks, facts, src, dst)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let loop_has_workgroup_barrier = back_edges.iter().any(|&(src, dst)| {
|
||||
natural_loop_nodes(&succ_idx, src, dst)
|
||||
@@ -1553,6 +1637,7 @@ fn transform_func(
|
||||
f: &FuncSpan,
|
||||
pf: &ParsedFunc,
|
||||
opaque_ptr: bool,
|
||||
loop_budget_backedges: i32,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let body_src = &lines[f.define_idx + 1..f.close_idx];
|
||||
let mut body: Vec<String> = body_src.iter().map(|s| s.to_string()).collect();
|
||||
@@ -1686,7 +1771,7 @@ fn transform_func(
|
||||
};
|
||||
let init = vec![
|
||||
format!(" {budget} = alloca i32, align 4"),
|
||||
format!(" store i32 {LOOP_BUDGET_BACKEDGES}, {ptr} {budget}, align 4"),
|
||||
format!(" store i32 {loop_budget_backedges}, {ptr} {budget}, align 4"),
|
||||
];
|
||||
let mut emitted_body = Vec::with_capacity(
|
||||
body.len() + init.len() + guards_after.len() * 6 + budget_before.len() * 5 + 2,
|
||||
@@ -1741,7 +1826,156 @@ fn small_fixed_trip_loop(
|
||||
let const_loop = counted_const_loop(body, blocks, src, dst);
|
||||
let symbolic = counted_small_symbolic_loop(body, blocks, facts, src, dst);
|
||||
let consteval = counted_consteval_loop(body, blocks, facts, src, dst);
|
||||
bool_toggle || const_loop || symbolic || consteval
|
||||
let min_chunk = bounded_min_chunk_descending_loop(body, blocks, facts, src, dst);
|
||||
bool_toggle || const_loop || symbolic || consteval || min_chunk
|
||||
}
|
||||
|
||||
/// Recognize `remaining -= min(remaining, positive_chunk)` loops. This is a common AIR memcpy /
|
||||
/// tiled-copy shape. With a concrete small initial value and a positive chunk it reaches zero in a
|
||||
/// bounded number of iterations without needing validation-only IR instrumentation.
|
||||
fn bounded_min_chunk_descending_loop(
|
||||
body: &[&str],
|
||||
blocks: &[Block],
|
||||
facts: &LoopFacts,
|
||||
src: usize,
|
||||
dst: usize,
|
||||
) -> bool {
|
||||
let header = &blocks[dst];
|
||||
let latch = &blocks[src];
|
||||
let Some(src_label) = latch.label.as_deref() else {
|
||||
return false;
|
||||
};
|
||||
let Some(dst_label) = header.label.as_deref() else {
|
||||
return false;
|
||||
};
|
||||
let latch_lines = block_lines(body, latch).collect::<Vec<_>>();
|
||||
let Some(branch) = latch_lines
|
||||
.iter()
|
||||
.rev()
|
||||
.copied()
|
||||
.find(|line| line.trim_start().starts_with("br i1 "))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(backedge_on_true) = branch_backedge_on_true(branch, dst_label) else {
|
||||
return false;
|
||||
};
|
||||
let Some(condition) = branch_condition(branch) else {
|
||||
return false;
|
||||
};
|
||||
let Some(condition_line) = latch_lines
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|line| result_name(line).as_deref() == Some(condition.as_str()))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some((predicate, condition_lhs, condition_rhs)) = parse_icmp_value_operands(condition_line)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let continues_while_nonzero =
|
||||
(predicate == "ne" && backedge_on_true) || (predicate == "eq" && !backedge_on_true);
|
||||
if !continues_while_nonzero {
|
||||
return false;
|
||||
}
|
||||
|
||||
let lines = body.to_vec();
|
||||
for ty in ["i32", "i64"] {
|
||||
let bit_width = ty.trim_start_matches('i').parse::<u32>().unwrap_or(64);
|
||||
for phi_line in
|
||||
block_lines(body, header).filter(|line| line.contains(&format!(" = phi {ty} ")))
|
||||
{
|
||||
let Some(phi) = parse_integer_phi(phi_line, src_label, ty) else {
|
||||
continue;
|
||||
};
|
||||
let condition_lhs = condition_lhs.trim_start_matches('%');
|
||||
let condition_rhs = condition_rhs.trim_start_matches('%');
|
||||
if !((condition_lhs == phi.recur && condition_rhs == "0")
|
||||
|| (condition_rhs == phi.recur && condition_lhs == "0"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(recur_line) = lines
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|line| result_name(line).as_deref() == Some(phi.recur.as_str()))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some((_, sub_rhs)) = recur_line.split_once(" = sub ") else {
|
||||
continue;
|
||||
};
|
||||
let operands = sub_rhs
|
||||
.split([',', ' '])
|
||||
.filter(|token| !token.is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
let Some(type_pos) = operands.iter().position(|token| *token == ty) else {
|
||||
continue;
|
||||
};
|
||||
let Some(base) = operands
|
||||
.get(type_pos + 1)
|
||||
.map(|token| token.trim_start_matches('%'))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(chunk) = operands
|
||||
.get(type_pos + 2)
|
||||
.map(|token| token.trim_start_matches('%'))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if base != phi.name {
|
||||
continue;
|
||||
}
|
||||
let Some(chunk_line) = lines
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|line| result_name(line).as_deref() == Some(chunk))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !chunk_line.contains("@air.min.") {
|
||||
continue;
|
||||
}
|
||||
let Some(args) = chunk_line
|
||||
.split_once(" = ")
|
||||
.and_then(|(_, rhs)| call_arg_tokens(rhs))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if args.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let lhs = args[0].trim_start_matches('%');
|
||||
let rhs = args[1].trim_start_matches('%');
|
||||
let bound = if lhs == phi.name {
|
||||
rhs
|
||||
} else if rhs == phi.name {
|
||||
lhs
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let Some(initial) =
|
||||
small_integer_upper_bound_with_facts(&lines, facts, &phi.init, bit_width)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(chunk) =
|
||||
exact_positive_value(&lines, facts, bound, bit_width, &mut Vec::new())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if initial < 0 || chunk <= 0 {
|
||||
continue;
|
||||
}
|
||||
let trips = (initial.max(1) + chunk - 1) / chunk;
|
||||
if (1..=256).contains(&trips) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn bool_toggle_loop(body: &[&str], blocks: &[Block], src: usize, dst: usize) -> bool {
|
||||
@@ -3654,15 +3888,27 @@ fn consteval_int_values(body: &[&str], facts: &LoopFacts) -> HashMap<String, i12
|
||||
let mut values = facts.arg_ints.clone();
|
||||
let mut pointer_values = HashMap::new();
|
||||
let mut pointer_field_paths = HashMap::new();
|
||||
let mut pointer_byte_offsets = HashMap::new();
|
||||
let mut pointer_arg_aliases = HashMap::new();
|
||||
let mut vector_values = HashMap::new();
|
||||
for line in body {
|
||||
if let Some(pointer) = store_dest_pointer(line) {
|
||||
pointer_values.remove(&pointer);
|
||||
pointer_field_paths.remove(&pointer);
|
||||
pointer_byte_offsets.remove(&pointer);
|
||||
pointer_arg_aliases.remove(&pointer);
|
||||
continue;
|
||||
}
|
||||
if let Some((result, arg, offset)) = byte_gep_result_arg_offset(line, &values) {
|
||||
pointer_byte_offsets.insert(
|
||||
result.trim_start_matches('%').to_string(),
|
||||
(arg.clone(), offset),
|
||||
);
|
||||
if let Some(&value) = facts.arg_byte_ints.get(&(arg, offset)) {
|
||||
pointer_values.insert(result.trim_start_matches('%').to_string(), value);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some((result, arg, path)) = gep_result_arg_field_path(line, &values) {
|
||||
pointer_field_paths.insert(
|
||||
result.trim_start_matches('%').to_string(),
|
||||
@@ -3673,6 +3919,26 @@ fn consteval_int_values(body: &[&str], facts: &LoopFacts) -> HashMap<String, i12
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if line.contains(" = bitcast ") {
|
||||
if let Some(result) = result_name(line) {
|
||||
let rhs = line.split_once('=').map(|(_, rhs)| rhs).unwrap_or("");
|
||||
if let Some(source) = first_percent_name(rhs) {
|
||||
if let Some(value) = pointer_values.get(&source).copied() {
|
||||
pointer_values.insert(result.clone(), value);
|
||||
}
|
||||
if let Some(field) = pointer_field_paths.get(&source).cloned() {
|
||||
pointer_field_paths.insert(result.clone(), field);
|
||||
}
|
||||
if let Some(byte) = pointer_byte_offsets.get(&source).cloned() {
|
||||
pointer_byte_offsets.insert(result.clone(), byte);
|
||||
}
|
||||
if let Some(alias) = pointer_arg_aliases.get(&source).cloned() {
|
||||
pointer_arg_aliases.insert(result, alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some((result, arg)) = gep_result_arg_root_alias(line, &values) {
|
||||
pointer_arg_aliases.insert(result.trim_start_matches('%').to_string(), arg);
|
||||
continue;
|
||||
@@ -3797,6 +4063,41 @@ fn consteval_int_values(body: &[&str], facts: &LoopFacts) -> HashMap<String, i12
|
||||
values
|
||||
}
|
||||
|
||||
fn byte_gep_result_arg_offset(
|
||||
line: &str,
|
||||
values: &HashMap<String, i128>,
|
||||
) -> Option<(String, String, usize)> {
|
||||
if !line.contains(" = getelementptr ") || !line.contains(" i8,") {
|
||||
return None;
|
||||
}
|
||||
let result = result_name(line)?;
|
||||
let (arg, after_arg) = pointer_operand_and_tail_after(line, "ptr addrspace(")
|
||||
.or_else(|| pointer_operand_and_tail_after(line, "addrspace("))?;
|
||||
for raw in after_arg.split(',') {
|
||||
let mut parts = raw.split_whitespace();
|
||||
let Some(ty) = parts.next() else {
|
||||
continue;
|
||||
};
|
||||
let Some(value) = parts.next() else {
|
||||
continue;
|
||||
};
|
||||
if !ty.starts_with('i') || !ty[1..].chars().all(|ch| ch.is_ascii_digit()) {
|
||||
continue;
|
||||
}
|
||||
let offset = operand_const_value(value.trim_end_matches(','), values)?;
|
||||
return Some((result, arg, usize::try_from(offset).ok()?));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn first_percent_name(text: &str) -> Option<String> {
|
||||
let (_, tail) = text.split_once('%')?;
|
||||
let name = tail
|
||||
.split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '.' && ch != '_')
|
||||
.next()?;
|
||||
(!name.is_empty()).then(|| name.to_string())
|
||||
}
|
||||
|
||||
fn extractelement_result_vector_lane(line: &str) -> Option<(String, String, usize)> {
|
||||
let result = result_name(line)?;
|
||||
let (_, rhs) = line.split_once(" = extractelement <")?;
|
||||
@@ -5803,6 +6104,14 @@ define void @k(ptr addrspace(1) %0) {
|
||||
}
|
||||
";
|
||||
assert_eq!(classify_and_instrument(ll, "k"), GuardPlan::LoopFree);
|
||||
assert_eq!(
|
||||
reachable_module_has_cfg_cycle_with_loop_input_facts(
|
||||
ll,
|
||||
"k",
|
||||
LoopInputFacts::default(),
|
||||
),
|
||||
Ok(false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -5841,6 +6150,109 @@ define void @spin(ptr addrspace(1) %0) {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_budget_is_embedded_and_must_be_positive() {
|
||||
let ll = "\
|
||||
define void @spin(ptr addrspace(1) %0) {
|
||||
br label %1
|
||||
1:
|
||||
br label %1
|
||||
}
|
||||
";
|
||||
let out = match classify_and_instrument_with_loop_input_facts_and_budget(
|
||||
ll,
|
||||
"spin",
|
||||
LoopInputFacts::default(),
|
||||
7,
|
||||
) {
|
||||
GuardPlan::Instrumented(text) => text,
|
||||
other => panic!("expected Instrumented, got {other:?}"),
|
||||
};
|
||||
assert!(out.contains("store i32 7, ptr %m2v.bd"), "{out}");
|
||||
assert_eq!(
|
||||
classify_and_instrument_with_loop_input_facts_and_budget(
|
||||
ll,
|
||||
"spin",
|
||||
LoopInputFacts::default(),
|
||||
0,
|
||||
),
|
||||
GuardPlan::Quarantine("loop back-edge budget must be positive".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_raw_byte_field_proves_one_iteration_loop_bounded() {
|
||||
let ll = r#"
|
||||
define void @kernel(ptr addrspace(1) %source) {
|
||||
entry:
|
||||
%count.ptr = getelementptr inbounds i8, ptr addrspace(1) %source, i64 24
|
||||
%count.cast = bitcast ptr addrspace(1) %count.ptr to ptr addrspace(1)
|
||||
%count = load i32, ptr addrspace(1) %count.cast, align 4
|
||||
br label %loop
|
||||
loop:
|
||||
%remaining = phi i32 [ %count, %entry ], [ %next, %loop ]
|
||||
%next = sub i32 %remaining, 1
|
||||
%done = icmp eq i32 %next, 0
|
||||
br i1 %done, label %exit, label %loop
|
||||
exit:
|
||||
ret void
|
||||
}
|
||||
"#;
|
||||
let byte_values = [("source".to_string(), 24, 1)];
|
||||
let facts_input = LoopInputFacts {
|
||||
arg_byte_values: &byte_values,
|
||||
..LoopInputFacts::default()
|
||||
};
|
||||
let lines = ll.lines().collect::<Vec<_>>();
|
||||
let facts = LoopFacts::from_module(&lines, &facts_input);
|
||||
let function = find_functions(&lines).remove(0);
|
||||
let values =
|
||||
consteval_int_values(&lines[function.define_idx + 1..function.close_idx], &facts);
|
||||
assert_eq!(values.get("count"), Some(&1), "{values:?}");
|
||||
assert_eq!(
|
||||
classify_and_instrument_with_loop_input_facts(ll, "kernel", facts_input,),
|
||||
GuardPlan::LoopFree
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_raw_header_proves_min_chunk_descending_loop_bounded() {
|
||||
let ll = r#"
|
||||
define void @kernel(ptr addrspace(1) %source) {
|
||||
entry:
|
||||
%count.ptr = getelementptr inbounds i8, ptr addrspace(1) %source, i64 24
|
||||
%count = load i32, ptr addrspace(1) %count.ptr, align 4
|
||||
%wide = zext i32 %count to i64
|
||||
%bytes = shl i64 %wide, 4
|
||||
br label %loop
|
||||
loop:
|
||||
%remaining = phi i64 [ %bytes, %entry ], [ %next, %loop ]
|
||||
%chunk = tail call i64 @air.min.u.i64(i64 %remaining, i64 1024)
|
||||
%next = sub i64 %remaining, %chunk
|
||||
%done = icmp eq i64 %next, 0
|
||||
br i1 %done, label %exit, label %loop
|
||||
exit:
|
||||
ret void
|
||||
}
|
||||
declare i64 @air.min.u.i64(i64, i64)
|
||||
"#;
|
||||
let byte_values = [("source".to_string(), 24, 1)];
|
||||
let facts_input = LoopInputFacts {
|
||||
arg_byte_values: &byte_values,
|
||||
..LoopInputFacts::default()
|
||||
};
|
||||
let lines = ll.lines().collect::<Vec<_>>();
|
||||
let facts = LoopFacts::from_module(&lines, &facts_input);
|
||||
let function = find_functions(&lines).remove(0);
|
||||
let body = &lines[function.define_idx + 1..function.close_idx];
|
||||
let values = consteval_int_values(body, &facts);
|
||||
assert_eq!(values.get("bytes"), Some(&16), "{values:?}");
|
||||
assert_eq!(
|
||||
classify_and_instrument_with_loop_input_facts(ll, "kernel", facts_input,),
|
||||
GuardPlan::LoopFree
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn phi_predecessor_is_renamed_on_split_edge() {
|
||||
// Loop header `%loop` has a phi over {entry, latch}; the latch back-edge must have its phi
|
||||
@@ -6943,6 +7355,15 @@ declare i32 @air.atomic.local.add.u.i32(ptr addrspace(3), i32, i32, i32, i1)
|
||||
GuardPlan::LoopFree => {}
|
||||
other => panic!("expected fixed loops to be treated as bounded, got {other:?}"),
|
||||
}
|
||||
assert_eq!(
|
||||
reachable_module_has_cfg_cycle_with_loop_input_facts(
|
||||
ll,
|
||||
"fixed",
|
||||
LoopInputFacts::default(),
|
||||
),
|
||||
Ok(true),
|
||||
"semantic safety gate must retain even proven finite CFG cycles"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+509
-28
@@ -12,7 +12,7 @@ use base64::engine::general_purpose::STANDARD as BASE64;
|
||||
use base64::Engine as _;
|
||||
use core::ffi::c_void;
|
||||
use core::ptr::NonNull;
|
||||
use metal2vulkan::meta::{FragRole, KernRole, VertRole};
|
||||
use metal2vulkan::meta::{FragRole, KernRole, VertOutRole, VertRole};
|
||||
use objc2::rc::{autoreleasepool, Retained};
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_foundation::{NSArray, NSString, NSURL};
|
||||
@@ -52,6 +52,7 @@ using namespace metal;
|
||||
struct Metal2VulkanValidationVertexOut {
|
||||
float4 position [[position]];
|
||||
float2 coord [[user(coord)]];
|
||||
uint viewport [[viewport_array_index]];
|
||||
};
|
||||
|
||||
vertex Metal2VulkanValidationVertexOut metal2vulkan_validation_fullscreen_vertex(uint vid [[vertex_id]]) {
|
||||
@@ -68,6 +69,7 @@ vertex Metal2VulkanValidationVertexOut metal2vulkan_validation_fullscreen_vertex
|
||||
Metal2VulkanValidationVertexOut out;
|
||||
out.position = float4(positions[vid], 0.0, 1.0);
|
||||
out.coord = coords[vid];
|
||||
out.viewport = 0;
|
||||
return out;
|
||||
}
|
||||
"#;
|
||||
@@ -88,6 +90,7 @@ pub fn execute_metallib_blob(
|
||||
inputs: &crate::Inputs,
|
||||
sanitized_ll: &str,
|
||||
source_metallib: Option<&Path>,
|
||||
submit_gpu: bool,
|
||||
) -> Vec<u8> {
|
||||
autoreleasepool(|_| {
|
||||
let tmp = scratch_dir_for("oracle-metallib");
|
||||
@@ -122,17 +125,28 @@ pub fn execute_metallib_blob(
|
||||
.unwrap_or_else(|e| panic!("m2v-quarantine: metal-objdump failed: {e}"));
|
||||
let missing_visible_refs =
|
||||
missing_visible_function_reference_names(sanitized_ll, &module_text);
|
||||
let zero_init = if sanitized_ll.contains("addrspace(3)") {
|
||||
insert_threadgroup_zero_init(&module_text, function_name)
|
||||
let rgb_widened = if stage == Stage::Fragment {
|
||||
widen_fragment_rgb_entry(&module_text, function_name, sanitized_ll)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let analysis_text = zero_init.as_deref().unwrap_or(&module_text);
|
||||
let structural_text = rgb_widened.as_deref().unwrap_or(&module_text);
|
||||
let zero_init = if sanitized_ll.contains("addrspace(3)") {
|
||||
insert_threadgroup_zero_init(structural_text, function_name)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let analysis_text = zero_init.as_deref().unwrap_or(structural_text);
|
||||
|
||||
let arg_values = exact_scalar_arg_values(analysis_text, function_name, inputs);
|
||||
let arg_float_values = exact_float_arg_values(analysis_text, function_name, inputs);
|
||||
let arg_upper_bounds = launch_scalar_arg_upper_bounds(analysis_text, function_name, inputs);
|
||||
let arg_field_values = exact_struct_arg_values(analysis_text, function_name, inputs);
|
||||
let arg_byte_values = crate::corpus_run::exact_raw_integer_buffer_arg_byte_values(
|
||||
analysis_text,
|
||||
function_name,
|
||||
inputs,
|
||||
);
|
||||
let arg_vector_values =
|
||||
exact_launch_vector_arg_values(analysis_text, function_name, inputs);
|
||||
let buffer_arg_vector_values =
|
||||
@@ -174,20 +188,36 @@ pub fn execute_metallib_blob(
|
||||
function_name,
|
||||
inputs,
|
||||
));
|
||||
let loop_input_facts = || crate::loop_budget::LoopInputFacts {
|
||||
fc_values: &loop_guard_fc_values,
|
||||
arg_values: &arg_values,
|
||||
arg_float_values: &arg_float_values,
|
||||
arg_upper_bounds: &arg_upper_bounds,
|
||||
arg_field_values: &arg_field_values,
|
||||
arg_byte_values: &arg_byte_values,
|
||||
arg_vector_values: &arg_vector_values,
|
||||
arg_vector_upper_bounds: &arg_vector_upper_bounds,
|
||||
texture_extents: &texture_extents,
|
||||
imageblock_extent,
|
||||
};
|
||||
let has_reachable_cfg_cycle =
|
||||
crate::loop_budget::reachable_module_has_cfg_cycle_with_loop_input_facts(
|
||||
analysis_text,
|
||||
function_name,
|
||||
loop_input_facts(),
|
||||
)
|
||||
.unwrap_or_else(|reason| panic!("m2v-quarantine: {reason}"));
|
||||
if has_reachable_cfg_cycle && submit_gpu {
|
||||
panic!(
|
||||
"m2v-quarantine: reachable CFG cycle lacks a quantitative aggregate GPU-work \
|
||||
bound; semantic Metal submission refused"
|
||||
);
|
||||
}
|
||||
|
||||
match crate::loop_budget::classify_and_instrument_with_loop_input_facts(
|
||||
analysis_text,
|
||||
function_name,
|
||||
crate::loop_budget::LoopInputFacts {
|
||||
fc_values: &loop_guard_fc_values,
|
||||
arg_values: &arg_values,
|
||||
arg_float_values: &arg_float_values,
|
||||
arg_upper_bounds: &arg_upper_bounds,
|
||||
arg_field_values: &arg_field_values,
|
||||
arg_vector_values: &arg_vector_values,
|
||||
arg_vector_upper_bounds: &arg_vector_upper_bounds,
|
||||
texture_extents: &texture_extents,
|
||||
imageblock_extent,
|
||||
},
|
||||
loop_input_facts(),
|
||||
) {
|
||||
crate::loop_budget::GuardPlan::Quarantine(reason) => {
|
||||
if !missing_visible_refs.is_empty() {
|
||||
@@ -207,8 +237,16 @@ pub fn execute_metallib_blob(
|
||||
unresolved_visible_function_references_message(&missing_visible_refs)
|
||||
);
|
||||
}
|
||||
// Candidate runners use compare=none to apply the same loop-budget transform before
|
||||
// translating their SPIR-V, so the golden and candidate both cover bounded work.
|
||||
if submit_gpu {
|
||||
// The guard makes submission finite, but reaching its synthetic exit does not
|
||||
// prove the original kernel terminated or preserve a semantic output oracle.
|
||||
// Keep the compile-only preflight path below, but never bank bounded-smoke
|
||||
// bytes as a successful Metal golden.
|
||||
panic!(
|
||||
"m2v-quarantine: kernel requires loop-budget instrumentation; bounded smoke \
|
||||
output is not a semantic Metal oracle"
|
||||
);
|
||||
}
|
||||
set_oracle_compare(OracleCompare::MetalOnly);
|
||||
let text = substitute_imageblock_air_calls(&text, imageblock_extent);
|
||||
match link_module_text_with_rename_retry(
|
||||
@@ -225,11 +263,22 @@ pub fn execute_metallib_blob(
|
||||
}
|
||||
}
|
||||
crate::loop_budget::GuardPlan::LoopFree => {
|
||||
if let Some(text) = zero_init {
|
||||
if has_reachable_cfg_cycle {
|
||||
// A legacy small-trip proof may leave the module byte-identical, but without
|
||||
// an aggregate work estimate it is compile-only, not a semantic submission.
|
||||
set_oracle_compare(OracleCompare::MetalOnly);
|
||||
}
|
||||
if let Some(text) = zero_init.as_deref().or(rgb_widened.as_deref()) {
|
||||
if text.contains("@air.load.implicit_imageblock.") {
|
||||
if submit_gpu {
|
||||
panic!(
|
||||
"m2v-quarantine: implicit imageblock substitution is compile-only; \
|
||||
transformed output is not a semantic Metal oracle"
|
||||
);
|
||||
}
|
||||
set_oracle_compare(OracleCompare::MetalOnly);
|
||||
}
|
||||
let text = substitute_imageblock_air_calls(&text, imageblock_extent);
|
||||
let text = substitute_imageblock_air_calls(text, imageblock_extent);
|
||||
match link_module_text_with_rename_retry(
|
||||
&text,
|
||||
&air_path,
|
||||
@@ -324,6 +373,7 @@ pub fn execute_metallib_blob(
|
||||
&effective_name,
|
||||
inputs,
|
||||
Some(sanitized_ll),
|
||||
submit_gpu,
|
||||
),
|
||||
Stage::Fragment => execute_render_fragment_library(
|
||||
&device,
|
||||
@@ -331,6 +381,7 @@ pub fn execute_metallib_blob(
|
||||
&effective_name,
|
||||
inputs,
|
||||
Some(sanitized_ll),
|
||||
submit_gpu,
|
||||
),
|
||||
Stage::Vertex => execute_vertex_library(
|
||||
&device,
|
||||
@@ -338,6 +389,7 @@ pub fn execute_metallib_blob(
|
||||
&effective_name,
|
||||
inputs,
|
||||
Some(sanitized_ll),
|
||||
submit_gpu,
|
||||
),
|
||||
}
|
||||
})
|
||||
@@ -496,10 +548,9 @@ fn link_module_text_with_rename_retry(
|
||||
}
|
||||
}
|
||||
|
||||
/// How a candidate backend (`corpus-run-vulkan` / `-moltenvk`) should prepare this oracle golden.
|
||||
/// Set per-case by [`execute_metallib_blob`]: a kernel that needed loop-budget instrumentation is
|
||||
/// [`OracleCompare::MetalOnly`] because candidate runners must translate a guarded LL copy before
|
||||
/// dispatching on Vulkan / MoltenVK.
|
||||
/// Whether this invocation can produce a semantic oracle. Set per-case by
|
||||
/// [`execute_metallib_blob`]: [`OracleCompare::MetalOnly`] identifies a compile-only transformed
|
||||
/// module that must not be submitted or banked as candidate comparison evidence.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OracleCompare {
|
||||
Full,
|
||||
@@ -2050,6 +2101,7 @@ fn execute_compute_library(
|
||||
entry: &str,
|
||||
inputs: &Inputs,
|
||||
sanitized_ll: Option<&str>,
|
||||
submit_gpu: bool,
|
||||
) -> Vec<u8> {
|
||||
let function = new_specialized_function(library, entry, sanitized_ll);
|
||||
let stage_inputs = sanitized_ll.map(compute_stage_inputs).unwrap_or_default();
|
||||
@@ -2096,6 +2148,9 @@ fn execute_compute_library(
|
||||
)
|
||||
})
|
||||
});
|
||||
if !submit_gpu {
|
||||
return Vec::new();
|
||||
}
|
||||
let queue = device
|
||||
.newCommandQueue()
|
||||
.expect("MTLDevice::newCommandQueue returned nil");
|
||||
@@ -2367,6 +2422,260 @@ fn unresolved_visible_function_references_message(names: &[String]) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn fragment_rgb_output_types(sanitized_ll: &str) -> Option<(&'static str, &'static str)> {
|
||||
let meta = metal2vulkan::meta::parse_air_fragment_meta(sanitized_ll)?;
|
||||
let mut location_zero_types = meta
|
||||
.render_target_members
|
||||
.iter()
|
||||
.filter(|(_, location)| *location == 0)
|
||||
.filter_map(|(member, _)| meta.render_target_type_name(*member));
|
||||
let type_name = location_zero_types.next()?;
|
||||
if location_zero_types.any(|other| other != type_name) {
|
||||
return None;
|
||||
}
|
||||
match type_name {
|
||||
"half3" => Some(("half3", "half")),
|
||||
"float3" => Some(("float3", "float")),
|
||||
"ushort3" => Some(("ushort3", "i16")),
|
||||
"short3" => Some(("short3", "i16")),
|
||||
"uint3" => Some(("uint3", "i32")),
|
||||
"int3" => Some(("int3", "i32")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Widen a three-component fragment entry to a four-component Metal attachment interface.
|
||||
/// Only the entry ABI and its location-zero render-target metadata change; helper functions keep
|
||||
/// their original types. The added lane is zero and is discarded by corpus output
|
||||
/// canonicalization, so all shader-defined RGB bytes remain an exact oracle.
|
||||
fn widen_fragment_rgb_entry(
|
||||
module_text: &str,
|
||||
function_name: &str,
|
||||
sanitized_ll: &str,
|
||||
) -> Option<String> {
|
||||
let (air_type, scalar_type) = fragment_rgb_output_types(sanitized_ll)?;
|
||||
let narrow_type = format!("<3 x {scalar_type}>");
|
||||
let wide_type = format!("<4 x {scalar_type}>");
|
||||
let mut in_entry = false;
|
||||
let mut widened_header = false;
|
||||
let mut widened_returns = 0usize;
|
||||
let mut widened_metadata = 0usize;
|
||||
let mut widened_entry_metadata_refs = 0usize;
|
||||
let mut out = String::with_capacity(module_text.len() + 256);
|
||||
|
||||
for line in module_text.lines() {
|
||||
let mut emitted = false;
|
||||
if !in_entry
|
||||
&& defined_function_name(line).as_deref() == Some(function_name)
|
||||
&& line
|
||||
.find('@')
|
||||
.is_some_and(|at| line[..at].contains(&narrow_type))
|
||||
{
|
||||
let at = line.find('@').expect("entry definition contains @");
|
||||
let type_pos = line[..at].rfind(&narrow_type)?;
|
||||
out.push_str(&line[..type_pos]);
|
||||
out.push_str(&wide_type);
|
||||
out.push_str(&line[type_pos + narrow_type.len()..]);
|
||||
out.push('\n');
|
||||
in_entry = true;
|
||||
widened_header = true;
|
||||
emitted = true;
|
||||
} else if in_entry {
|
||||
let indent_len = line.len() - line.trim_start().len();
|
||||
let trimmed = line.trim_start();
|
||||
let return_prefix = format!("ret {narrow_type} ");
|
||||
if let Some(value_and_metadata) = trimmed.strip_prefix(&return_prefix) {
|
||||
let (value, metadata) = value_and_metadata
|
||||
.split_once(", !")
|
||||
.map_or((value_and_metadata, None), |(value, metadata)| {
|
||||
(value, Some(metadata))
|
||||
});
|
||||
let value_name = format!("%m2v.rgb.wide.{widened_returns}");
|
||||
let indent = &line[..indent_len];
|
||||
out.push_str(indent);
|
||||
out.push_str(&value_name);
|
||||
out.push_str(" = shufflevector ");
|
||||
out.push_str(&narrow_type);
|
||||
out.push(' ');
|
||||
out.push_str(value.trim());
|
||||
out.push_str(", ");
|
||||
out.push_str(&narrow_type);
|
||||
out.push_str(" zeroinitializer, <4 x i32> <i32 0, i32 1, i32 2, i32 3>\n");
|
||||
out.push_str(indent);
|
||||
out.push_str("ret ");
|
||||
out.push_str(&wide_type);
|
||||
out.push(' ');
|
||||
out.push_str(&value_name);
|
||||
if let Some(metadata) = metadata {
|
||||
out.push_str(", !");
|
||||
out.push_str(metadata);
|
||||
}
|
||||
out.push('\n');
|
||||
widened_returns += 1;
|
||||
emitted = true;
|
||||
}
|
||||
if trimmed == "}" {
|
||||
in_entry = false;
|
||||
}
|
||||
}
|
||||
|
||||
if emitted {
|
||||
continue;
|
||||
}
|
||||
if line.trim_start().starts_with('!') && symbol_reference_pos(line, function_name).is_some()
|
||||
{
|
||||
let at = symbol_reference_pos(line, function_name)
|
||||
.expect("entry metadata reference was just found");
|
||||
if let Some(type_pos) = line[..at].rfind(&narrow_type) {
|
||||
out.push_str(&line[..type_pos]);
|
||||
out.push_str(&wide_type);
|
||||
out.push_str(&line[type_pos + narrow_type.len()..]);
|
||||
out.push('\n');
|
||||
} else {
|
||||
// Opaque-pointer LLVM metadata spells the entry reference `ptr @entry`; there is
|
||||
// no function type to rewrite, but the reference still proves we found the entry
|
||||
// metadata node whose render-target child is widened below.
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
widened_entry_metadata_refs += 1;
|
||||
} else if line.contains(r#"!"air.render_target""#)
|
||||
&& metadata_i32_after(line, "air.render_target") == Some(0)
|
||||
&& line.contains(&format!(r#"!"{air_type}""#))
|
||||
{
|
||||
out.push_str(&line.replacen(
|
||||
&format!(r#"!"{air_type}""#),
|
||||
&format!(r#"!"{}4""#, air_type.trim_end_matches('3')),
|
||||
1,
|
||||
));
|
||||
out.push('\n');
|
||||
widened_metadata += 1;
|
||||
} else {
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
|
||||
if widened_header
|
||||
&& widened_returns != 0
|
||||
&& widened_metadata != 0
|
||||
&& widened_entry_metadata_refs != 0
|
||||
{
|
||||
return Some(out);
|
||||
}
|
||||
widen_fragment_rgb_aggregate_entry(
|
||||
module_text,
|
||||
function_name,
|
||||
air_type,
|
||||
&narrow_type,
|
||||
&wide_type,
|
||||
)
|
||||
}
|
||||
|
||||
fn widen_fragment_rgb_aggregate_entry(
|
||||
module_text: &str,
|
||||
function_name: &str,
|
||||
air_type: &str,
|
||||
narrow_type: &str,
|
||||
wide_type: &str,
|
||||
) -> Option<String> {
|
||||
let header = module_text.lines().find(|line| {
|
||||
defined_function_name(line).as_deref() == Some(function_name)
|
||||
&& line
|
||||
.find('@')
|
||||
.is_some_and(|at| line[..at].contains("<{") && line[..at].contains(narrow_type))
|
||||
})?;
|
||||
let at = header.find('@')?;
|
||||
let aggregate_start = header[..at].rfind("<{")?;
|
||||
let aggregate_end = header[aggregate_start..at].rfind("}>")? + aggregate_start + 2;
|
||||
let narrow_aggregate = &header[aggregate_start..aggregate_end];
|
||||
let wide_aggregate = narrow_aggregate.replacen(narrow_type, wide_type, 1);
|
||||
if wide_aggregate == narrow_aggregate {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut in_entry = false;
|
||||
let mut widened_insert = 0usize;
|
||||
let mut widened_metadata = 0usize;
|
||||
let mut entry_metadata_refs = 0usize;
|
||||
let mut out = String::with_capacity(module_text.len() + 256);
|
||||
for line in module_text.lines() {
|
||||
if !in_entry && defined_function_name(line).as_deref() == Some(function_name) {
|
||||
out.push_str(&line.replacen(narrow_aggregate, &wide_aggregate, 1));
|
||||
out.push('\n');
|
||||
in_entry = true;
|
||||
continue;
|
||||
}
|
||||
if in_entry {
|
||||
let trimmed = line.trim_start();
|
||||
let insert_marker = format!(", {narrow_type} ");
|
||||
if trimmed.contains(" = insertvalue ")
|
||||
&& trimmed.ends_with(", 0")
|
||||
&& trimmed.contains(&insert_marker)
|
||||
{
|
||||
let value_start = line.find(&insert_marker)? + insert_marker.len();
|
||||
let value_end = line.rfind(", 0")?;
|
||||
let value = line[value_start..value_end].trim();
|
||||
let indent = &line[..line.len() - trimmed.len()];
|
||||
let wide_value = format!("%m2v.rgb.aggregate.wide.{widened_insert}");
|
||||
out.push_str(indent);
|
||||
out.push_str(&wide_value);
|
||||
out.push_str(" = shufflevector ");
|
||||
out.push_str(narrow_type);
|
||||
out.push(' ');
|
||||
out.push_str(value);
|
||||
out.push_str(", ");
|
||||
out.push_str(narrow_type);
|
||||
out.push_str(" zeroinitializer, <4 x i32> <i32 0, i32 1, i32 2, i32 3>\n");
|
||||
let replaced = line
|
||||
.replacen(narrow_aggregate, &wide_aggregate, 1)
|
||||
.replacen(
|
||||
&format!("{insert_marker}{value}"),
|
||||
&format!(", {wide_type} {wide_value}"),
|
||||
1,
|
||||
);
|
||||
out.push_str(&replaced);
|
||||
out.push('\n');
|
||||
widened_insert += 1;
|
||||
continue;
|
||||
}
|
||||
out.push_str(&line.replace(narrow_aggregate, &wide_aggregate));
|
||||
out.push('\n');
|
||||
if trimmed == "}" {
|
||||
in_entry = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if line.trim_start().starts_with('!') && symbol_reference_pos(line, function_name).is_some()
|
||||
{
|
||||
out.push_str(&line.replace(narrow_aggregate, &wide_aggregate));
|
||||
out.push('\n');
|
||||
entry_metadata_refs += 1;
|
||||
} else if line.contains(r#"!"air.render_target""#)
|
||||
&& metadata_i32_after(line, "air.render_target") == Some(0)
|
||||
&& line.contains(&format!(r#"!"{air_type}""#))
|
||||
{
|
||||
out.push_str(&line.replacen(
|
||||
&format!(r#"!"{air_type}""#),
|
||||
&format!(r#"!"{}4""#, air_type.trim_end_matches('3')),
|
||||
1,
|
||||
));
|
||||
out.push('\n');
|
||||
widened_metadata += 1;
|
||||
} else {
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
(widened_insert != 0 && widened_metadata != 0 && entry_metadata_refs != 0).then_some(out)
|
||||
}
|
||||
|
||||
fn symbol_reference_pos(line: &str, symbol: &str) -> Option<usize> {
|
||||
line.match_indices('@').find_map(|(pos, _)| {
|
||||
(symbol_after_at(&line[pos..]).as_deref() == Some(symbol)).then_some(pos)
|
||||
})
|
||||
}
|
||||
|
||||
fn defined_function_names(module_text: &str) -> Vec<String> {
|
||||
module_text
|
||||
.lines()
|
||||
@@ -2483,6 +2792,7 @@ fn execute_render_fragment_library(
|
||||
fragment_entry: &str,
|
||||
inputs: &Inputs,
|
||||
sanitized_ll: Option<&str>,
|
||||
submit_gpu: bool,
|
||||
) -> Vec<u8> {
|
||||
let (format, extent) = match inputs.output {
|
||||
Output::RenderTarget { format, extent } => (format, extent),
|
||||
@@ -2541,6 +2851,9 @@ fn execute_render_fragment_library(
|
||||
let pipeline = device
|
||||
.newRenderPipelineStateWithDescriptor_error(&pipeline_descriptor)
|
||||
.unwrap_or_else(|e| panic!("newRenderPipelineStateWithDescriptor({fragment_entry}): {e}"));
|
||||
if !submit_gpu {
|
||||
return Vec::new();
|
||||
}
|
||||
let depth_stencil_state = writes_depth.then(|| make_depth_stencil_state(device));
|
||||
|
||||
let target = make_render_target(device, format, extent);
|
||||
@@ -2790,6 +3103,7 @@ struct FragmentInput {
|
||||
}
|
||||
|
||||
fn validation_vertex_src_for_fragment(sanitized_ll: Option<&str>) -> String {
|
||||
let distinct_float3_inputs = sanitized_ll.is_some_and(fragment_requires_distinct_float3_inputs);
|
||||
let inputs = sanitized_ll
|
||||
.map(fragment_inputs)
|
||||
.unwrap_or_default()
|
||||
@@ -2815,6 +3129,7 @@ struct Metal2VulkanValidationVertexOut {
|
||||
"#,
|
||||
);
|
||||
src.push_str(&format!(" float4 {position_field} [[position]];\n"));
|
||||
src.push_str(" uint metal2vulkan_viewport [[viewport_array_index]];\n");
|
||||
for (index, input) in inputs.iter().enumerate() {
|
||||
src.push_str(&format!(
|
||||
" {} {}{};\n",
|
||||
@@ -2844,8 +3159,11 @@ vertex Metal2VulkanValidationVertexOut metal2vulkan_validation_fullscreen_vertex
|
||||
src.push_str(&format!(
|
||||
" out.{position_field} = float4(positions[vid], 0.0, 1.0);\n"
|
||||
));
|
||||
src.push_str(" out.metal2vulkan_viewport = 0;\n");
|
||||
for (index, input) in inputs.iter().enumerate() {
|
||||
let value = validation_vertex_value(&input.type_name).expect("input type was filtered");
|
||||
let value =
|
||||
validation_vertex_value_for_input(&input.type_name, index, distinct_float3_inputs)
|
||||
.expect("input type was filtered");
|
||||
src.push_str(&format!(" out.{} = {value};\n", field_names[index]));
|
||||
}
|
||||
src.push_str(
|
||||
@@ -2967,6 +3285,31 @@ fn validation_vertex_value(type_name: &str) -> Option<&'static str> {
|
||||
})
|
||||
}
|
||||
|
||||
fn validation_vertex_value_for_input(
|
||||
type_name: &str,
|
||||
index: usize,
|
||||
distinct_float3_inputs: bool,
|
||||
) -> Option<&'static str> {
|
||||
if type_name == "float3" && distinct_float3_inputs && index > 0 {
|
||||
return Some("float3(coord, 1.0f)");
|
||||
}
|
||||
validation_vertex_value(type_name)
|
||||
}
|
||||
|
||||
fn fragment_requires_distinct_float3_inputs(ll: &str) -> bool {
|
||||
ll.lines()
|
||||
.filter(|line| {
|
||||
line.contains(r#""air.fragment_input""#)
|
||||
&& line.contains("!\"air.arg_type_name\", !\"float3\"")
|
||||
})
|
||||
.count()
|
||||
>= 2
|
||||
&& ll.contains("@air.fast_rsqrt.f32")
|
||||
&& ll
|
||||
.lines()
|
||||
.any(|line| line.trim_start().contains(" = fsub ") && line.contains("<3 x float>"))
|
||||
}
|
||||
|
||||
fn metadata_string_after(line: &str, marker: &str) -> Option<String> {
|
||||
let marker = format!("!\"{marker}\", !\"");
|
||||
let tail = line.get(line.find(&marker)? + marker.len()..)?;
|
||||
@@ -2989,6 +3332,7 @@ fn execute_vertex_library(
|
||||
entry: &str,
|
||||
inputs: &Inputs,
|
||||
sanitized_ll: Option<&str>,
|
||||
submit_gpu: bool,
|
||||
) -> Vec<u8> {
|
||||
let (index, len) = match inputs.output {
|
||||
Output::Buffer { index, len, .. } => (index, len),
|
||||
@@ -3007,6 +3351,7 @@ fn execute_vertex_library(
|
||||
.expect("validation empty fragment function not found");
|
||||
|
||||
let vertex_inputs = sanitized_ll.map(vertex_inputs).unwrap_or_default();
|
||||
let writes_point_size = sanitized_ll.is_some_and(vertex_writes_point_size);
|
||||
let vertex_input_buffer_index = free_attribute_buffer_index(inputs);
|
||||
let pipeline_descriptor = MTLRenderPipelineDescriptor::new();
|
||||
pipeline_descriptor.setVertexFunction(Some(&function));
|
||||
@@ -3021,10 +3366,15 @@ fn execute_vertex_library(
|
||||
} else {
|
||||
pipeline_descriptor.setFragmentFunction(Some(&fragment_function));
|
||||
}
|
||||
// Standalone vertex validation also draws a triangle below; declare the topology for layered
|
||||
// vertex outputs such as render_target_array_index.
|
||||
// Metal requires a point topology when the vertex ABI writes [[point_size]]. Other standalone
|
||||
// vertex cases retain the validation harness's triangle draw. Derive this from !air.vertex
|
||||
// output roles so the oracle follows the shader interface rather than an entry-point name.
|
||||
unsafe {
|
||||
pipeline_descriptor.setInputPrimitiveTopology(MTLPrimitiveTopologyClass::Triangle);
|
||||
pipeline_descriptor.setInputPrimitiveTopology(if writes_point_size {
|
||||
MTLPrimitiveTopologyClass::Point
|
||||
} else {
|
||||
MTLPrimitiveTopologyClass::Triangle
|
||||
});
|
||||
}
|
||||
let vertex_descriptor = if vertex_inputs.is_empty() {
|
||||
None
|
||||
@@ -3039,6 +3389,9 @@ fn execute_vertex_library(
|
||||
let pipeline = device
|
||||
.newRenderPipelineStateWithDescriptor_error(&pipeline_descriptor)
|
||||
.unwrap_or_else(|e| panic!("newRenderPipelineStateWithDescriptor({entry}): {e}"));
|
||||
if !submit_gpu {
|
||||
return Vec::new();
|
||||
}
|
||||
let _vertex_descriptor = vertex_descriptor;
|
||||
|
||||
let target = make_render_target(device, DataFormat::Rgba8Unorm, inputs.render.target);
|
||||
@@ -3093,7 +3446,11 @@ fn execute_vertex_library(
|
||||
unsafe {
|
||||
encoder.setVertexSamplerState_atIndex(Some(&*default_sampler), 0);
|
||||
encoder.drawPrimitives_vertexStart_vertexCount(
|
||||
MTLPrimitiveType::Triangle,
|
||||
if writes_point_size {
|
||||
MTLPrimitiveType::Point
|
||||
} else {
|
||||
MTLPrimitiveType::Triangle
|
||||
},
|
||||
0,
|
||||
inputs.render.vertex_count as usize,
|
||||
);
|
||||
@@ -3126,6 +3483,11 @@ fn execute_vertex_library(
|
||||
}
|
||||
}
|
||||
|
||||
fn vertex_writes_point_size(sanitized_ll: &str) -> bool {
|
||||
metal2vulkan::meta::parse_air_vertex_meta(sanitized_ll)
|
||||
.is_some_and(|meta| meta.output_roles.contains(&VertOutRole::PointSize))
|
||||
}
|
||||
|
||||
fn entry_function_returns_void(sanitized_ll: &str, entry: &str) -> bool {
|
||||
for line in sanitized_ll.lines() {
|
||||
let trimmed = line.trim_start();
|
||||
@@ -4465,6 +4827,84 @@ define void @k(i32 %tgid, ptr addrspace(1) %queue) {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb_fragment_entry_is_widened_without_changing_rgb_helpers() {
|
||||
let sanitized_ll = r#"
|
||||
define <3 x half> @frag() {
|
||||
ret <3 x half> zeroinitializer
|
||||
}
|
||||
!air.fragment = !{!15}
|
||||
!15 = !{ptr @frag, !16, !18}
|
||||
!16 = !{!17}
|
||||
!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half3"}
|
||||
!18 = !{}
|
||||
"#;
|
||||
let module_text = r#"; ModuleID = 'rgb'
|
||||
define <3 x half> @frag(i1 %condition) {
|
||||
entry:
|
||||
br i1 %condition, label %left, label %right
|
||||
left:
|
||||
ret <3 x half> zeroinitializer
|
||||
right:
|
||||
ret <3 x half> <half 0xH3C00, half 0xH4000, half 0xH4200>
|
||||
}
|
||||
define internal <3 x half> @helper() {
|
||||
ret <3 x half> zeroinitializer
|
||||
}
|
||||
!15 = !{<3 x half> (i1)* @frag, !16, !18}
|
||||
!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half3"}
|
||||
"#;
|
||||
|
||||
let widened = widen_fragment_rgb_entry(module_text, "frag", sanitized_ll)
|
||||
.expect("RGB fragment entry should widen");
|
||||
assert!(widened.contains("define <4 x half> @frag"));
|
||||
assert_eq!(widened.matches("ret <4 x half> %m2v.rgb.wide.").count(), 2);
|
||||
assert!(widened.contains("<3 x half> zeroinitializer, <4 x i32>"));
|
||||
assert!(widened.contains("define internal <3 x half> @helper()"));
|
||||
assert!(widened.contains("!15 = !{<4 x half> (i1)* @frag"));
|
||||
assert!(widened.contains(r#"!"air.arg_type_name", !"half4""#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb_member_of_fragment_return_struct_is_widened() {
|
||||
let ll = r#"
|
||||
define <{ <3 x half>, half }> @frag() {
|
||||
%rgb = insertvalue <{ <3 x half>, half }> undef, <3 x half> zeroinitializer, 0
|
||||
%rgba = insertvalue <{ <3 x half>, half }> %rgb, half 0xH3C00, 1
|
||||
ret <{ <3 x half>, half }> %rgba
|
||||
}
|
||||
!air.fragment = !{!15}
|
||||
!15 = !{ptr @frag, !16, !19}
|
||||
!16 = !{!17, !18}
|
||||
!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half3"}
|
||||
!18 = !{!"air.render_target", i32 1, i32 0, !"air.arg_type_name", !"half"}
|
||||
!19 = !{}
|
||||
"#;
|
||||
|
||||
let widened = widen_fragment_rgb_entry(ll, "frag", ll)
|
||||
.expect("aggregate RGB fragment entry should widen");
|
||||
assert!(widened.contains("define <{ <4 x half>, half }> @frag"));
|
||||
assert!(widened.contains("%m2v.rgb.aggregate.wide.0 = shufflevector <3 x half>"));
|
||||
assert!(widened.contains(
|
||||
"insertvalue <{ <4 x half>, half }> undef, <4 x half> %m2v.rgb.aggregate.wide.0, 0"
|
||||
));
|
||||
assert!(widened.contains("ret <{ <4 x half>, half }> %rgba"));
|
||||
assert!(widened.contains(r#"!"air.arg_type_name", !"half4""#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgba_fragment_entry_does_not_need_oracle_widening() {
|
||||
let ll = r#"
|
||||
define <4 x half> @frag() { ret <4 x half> zeroinitializer }
|
||||
!air.fragment = !{!15}
|
||||
!15 = !{ptr @frag, !16, !18}
|
||||
!16 = !{!17}
|
||||
!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"half4"}
|
||||
!18 = !{}
|
||||
"#;
|
||||
assert!(widen_fragment_rgb_entry(ll, "frag", ll).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_resource_location_fcs_use_minimal_positive_values() {
|
||||
let ll = r#"
|
||||
@@ -4596,6 +5036,24 @@ define void @k(i32 %tgid, ptr addrspace(1) %queue) {
|
||||
assert!(src.contains("out.position = float3(coord, 0.5f);"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_vertex_separates_duplicate_float3_rsqrt_inputs() {
|
||||
let ll = r#"
|
||||
define void @frag(<3 x float> %a, <3 x float> %b) {
|
||||
%delta = fsub fast <3 x float> %a, %b
|
||||
%len2 = tail call fast float @air.dot.v3f32(<3 x float> %delta, <3 x float> %delta)
|
||||
%inv = tail call fast float @air.fast_rsqrt.f32(float %len2)
|
||||
ret void
|
||||
}
|
||||
declare float @air.fast_rsqrt.f32(float)
|
||||
!20 = !{i32 0, !"air.fragment_input", !"generated(a)", !"air.arg_type_name", !"float3", !"air.arg_name", !"a"}
|
||||
!21 = !{i32 1, !"air.fragment_input", !"generated(b)", !"air.arg_type_name", !"float3", !"air.arg_name", !"b"}
|
||||
"#;
|
||||
let src = validation_vertex_src_for_fragment(Some(ll));
|
||||
assert!(src.contains("out.a = float3(coord, 0.5f);"));
|
||||
assert!(src.contains("out.b = float3(coord, 1.0f);"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_vertex_emits_flat_integer_and_bool_inputs() {
|
||||
let ll = r#"
|
||||
@@ -4799,6 +5257,29 @@ define void @progressTrackVertex(ptr addrspace(1) %out) {
|
||||
assert!(!entry_function_returns_void(ll, "missing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertex_point_topology_follows_air_output_role() {
|
||||
let point_ll = r#"
|
||||
!air.vertex = !{!0}
|
||||
!0 = !{ptr @vmain, !1, !4}
|
||||
!1 = !{!2, !3}
|
||||
!2 = !{!"air.position", !"air.arg_type_name", !"float4"}
|
||||
!3 = !{!"air.point_size", !"air.arg_type_name", !"float"}
|
||||
!4 = !{}
|
||||
"#;
|
||||
let triangle_ll = r#"
|
||||
!air.vertex = !{!0}
|
||||
!0 = !{ptr @vmain, !1, !3}
|
||||
!1 = !{!2}
|
||||
!2 = !{!"air.position", !"air.arg_type_name", !"float4"}
|
||||
!3 = !{}
|
||||
"#;
|
||||
|
||||
assert!(vertex_writes_point_size(point_ll));
|
||||
assert!(!vertex_writes_point_size(triangle_ll));
|
||||
assert!(!vertex_writes_point_size("!air.vertex = !{}"));
|
||||
}
|
||||
|
||||
/// End-to-end on the real Apple toolchain, but WITHOUT dispatching to the GPU: compile a kernel
|
||||
/// with a data-dependent (effectively unbounded) loop to AIR, disassemble it, run the loop-budget
|
||||
/// instrumentation, and prove `metal-as` + `metallib` accept the instrumented module. This is the
|
||||
|
||||
+208
-46
@@ -37,6 +37,7 @@ use vulkano::memory::allocator::{AllocationCreateInfo, MemoryTypeFilter, Standar
|
||||
use vulkano::pipeline::compute::ComputePipelineCreateInfo;
|
||||
use vulkano::pipeline::graphics::color_blend::{
|
||||
AttachmentBlend, BlendFactor, BlendOp, ColorBlendAttachmentState, ColorBlendState,
|
||||
ColorComponents,
|
||||
};
|
||||
use vulkano::pipeline::graphics::depth_stencil::{CompareOp, DepthState, DepthStencilState};
|
||||
use vulkano::pipeline::graphics::input_assembly::InputAssemblyState;
|
||||
@@ -197,6 +198,16 @@ pub(crate) fn fragment_writes_color_location(spv: &[u8], location: u32) -> bool
|
||||
}
|
||||
|
||||
fn fragment_color_output_locations(spv: &[u8]) -> Vec<u32> {
|
||||
fragment_color_output_component_counts(spv)
|
||||
.into_keys()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fragment_color_output_component_counts(spv: &[u8]) -> HashMap<u32, u32> {
|
||||
const OP_TYPE_INT: u32 = 21;
|
||||
const OP_TYPE_FLOAT: u32 = 22;
|
||||
const OP_TYPE_VECTOR: u32 = 23;
|
||||
const OP_TYPE_STRUCT: u32 = 30;
|
||||
const OP_TYPE_POINTER: u32 = 32;
|
||||
const OP_VARIABLE: u32 = 59;
|
||||
const OP_DECORATE: u32 = 71;
|
||||
@@ -205,10 +216,12 @@ fn fragment_color_output_locations(spv: &[u8]) -> Vec<u32> {
|
||||
const STORAGE_CLASS_OUTPUT: u32 = 3;
|
||||
|
||||
let Ok(words) = bytes_to_words(spv) else {
|
||||
return Vec::new();
|
||||
return HashMap::new();
|
||||
};
|
||||
let mut variable_locations = HashMap::new();
|
||||
let mut member_locations: HashMap<u32, Vec<u32>> = HashMap::new();
|
||||
let mut member_locations = HashMap::new();
|
||||
let mut type_component_counts = HashMap::new();
|
||||
let mut struct_member_types: HashMap<u32, Vec<u32>> = HashMap::new();
|
||||
let mut pointer_pointees = HashMap::new();
|
||||
let mut output_variables = Vec::new();
|
||||
let mut index = 5usize;
|
||||
@@ -217,9 +230,21 @@ fn fragment_color_output_locations(spv: &[u8]) -> Vec<u32> {
|
||||
let word_count = (word >> 16) as usize;
|
||||
let opcode = word & 0xffff;
|
||||
if word_count == 0 || index + word_count > words.len() {
|
||||
return Vec::new();
|
||||
return HashMap::new();
|
||||
}
|
||||
match opcode {
|
||||
OP_TYPE_INT | OP_TYPE_FLOAT if word_count >= 3 => {
|
||||
type_component_counts.insert(words[index + 1], 1);
|
||||
}
|
||||
OP_TYPE_VECTOR if word_count >= 4 => {
|
||||
type_component_counts.insert(words[index + 1], words[index + 3]);
|
||||
}
|
||||
OP_TYPE_STRUCT if word_count >= 2 => {
|
||||
struct_member_types.insert(
|
||||
words[index + 1],
|
||||
words[index + 2..index + word_count].to_vec(),
|
||||
);
|
||||
}
|
||||
OP_TYPE_POINTER if word_count >= 4 => {
|
||||
pointer_pointees.insert(words[index + 1], words[index + 3]);
|
||||
}
|
||||
@@ -230,31 +255,41 @@ fn fragment_color_output_locations(spv: &[u8]) -> Vec<u32> {
|
||||
variable_locations.insert(words[index + 1], words[index + 3]);
|
||||
}
|
||||
OP_MEMBER_DECORATE if word_count >= 5 && words[index + 3] == DECORATION_LOCATION => {
|
||||
member_locations
|
||||
.entry(words[index + 1])
|
||||
.or_default()
|
||||
.push(words[index + 4]);
|
||||
member_locations.insert((words[index + 1], words[index + 2]), words[index + 4]);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
index += word_count;
|
||||
}
|
||||
|
||||
let mut out = output_variables
|
||||
.into_iter()
|
||||
.flat_map(|(variable_id, pointer_type_id)| {
|
||||
let direct = variable_locations.get(&variable_id).copied().into_iter();
|
||||
let members = pointer_pointees
|
||||
.get(&pointer_type_id)
|
||||
.and_then(|pointee_id| member_locations.get(pointee_id))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.copied();
|
||||
direct.chain(members).collect::<Vec<_>>()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
let mut out = HashMap::new();
|
||||
for (variable_id, pointer_type_id) in output_variables {
|
||||
let Some(&pointee_id) = pointer_pointees.get(&pointer_type_id) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(&location) = variable_locations.get(&variable_id) {
|
||||
if let Some(&count) = type_component_counts.get(&pointee_id) {
|
||||
out.entry(location)
|
||||
.and_modify(|seen: &mut u32| *seen = (*seen).max(count))
|
||||
.or_insert(count);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(member_types) = struct_member_types.get(&pointee_id) else {
|
||||
continue;
|
||||
};
|
||||
for (member, type_id) in member_types.iter().copied().enumerate() {
|
||||
let Some(&location) = member_locations.get(&(pointee_id, member as u32)) else {
|
||||
continue;
|
||||
};
|
||||
let Some(&count) = type_component_counts.get(&type_id) else {
|
||||
continue;
|
||||
};
|
||||
out.entry(location)
|
||||
.and_modify(|seen: &mut u32| *seen = (*seen).max(count))
|
||||
.or_insert(count);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -1230,8 +1265,12 @@ pub fn device_and_queue_result(
|
||||
if physical_device.supported_features().sample_rate_shading {
|
||||
enabled_features.sample_rate_shading = true;
|
||||
}
|
||||
if physical_device.supported_features().independent_blend {
|
||||
enabled_features.independent_blend = true;
|
||||
}
|
||||
let enabled_extensions = DeviceExtensions {
|
||||
ext_shader_atomic_float: true,
|
||||
ext_filter_cubic: physical_device.supported_extensions().ext_filter_cubic,
|
||||
ext_shader_stencil_export: physical_device
|
||||
.supported_extensions()
|
||||
.ext_shader_stencil_export,
|
||||
@@ -1280,7 +1319,7 @@ fn compute_pipeline(device: Arc<Device>, spv: &[u8]) -> Result<Arc<ComputePipeli
|
||||
None,
|
||||
ComputePipelineCreateInfo::stage_layout(stage, layout),
|
||||
)
|
||||
.map_err(|error| format!("create compute pipeline: {error}"))
|
||||
.map_err(|error| format!("create compute pipeline: {error} ({error:?})"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -1333,10 +1372,19 @@ fn graphics_pipeline(
|
||||
create_info.color_blend_state = if target.color_attachment_formats.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(ColorBlendState::with_attachment_states(
|
||||
target.color_attachment_formats.len() as u32,
|
||||
color_blend_attachment(blend),
|
||||
))
|
||||
let component_counts = fragment_color_output_component_counts(fragment_spv);
|
||||
let attachments = target
|
||||
.color_attachment_formats
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(location, _)| {
|
||||
color_blend_attachment(blend, component_counts.get(&(location as u32)).copied())
|
||||
})
|
||||
.collect();
|
||||
Some(ColorBlendState {
|
||||
attachments,
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
let color_attachment_formats = target
|
||||
.color_attachment_formats
|
||||
@@ -1923,8 +1971,17 @@ fn vertex_validation_viewport_state() -> Option<ViewportState> {
|
||||
None
|
||||
}
|
||||
|
||||
fn color_blend_attachment(blend: BlendMode) -> ColorBlendAttachmentState {
|
||||
match blend {
|
||||
fn color_blend_attachment(
|
||||
blend: BlendMode,
|
||||
output_component_count: Option<u32>,
|
||||
) -> ColorBlendAttachmentState {
|
||||
let color_write_mask = match output_component_count {
|
||||
Some(1) => ColorComponents::R,
|
||||
Some(2) => ColorComponents::R | ColorComponents::G,
|
||||
Some(3) => ColorComponents::R | ColorComponents::G | ColorComponents::B,
|
||||
_ => ColorComponents::all(),
|
||||
};
|
||||
let mut state = match blend {
|
||||
BlendMode::Replace => ColorBlendAttachmentState::default(),
|
||||
BlendMode::SourceOver => ColorBlendAttachmentState {
|
||||
blend: Some(AttachmentBlend {
|
||||
@@ -1937,7 +1994,9 @@ fn color_blend_attachment(blend: BlendMode) -> ColorBlendAttachmentState {
|
||||
}),
|
||||
..ColorBlendAttachmentState::default()
|
||||
},
|
||||
}
|
||||
};
|
||||
state.color_write_mask = color_write_mask;
|
||||
state
|
||||
}
|
||||
|
||||
fn shader_stage(device: Arc<Device>, spv: &[u8]) -> PipelineShaderStageCreateInfo {
|
||||
@@ -2881,6 +2940,19 @@ fn texture_binding_req_for_index(
|
||||
})
|
||||
}
|
||||
|
||||
fn placeholder_texture_binding_req_for_index(
|
||||
reqs: &HashMap<u32, TextureBindingReq>,
|
||||
index: u32,
|
||||
) -> Option<&TextureBindingReq> {
|
||||
reqs.values()
|
||||
.filter(|req| {
|
||||
index >= req.index && index < req.index.saturating_add(req.descriptor_count.max(1))
|
||||
})
|
||||
// An explicit storage-image format is a hard SPIR-V constraint; a sampled-image scalar
|
||||
// class is only a format-family hint. Prefer the former when descriptor arrays overlap.
|
||||
.min_by_key(|req| (req.image_format.is_none(), !req.needs_storage, req.index))
|
||||
}
|
||||
|
||||
fn texture_binding_mutable_format_flag(
|
||||
reqs: &HashMap<u32, TextureBindingReq>,
|
||||
index: u32,
|
||||
@@ -3270,16 +3342,18 @@ fn append_texture_placeholders(
|
||||
spv: &[u8],
|
||||
textures: &mut Vec<TextureResource>,
|
||||
) {
|
||||
for req in required_texture_bindings(device, spv).into_values() {
|
||||
let view_type = req.image_view_type.unwrap_or(ImageViewType::Dim2d);
|
||||
let (image_type, array_layers, flags) = placeholder_image_shape(view_type);
|
||||
let format = placeholder_format(&req);
|
||||
let extent = [1u32, 1, 1];
|
||||
let usage = ImageUsage::TRANSFER_DST
|
||||
| ImageUsage::TRANSFER_SRC
|
||||
| texture_binding_image_usage(Some(&req));
|
||||
let reqs = required_texture_bindings(device, spv);
|
||||
for req in reqs.values() {
|
||||
for offset in 0..req.descriptor_count {
|
||||
let index = req.index + offset;
|
||||
let image_req = placeholder_texture_binding_req_for_index(&reqs, index).unwrap_or(req);
|
||||
let view_type = image_req.image_view_type.unwrap_or(ImageViewType::Dim2d);
|
||||
let (image_type, array_layers, flags) = placeholder_image_shape(view_type);
|
||||
let format = placeholder_format(image_req);
|
||||
let extent = [1u32, 1, 1];
|
||||
let usage = ImageUsage::TRANSFER_DST
|
||||
| ImageUsage::TRANSFER_SRC
|
||||
| texture_binding_image_usage_for_index(&reqs, index);
|
||||
if textures.iter().any(|texture| texture.index == index) {
|
||||
continue;
|
||||
}
|
||||
@@ -3380,8 +3454,18 @@ fn texture_view_for_req(
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
ImageView::new(texture.image.clone(), view_info)
|
||||
.unwrap_or_else(|e| panic!("create descriptor texture view {}: {e}", texture.index))
|
||||
let descriptor_format = view_info.format;
|
||||
ImageView::new(texture.image.clone(), view_info).unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"create descriptor texture view {} (image_format={:?}, descriptor_format={:?}, \
|
||||
image_flags={:?}, requirement={:?}): {e:?}",
|
||||
texture.index,
|
||||
texture.image.format(),
|
||||
descriptor_format,
|
||||
texture.image.flags(),
|
||||
req
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn descriptor_view_format(parent_format: Format, req: Option<&TextureBindingReq>) -> Format {
|
||||
@@ -3822,9 +3906,21 @@ fn descriptor_set(
|
||||
let static_samplers = static_sampler_binding_states(sanitized_ll)
|
||||
.into_iter()
|
||||
.map(|(binding, state)| {
|
||||
let sampler = Sampler::new(device.clone(), state.create_info()).unwrap_or_else(|e| {
|
||||
let mut create_info = state.create_info();
|
||||
// The product lowers every supported AIR bicubic sample to explicit Catmull-Rom
|
||||
// fetches, but its now-dead static sampler descriptor can remain in the reflected
|
||||
// layout. MoltenVK does not expose EXT_filter_cubic, so use a legal placeholder for
|
||||
// that unobserved descriptor. Unsupported bicubic shapes fail translation above.
|
||||
if create_info.min_filter == Filter::Cubic
|
||||
&& !device.enabled_extensions().ext_filter_cubic
|
||||
&& !device.enabled_extensions().img_filter_cubic
|
||||
{
|
||||
create_info.min_filter = Filter::Nearest;
|
||||
create_info.mag_filter = Filter::Nearest;
|
||||
}
|
||||
let sampler = Sampler::new(device.clone(), create_info).unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"create static sampler for AIR word {:#x} binding {binding}: {e}",
|
||||
"create static sampler for AIR word {:#x} binding {binding}: {e:?}",
|
||||
state.word
|
||||
)
|
||||
});
|
||||
@@ -3978,10 +4074,10 @@ impl StaticSamplerState {
|
||||
decode_air_sampler_address((word >> 3) & 0x7),
|
||||
decode_air_sampler_address((word >> 6) & 0x7),
|
||||
],
|
||||
filter: if word & 0x0a00 == 0x0a00 {
|
||||
Filter::Linear
|
||||
} else {
|
||||
Filter::Nearest
|
||||
filter: match ((word >> 11) & 0x3, (word >> 9) & 0x3) {
|
||||
(2, 2) => Filter::Cubic,
|
||||
(1, 1) => Filter::Linear,
|
||||
_ => Filter::Nearest,
|
||||
},
|
||||
unnormalized_coordinates: word & 0x8000 != 0,
|
||||
}
|
||||
@@ -4197,6 +4293,28 @@ mod tests {
|
||||
words.iter().flat_map(|word| word.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_rgb_output_limits_color_write_mask_to_declared_components() {
|
||||
let mut words = vec![0x0723_0203, 0x0001_0300, 0, 8, 0];
|
||||
words.extend(spirv_inst(22, &[1, 16])); // %1 = OpTypeFloat 16
|
||||
words.extend(spirv_inst(23, &[2, 1, 3])); // %2 = OpTypeVector %1 3
|
||||
words.extend(spirv_inst(32, &[3, 3, 2])); // %3 = Output pointer to %2
|
||||
words.extend(spirv_inst(59, &[3, 4, 3])); // %4 = output variable
|
||||
words.extend(spirv_inst(71, &[4, 30, 0])); // Location 0
|
||||
let spv = spirv_bytes(&words);
|
||||
|
||||
assert_eq!(
|
||||
fragment_color_output_component_counts(&spv).get(&0),
|
||||
Some(&3)
|
||||
);
|
||||
let state = color_blend_attachment(BlendMode::Replace, Some(3));
|
||||
assert_eq!(
|
||||
state.color_write_mask,
|
||||
ColorComponents::R | ColorComponents::G | ColorComponents::B
|
||||
);
|
||||
assert!(!state.color_write_mask.intersects(ColorComponents::A));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_render_target_attachment_formats_include_all_mrt_locations() {
|
||||
let ll = r#"
|
||||
@@ -4515,6 +4633,38 @@ mod tests {
|
||||
assert!(!texture_binding_image_usage_for_index(&reqs, 5).intersects(ImageUsage::SAMPLED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_texture_array_requirements_combine_image_usage() {
|
||||
let sampled = TextureBindingReq {
|
||||
index: 0,
|
||||
descriptor_count: 128,
|
||||
needs_sampled: true,
|
||||
needs_storage: false,
|
||||
image_format: None,
|
||||
image_scalar_type: Some(NumericType::Float),
|
||||
image_view_type: Some(ImageViewType::Dim2d),
|
||||
};
|
||||
let storage = TextureBindingReq {
|
||||
index: 8,
|
||||
descriptor_count: 128,
|
||||
needs_sampled: false,
|
||||
needs_storage: true,
|
||||
image_format: Some(Format::R32_SFLOAT),
|
||||
image_scalar_type: Some(NumericType::Float),
|
||||
image_view_type: Some(ImageViewType::Dim2d),
|
||||
};
|
||||
let reqs = HashMap::from([(0, sampled), (8, storage)]);
|
||||
|
||||
let usage = texture_binding_image_usage_for_index(&reqs, 16);
|
||||
|
||||
assert!(usage.intersects(ImageUsage::SAMPLED));
|
||||
assert!(usage.intersects(ImageUsage::STORAGE));
|
||||
assert_eq!(
|
||||
placeholder_texture_binding_req_for_index(&reqs, 16).map(|req| req.index),
|
||||
Some(8)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflected_sampled_image_array_requirement_overrides_later_texture_format() {
|
||||
let req = TextureBindingReq {
|
||||
@@ -4631,6 +4781,18 @@ mod tests {
|
||||
assert!(!states[0].unnormalized_coordinates);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_sampler_state_decodes_bicubic_filter_bits() {
|
||||
let states = static_sampler_states(
|
||||
r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 562249, i64 0], align 8"#,
|
||||
);
|
||||
|
||||
assert_eq!(states.len(), 1);
|
||||
assert_eq!(states[0].address_mode, [SamplerAddressMode::ClampToEdge; 3]);
|
||||
assert_eq!(states[0].filter, Filter::Cubic);
|
||||
assert!(states[0].unnormalized_coordinates);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_sampler_binding_skips_runtime_sampler_slots() {
|
||||
let states = static_sampler_binding_states(
|
||||
|
||||
Reference in new issue
Block a user