Pin both reported bugs with regression tests that fail without their fixes

The two bundles under bugs/ are fixed at HEAD, but neither loss was pinned by a
test that fails when the fix is reverted, and bugs/ is gitignored, so the
reproducers cannot serve as the guard. Both defects also passed spirv-val, so
validation cannot be the guard either. Author the guards from the property each
bundle actually lost.

fragment-code-size-explosion: the module reached the driver as one OpFunction in
state-machine form -- 2286 of 2296 blocks were sibling OpSwitch cases inside a
single loop, with 3516 function-scope variables because sibling cases cannot
dominate each other -- and vkCreateGraphicsPipelines never returned. Build a
reducible-but-unstructured function (one loop over a chain of undeclared-merge
diamonds), run it through the real construction path, and assert the emitted
shape: a surviving loop construct, dispatch over a minority of blocks, and no
variable-per-crossing-value demotion. Held at 16 and at 64 diamonds.

compute-multisample-query-reports-one: air.get_num_samples_texture_2d_ms lowered
to the literal 1, so a four-sample kernel visited only sample zero. Extend the
family to texture2d_ms_array, and add the data-flow guard the opcode-presence
assertions cannot make: the queried count must be what bounds the per-sample
loop.

Verified: with reloop_nest::structure_selected_functions stubbed out, the two
shape tests fail reporting 51 cases over 58 blocks and 195 over 202 -- the
reported 99%-coverage state machine. With the sample-count lowering forced to
the constant, all three multisample tests fail; with the query emitted but its
result replaced by the constant at the use, only the new data-flow test fails,
which is the case it exists for. cargo test -p metal2vulkan: 1688 passed.
Workspace clippy with -D warnings: clean.
This commit is contained in:
Anees Iqbal committed 2026-08-31 13:57:18 +03:00
1 parent 47009b2693
commit 38d1ae3750
2 files changed
+406

No files matched your search

+267
View File
@@ -1946,4 +1946,271 @@ mod tests {
.expect("unowned backedge construction");
assert_ne!(module.functions[0].blocks.len(), 4);
}
/// Build a reducible-but-unstructured function: one loop whose body is a chain of `diamonds`
/// conditional diamonds, none of them carrying a declared merge. Selection picks it up through
/// the unowned selection headers and the unowned back-edge.
fn loop_of_unstructured_diamonds(diamonds: u32) -> Module {
let (void, uint, bool_ty, fn_ty) = (1, 2, 3, 4);
let (uint_0, uint_1, uint_64) = (5, 6, 7);
let (entry, header, latch, exit) = (100, 101, 102, 103);
let (i, cmp, next) = (300, 301, 302);
let body = |k: u32| 1000 + k * 10;
let then = |k: u32| 1001 + k * 10;
let join = |k: u32| 1002 + k * 10;
let cond = |k: u32| 5000 + k * 10;
let bumped = |k: u32| 5001 + k * 10;
let merged = |k: u32| 5002 + k * 10;
let mut module = Module::new();
module.header = Some(ModuleHeader::new(20000));
set_logical_memory_model(&mut module);
module.types_global_values = vec![
inst(Op::TypeVoid, None, Some(void), vec![]),
inst(
Op::TypeInt,
None,
Some(uint),
vec![Operand::LiteralBit32(32), Operand::LiteralBit32(0)],
),
inst(Op::TypeBool, None, Some(bool_ty), vec![]),
inst(
Op::TypeFunction,
None,
Some(fn_ty),
vec![Operand::IdRef(void)],
),
inst(
Op::Constant,
Some(uint),
Some(uint_0),
vec![Operand::LiteralBit32(0)],
),
inst(
Op::Constant,
Some(uint),
Some(uint_1),
vec![Operand::LiteralBit32(1)],
),
inst(
Op::Constant,
Some(uint),
Some(uint_64),
vec![Operand::LiteralBit32(64)],
),
];
let mut function = Function::new();
function.def = Some(inst(
Op::Function,
Some(void),
Some(20),
vec![
Operand::FunctionControl(spirv::FunctionControl::NONE),
Operand::IdRef(fn_ty),
],
));
function.blocks.push(Block {
label: Some(inst(Op::Label, None, Some(entry), vec![])),
instructions: vec![inst(Op::Branch, None, None, vec![Operand::IdRef(header)])],
});
// The loop header carries no OpLoopMerge, so the back-edge from the latch is unowned.
function.blocks.push(Block {
label: Some(inst(Op::Label, None, Some(header), vec![])),
instructions: vec![
inst(
Op::Phi,
Some(uint),
Some(i),
vec![
Operand::IdRef(uint_0),
Operand::IdRef(entry),
Operand::IdRef(next),
Operand::IdRef(latch),
],
),
inst(
Op::ULessThan,
Some(bool_ty),
Some(cmp),
vec![Operand::IdRef(i), Operand::IdRef(uint_64)],
),
inst(
Op::BranchConditional,
None,
None,
vec![
Operand::IdRef(cmp),
Operand::IdRef(body(0)),
Operand::IdRef(exit),
],
),
],
});
for k in 0..diamonds {
let after = if k + 1 == diamonds {
latch
} else {
body(k + 1)
};
// No OpSelectionMerge: this is the unowned selection header that selects construction.
function.blocks.push(Block {
label: Some(inst(Op::Label, None, Some(body(k)), vec![])),
instructions: vec![
inst(
Op::IEqual,
Some(bool_ty),
Some(cond(k)),
vec![Operand::IdRef(i), Operand::IdRef(uint_1)],
),
inst(
Op::BranchConditional,
None,
None,
vec![
Operand::IdRef(cond(k)),
Operand::IdRef(then(k)),
Operand::IdRef(join(k)),
],
),
],
});
function.blocks.push(Block {
label: Some(inst(Op::Label, None, Some(then(k)), vec![])),
instructions: vec![
inst(
Op::IAdd,
Some(uint),
Some(bumped(k)),
vec![Operand::IdRef(i), Operand::IdRef(uint_1)],
),
inst(Op::Branch, None, None, vec![Operand::IdRef(join(k))]),
],
});
function.blocks.push(Block {
label: Some(inst(Op::Label, None, Some(join(k)), vec![])),
instructions: vec![
inst(
Op::Phi,
Some(uint),
Some(merged(k)),
vec![
Operand::IdRef(bumped(k)),
Operand::IdRef(then(k)),
Operand::IdRef(i),
Operand::IdRef(body(k)),
],
),
inst(Op::Branch, None, None, vec![Operand::IdRef(after)]),
],
});
}
function.blocks.push(Block {
label: Some(inst(Op::Label, None, Some(latch), vec![])),
instructions: vec![
inst(
Op::IAdd,
Some(uint),
Some(next),
vec![Operand::IdRef(i), Operand::IdRef(uint_1)],
),
inst(Op::Branch, None, None, vec![Operand::IdRef(header)]),
],
});
function.blocks.push(Block {
label: Some(inst(Op::Label, None, Some(exit), vec![])),
instructions: vec![inst(Op::Return, None, None, vec![])],
});
module.functions.push(function);
module
}
/// The emitted control-flow shape of a function, as the driver's shader compiler sees it.
fn emitted_shape(function: &Function) -> (usize, usize, usize, usize) {
let body = || function.blocks.iter().flat_map(|block| &block.instructions);
let blocks = function.blocks.len();
let loop_merges = body()
.filter(|instruction| instruction.class.opcode == Op::LoopMerge)
.count();
// An OpSwitch is `selector, default, (literal, label)...`.
let switch_cases = body()
.filter(|instruction| instruction.class.opcode == Op::Switch)
.map(|instruction| instruction.operands.len().saturating_sub(2) / 2)
.sum();
let function_variables = body()
.filter(|instruction| {
instruction.class.opcode == Op::Variable
&& matches!(
instruction.operands.first(),
Some(Operand::StorageClass(StorageClass::Function))
)
})
.count();
(blocks, loop_merges, switch_cases, function_variables)
}
/// Regression: `bugs/fragment-code-size-explosion`.
///
/// A fragment module reached a host GPU driver as one `OpFunction` in state-machine form —
/// 2296 blocks, 2286 of them sibling `OpSwitch` cases inside a single loop, zero `OpPhi`, and
/// 3516 function-scope variables because sibling cases cannot dominate each other. The driver's
/// shader compiler promotes each of those back to SSA inside one loop spanning the whole
/// program, the interference graph goes near-complete, and `vkCreateGraphicsPipelines` never
/// returns — taking the VM process with it.
///
/// The module was valid SPIR-V and translated in about two seconds, so neither `spirv-val` nor
/// a time budget catches this. The only thing that does is the emitted shape, which is what
/// this pins: reducible control flow must arrive nested, with real loop constructs, dispatch
/// over a small minority of blocks, and no variable-per-crossing-value demotion.
#[test]
fn reducible_control_flow_is_not_constructed_as_a_whole_function_dispatch() {
const DIAMONDS: u32 = 16;
let mut module = loop_of_unstructured_diamonds(DIAMONDS);
let before = module.functions[0].blocks.len();
construct_cfg_functions_module(&mut module, &HashSet::new()).expect("construction");
let (blocks, loop_merges, switch_cases, function_variables) =
emitted_shape(&module.functions[0]);
assert!(
loop_merges >= 1,
"the loop must survive as a real loop construct, not as a dispatch over its body; \
got {loop_merges} OpLoopMerge across {blocks} blocks"
);
assert!(
switch_cases * 2 < blocks,
"dispatch must cover a minority of blocks; {switch_cases} switch cases over {blocks} \
blocks is the whole-function state machine that hangs the driver"
);
// Flattening demotes every value that crosses a block boundary. This function has one
// crossing value per diamond plus the loop's own induction values, and nesting keeps them
// in registers.
assert!(
function_variables < DIAMONDS as usize,
"nesting must keep crossing values in registers; {function_variables} function-scope \
variables for {DIAMONDS} diamonds is the register-demotion the driver chokes on"
);
assert!(
before > 0 && blocks > 0,
"the function must still have a body"
);
}
/// The same shape contract, held as the function grows. Flattening is what makes the driver's
/// cost superlinear, so the guard has to hold at a size where that would actually bite.
#[test]
fn a_larger_reducible_function_still_nests_instead_of_flattening() {
let mut module = loop_of_unstructured_diamonds(64);
construct_cfg_functions_module(&mut module, &HashSet::new()).expect("construction");
let (blocks, loop_merges, switch_cases, function_variables) =
emitted_shape(&module.functions[0]);
assert!(loop_merges >= 1, "{blocks} blocks, no loop construct");
assert!(
switch_cases * 2 < blocks,
"{switch_cases} switch cases over {blocks} blocks is a dispatch state machine"
);
assert!(
function_variables < 64,
"{function_variables} function-scope variables is register demotion at scale"
);
}
}
+139
View File
@@ -3920,6 +3920,145 @@ declare i32 @air.get_num_samples_texture_2d(ptr addrspace(1))
}
}
#[test]
fn native_kernel_multisample_array_sample_count_query_uses_image_query_samples() {
// A multisample *array* texture is still a 2D multisampled image, so its sample count is still
// a property of the bound image. Covering only `texture2d_ms` would leave the array member of
// the same family free to regress back to a literal.
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @k(ptr addrspace(1) %tex, ptr addrspace(1) %out) {
entry:
%n = tail call i32 @air.get_num_samples_texture_2d_ms_array(ptr addrspace(1) %tex)
store i32 %n, ptr addrspace(1) %out, align 4
ret void
}
declare i32 @air.get_num_samples_texture_2d_ms_array(ptr addrspace(1))
!air.kernel = !{!0}
!0 = !{ptr @k, !1, !2}
!1 = !{}
!2 = !{!3, !4}
!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d_ms_array<float, read>", !"air.arg_name", !"tex"}
!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.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_kernel_ms_array_sample_count_{}",
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!(asm.contains("OpImageQuerySamples"), "{asm}");
assert!(asm.contains("OpCapability ImageQuery"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&spv, &tmp).expect("spirv-val");
}
}
/// Regression: `bugs/compute-multisample-query-reports-one`.
///
/// The guest-visible loss was never the query instruction on its own — it was that the sample count
/// is what bounds the per-sample loop. Substituting the literal 1 made a four-sample kernel visit
/// only sample zero and leave samples one through three at their sentinel values, and the module
/// still passed `spirv-val`, because a constant loop bound is perfectly valid SPIR-V.
///
/// So pin the data flow, not just the opcode: the queried sample count has to be what the loop
/// compares against. A regression that reintroduced the constant would keep `OpImageQuerySamples`
/// live in a dead corner of the module and still collapse the loop.
#[test]
fn native_kernel_multisample_sample_count_query_bounds_the_per_sample_loop() {
let ll = r#"
target triple = "spirv-unknown-vulkan1.2"
define void @k(ptr addrspace(1) %tex, ptr addrspace(1) %out) {
entry:
%n = tail call i32 @air.get_num_samples_texture_2d_ms(ptr addrspace(1) %tex)
br label %loop
loop:
%s = phi i32 [ 0, %entry ], [ %s.next, %body ]
%acc = phi i32 [ 0, %entry ], [ %acc.next, %body ]
%more = icmp slt i32 %s, %n
br i1 %more, label %body, label %done
body:
%acc.next = add i32 %acc, %s
%s.next = add i32 %s, 1
br label %loop
done:
store i32 %acc, ptr addrspace(1) %out, align 4
ret void
}
declare i32 @air.get_num_samples_texture_2d_ms(ptr addrspace(1))
!air.kernel = !{!0}
!0 = !{ptr @k, !1, !2}
!1 = !{}
!2 = !{!3, !4}
!3 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d_ms<float, read>", !"air.arg_name", !"tex"}
!4 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.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_kernel_ms_sample_loop_{}",
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!(asm.contains("OpImageQuerySamples"), "{asm}");
// The query's result id, and every id derived from it by a pure move/convert. The bound may be
// bitcast or copied on its way to the comparison; what must not happen is a constant taking its
// place.
let mut derived = Vec::new();
for line in asm.lines() {
let Some((result, rhs)) = line.split_once(" = ") else {
continue;
};
let result = result.trim();
if rhs.contains("OpImageQuerySamples") {
derived.push(result.to_string());
continue;
}
let forwards = ["OpCopyObject", "OpBitcast", "OpUConvert", "OpSConvert"]
.iter()
.any(|op| rhs.starts_with(op));
if forwards && derived.iter().any(|id| rhs.contains(id.as_str())) {
derived.push(result.to_string());
}
}
assert!(!derived.is_empty(), "no OpImageQuerySamples result: {asm}");
let bounds_the_loop = asm.lines().any(|line| {
["OpSLessThan", "OpULessThan", "OpINotEqual", "OpIEqual"]
.iter()
.any(|op| line.contains(op))
&& derived.iter().any(|id| line.contains(id.as_str()))
});
assert!(
bounds_the_loop,
"the queried sample count must bound the per-sample loop; a constant bound here is the \
defect that made a four-sample kernel visit only sample zero: {asm}"
);
assert!(asm.contains("OpLoopMerge"), "{asm}");
if std::process::Command::new("spirv-val")
.arg("--version")
.output()
.is_ok()
{
tools::spirv_val_bytes(&spv, &tmp).expect("spirv-val");
}
}
#[test]
fn native_kernel_helper_wrapped_texture_query_resolves_loaded_image() {
let ll = r#"