diff --git a/crates/metal2vulkan/src/pipeline/link/tests.rs b/crates/metal2vulkan/src/pipeline/link/tests.rs index 134743bc4..49d570119 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests.rs @@ -791,58 +791,94 @@ fn a_mesh_pipelines_fragment_reads_its_primitive_outputs_per_primitive() { /// A fragment input read at another component count than its producer writes is Metal's link /// error behind a producer whose module does not state `agx.allow_mismatched_component_counts` -/// as 1, and this translator's gap behind one that does (`StageIo::mismatched_component_counts`, -/// a vertex or mesh function's): Metal makes that pipeline. The flag on the fragment function -/// alone, another numeric class, or a key the producer does not write stays Metal's link error. +/// as 1 (`StageIo::mismatched_component_counts`, a vertex or mesh function's). Behind a vertex +/// function that does, Metal makes the pipeline: a narrower input reads the output's first lanes, +/// so it takes the output's location and component, which Vulkan matches under `maintenance4` +/// (one form, the floor's; a description without it is the gap), and a wider one, whose lanes +/// past the output's Metal leaves undefined, is this translator's gap, as is any mismatch behind a +/// mesh function, whose flag is not measured. The flag on the fragment function alone, another +/// numeric class, or a key the producer does not write stays Metal's link error. #[test] -fn a_component_count_mismatch_behind_the_agx_flag_is_our_gap() { +fn behind_the_agx_flag_a_narrower_input_takes_its_output_s_location() { + use crate::device::requirements::VkFeature; let p = profile("lavapipe"); let [f2, f4] = [2, 4].map(|n| io_ty(IoNumeric::Float, n)); - let u2 = io_ty(IoNumeric::Uint, 2); + let [u1, u2, u3] = [1, 2, 3].map(|n| io_ty(IoNumeric::Uint, n)); + let flat = Some(Interpolation::Flat); let link_error: Error = Unsupported::not_representable(Feature::UnmatchedVarying).into(); let gap: Error = Unsupported::not_implemented(Feature::UnmatchedVarying).into(); - let producer = |stage: Stage, ty: IoType, flagged: bool| { - let mut io = stage_io(vec![], vec![varying("v", ty, None)]); + let producer = |stage: Stage, outputs: Vec, flagged: bool| { + let mut io = stage_io(vec![], outputs); io.mismatched_component_counts = flagged; with_io(stage, io) }; - let fragment = |input: IoVariable, flagged: bool| { - let mut io = stage_io(vec![input], vec![color(0, 0, f4)]); + let fragment = |inputs: Vec, flagged: bool| { + let mut io = stage_io(inputs, vec![color(0, 0, f4)]); io.mismatched_component_counts = flagged; with_io(Stage::Fragment, io) }; - // A wider and a narrower vertex output than the fragment input. + // Narrower: each input at its output's location, component 0, beside matched varyings. + let outputs = vec![ + varying("a", f4, None), + varying("v", f4, None), + varying("n", u3, None), + ]; + let vs = producer(Stage::Vertex, outputs.clone(), true); + for (v, n) in [(f2, u1), (io_ty(IoNumeric::Float, 1), u2)] { + for interpolation in [SMOOTH, flat] { + let fs = fragment( + vec![ + varying("n", n, flat), + varying("v", v, interpolation), + varying("a", f4, SMOOTH), + ], + false, + ); + let l = link(&[&vs, &fs], &render(), &p).expect("a narrower input links"); + for (k, at) in [("a", (0, 0)), ("v", (1, 0)), ("n", (2, 0))] { + assert_eq!(l.table.locations[&key(k)], at, "{k}"); + } + } + } + // Without `maintenance4` in the description, the narrower input is the gap. + let fs = fragment(vec![varying("v", f2, SMOOTH)], false); + let p_without = + crate::pipeline::testing::profile_without("lavapipe", &[VkFeature::Maintenance4]) + .expect("profile"); + assert_eq!( + link(&[&vs, &fs], &render(), &p_without).err(), + Some(gap.clone()) + ); + // Wider: the gap behind the flag; Metal's link error without it. + let narrow_vs = |flagged| producer(Stage::Vertex, vec![varying("v", f2, None)], flagged); + let wide_fs = fragment(vec![varying("v", f4, SMOOTH)], false); + assert_eq!( + link(&[&narrow_vs(true), &wide_fs], &render(), &p).err(), + Some(gap.clone()) + ); for (written, read) in [(f4, f2), (f2, f4)] { - let fs = fragment(varying("v", read, SMOOTH), false); - let flagged = producer(Stage::Vertex, written, true); - assert_eq!( - link(&[&flagged, &fs], &render(), &p).err(), - Some(gap.clone()) - ); - let plain = producer(Stage::Vertex, written, false); + let fs = fragment(vec![varying("v", read, SMOOTH)], false); + let plain = producer(Stage::Vertex, vec![varying("v", written, None)], false); assert_eq!( link(&[&plain, &fs], &render(), &p).err(), Some(link_error.clone()) ); - let fs_flagged = fragment(varying("v", read, SMOOTH), true); + let fs_flagged = fragment(vec![varying("v", read, SMOOTH)], true); assert_eq!( link(&[&plain, &fs_flagged], &render(), &p).err(), Some(link_error.clone()) ); - let mesh = producer(Stage::Mesh, written, true); + // A mesh function's flag is not measured: either way the gap. + let mesh = producer(Stage::Mesh, vec![varying("v", written, None)], true); assert_eq!( link(&[&mesh, &fs], &LinkInputs::Mesh(Box::default()), &p).err(), Some(gap.clone()) ); } // Behind the flag: another numeric class, or a key the vertex function does not write. - let flagged = producer(Stage::Vertex, f4, true); - for input in [ - varying("v", u2, Some(Interpolation::Flat)), - varying("w", f2, SMOOTH), - ] { + for input in [varying("v", u2, flat), varying("w", f2, SMOOTH)] { assert_eq!( - link(&[&flagged, &fragment(input, false)], &render(), &p).err(), + link(&[&vs, &fragment(vec![input], false)], &render(), &p).err(), Some(link_error.clone()) ); } diff --git a/crates/metal2vulkan/src/tests/engine_converter_module_flags.rs b/crates/metal2vulkan/src/tests/engine_converter_module_flags.rs index cb643f8d1..0a035abb7 100644 --- a/crates/metal2vulkan/src/tests/engine_converter_module_flags.rs +++ b/crates/metal2vulkan/src/tests/engine_converter_module_flags.rs @@ -6,18 +6,22 @@ //! Apple's Metal shader converter wrote. This test compiles, links and validates it on //! `nvidia-rtx50-linux` alone; its row in `tests/public_fixture_expectations_engine.tsv` holds it to //! `ok` on every committed profile (`public_fixtures_engine`). The render pipelines are written -//! here as text: a vertex function writing `user(locn0)` at some component count, with or without -//! the agx flag, and a fragment function reading it at some count. `llvm-as` assembles each; a -//! missing tool skips visibly. +//! here as text: a vertex function writing `user(locn1)` and then `user(locn0)` at some component +//! count of a class, with or without the agx flag, and a fragment function reading `user(locn0)` +//! at some count under an interpolation. `llvm-as` assembles each; a missing tool skips visibly. use crate::error::{Error, Feature, Unsupported}; +use crate::library::FunctionArtifact; use crate::metal::PixelFormat; use crate::pipeline::descriptor::ColorAttachmentDescriptor; use crate::pipeline::link::{link, LinkInputs, RenderLinkInputs}; +use crate::pipeline::relocate::relocate; +use crate::pipeline::sym::{Symbol, VaryingKey}; use crate::pipeline::testing::{ compile, compile_with, fixtures_dir, fragment_inputs, link_and_validate, llvm_assemble, llvm_assemble_text, profile, AssembleError, }; +use crate::spirv::testing::check_words_valid; /// The function compiles, links and validates under the converter's module flags. #[test] @@ -36,33 +40,86 @@ fn a_module_with_the_converter_s_flags_compiles() { link_and_validate(&a, &p).unwrap_or_else(|e| panic!("L3: {e}")); } -/// ``'s LLVM type, or `float` for one lane. -fn float_ty(n: u32) -> String { - match n { - 1 => "float".into(), - _ => format!("<{n} x float>"), - } +/// A varying's class: its AIR scalar, MSL scalar, and how the fragment function makes its first +/// lane a `float`. +#[derive(Clone, Copy, Debug)] +enum Class { + Float, + Uint, + Int, } -/// MSL's name of `n` floats. -fn float_name(n: u32) -> String { - match n { - 1 => "float".into(), - _ => format!("float{n}"), - } -} - -/// A vertex function `vs` writing `float` `(1, 2, ...)` to `user(locn0)` beside its position, -/// its module stating `agx.allow_mismatched_component_counts` as `flag` (nothing for `None`). -fn vertex_text(n: u32, flag: Option) -> String { - let ty = float_ty(n); - let value = match n { - 1 => "1.0".to_owned(), - _ => { - let lanes: Vec = (1..=n).map(|i| format!("float {i}.0")).collect(); - format!("<{}>", lanes.join(", ")) +impl Class { + fn llvm(self) -> &'static str { + match self { + Class::Float => "float", + Class::Uint | Class::Int => "i32", } - }; + } + + fn msl(self) -> &'static str { + match self { + Class::Float => "float", + Class::Uint => "uint", + Class::Int => "int", + } + } + + /// Lane `i`'s value, an LLVM literal. + fn value(self, i: u32) -> String { + match self { + Class::Float => format!("{}.0", 10 * (i + 1)), + Class::Uint => format!("{}", 11 * (i + 1)), + Class::Int => format!("-{}", 11 * (i + 1)), + } + } + + /// `n` lanes from lane `from` on, an LLVM constant of `n` lanes of the class. + fn constant(self, from: u32, n: u32) -> String { + match n { + 1 => self.value(from), + _ => { + let lanes: Vec = (from..from + n) + .map(|i| format!("{} {}", self.llvm(), self.value(i))) + .collect(); + format!("<{}>", lanes.join(", ")) + } + } + } + + /// The instruction making `%x`, the first lane `%l` as a `float`. + fn to_float(self) -> &'static str { + match self { + Class::Float => " %x = fadd float %l, 0.0\n", + Class::Uint => " %x = uitofp i32 %l to float\n", + Class::Int => " %x = sitofp i32 %l to float\n", + } + } +} + +/// `n` lanes of `c`'s LLVM type. +fn llvm_ty(c: Class, n: u32) -> String { + match n { + 1 => c.llvm().to_owned(), + _ => format!("<{n} x {}>", c.llvm()), + } +} + +/// MSL's name of `n` lanes of `c`. +fn msl_ty(c: Class, n: u32) -> String { + match n { + 1 => c.msl().to_owned(), + _ => format!("{}{n}", c.msl()), + } +} + +/// A vertex function `vs` writing its position, `user(locn1)` (four lanes of `c`) and then +/// `user(locn0)` (`n` lanes of `c`), its module stating `agx.allow_mismatched_component_counts` +/// as `flag` (nothing for `None`). +fn vertex_text(c: Class, n: u32, flag: Option) -> String { + let (ty, wide) = (llvm_ty(c, n), llvm_ty(c, 4)); + let (value, other) = (c.constant(0, n), c.constant(4, 4)); + let out = format!("<{{ <4 x float>, {wide}, {ty} }}>"); let flags = match flag { Some(v) => format!( "!llvm.module.flags = !{{!9}}\n\ @@ -72,34 +129,44 @@ fn vertex_text(n: u32, flag: Option) -> String { }; format!( "target triple = \"air64-apple-macosx14.0.0\"\n\ - define <{{ <4 x float>, {ty} }}> @vs() {{\n\ - \x20 %p = insertvalue <{{ <4 x float>, {ty} }}> undef, <4 x float> , 0\n\ - \x20 %o = insertvalue <{{ <4 x float>, {ty} }}> %p, {ty} {value}, 1\n\ - \x20 ret <{{ <4 x float>, {ty} }}> %o\n\ + define {out} @vs() {{\n\ + \x20 %p = insertvalue {out} undef, <4 x float> , 0\n\ + \x20 %w = insertvalue {out} %p, {wide} {other}, 1\n\ + \x20 %o = insertvalue {out} %w, {ty} {value}, 2\n\ + \x20 ret {out} %o\n\ }}\n\ {flags}\ !air.vertex = !{{!0}}\n\ - !0 = !{{ptr @vs, !1, !4}}\n\ - !1 = !{{!2, !3}}\n\ + !0 = !{{ptr @vs, !1, !5}}\n\ + !1 = !{{!2, !3, !4}}\n\ !2 = !{{!\"air.position\", !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"position\"}}\n\ - !3 = !{{!\"air.vertex_output\", !\"user(locn0)\", !\"air.arg_type_name\", !\"{name}\", !\"air.arg_name\", !\"v\"}}\n\ - !4 = !{{}}\n", - name = float_name(n), + !3 = !{{!\"air.vertex_output\", !\"user(locn1)\", !\"air.arg_type_name\", !\"{wide_name}\", !\"air.arg_name\", !\"w\"}}\n\ + !4 = !{{!\"air.vertex_output\", !\"user(locn0)\", !\"air.arg_type_name\", !\"{name}\", !\"air.arg_name\", !\"v\"}}\n\ + !5 = !{{}}\n", + wide_name = msl_ty(c, 4), + name = msl_ty(c, n), ) } -/// A fragment function `fs` reading `float` from `user(locn0)` (perspective, center) and -/// writing its first lane to color 0's red. -fn fragment_text(n: u32) -> String { - let ty = float_ty(n); - let first = match n { - 1 => " %x = fadd float %v, 0.0\n".to_owned(), - _ => format!(" %x = extractelement {ty} %v, i32 0\n"), +/// An interpolation's AIR qualifiers. +const PERSPECTIVE: &str = "!\"air.center\", !\"air.perspective\""; +const NO_PERSPECTIVE: &str = "!\"air.center\", !\"air.no_perspective\""; +const FLAT: &str = "!\"air.flat\""; + +/// A fragment function `fs` reading `n` lanes of `c` from `user(locn0)` under `interpolation` +/// and writing its first lane, as a `float`, to color 0's red. +fn fragment_text(c: Class, n: u32, interpolation: &str) -> String { + let ty = llvm_ty(c, n); + let first = match (n, c) { + (1, Class::Float) => " %l = fadd float %v, 0.0\n".to_owned(), + (1, _) => " %l = add i32 %v, 0\n".to_owned(), + _ => format!(" %l = extractelement {ty} %v, i32 0\n"), }; format!( "target triple = \"air64-apple-macosx14.0.0\"\n\ define <4 x float> @fs({ty} %v) {{\n\ {first}\ + {to_float}\ \x20 %c = insertelement <4 x float> , float %x, i32 0\n\ \x20 ret <4 x float> %c\n\ }}\n\ @@ -108,8 +175,9 @@ fn fragment_text(n: u32) -> String { !1 = !{{!2}}\n\ !2 = !{{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"color\"}}\n\ !3 = !{{!4}}\n\ - !4 = !{{i32 0, !\"air.fragment_input\", !\"user(locn0)\", !\"air.center\", !\"air.perspective\", !\"air.arg_type_name\", !\"{name}\", !\"air.arg_name\", !\"v\"}}\n", - name = float_name(n), + !4 = !{{i32 0, !\"air.fragment_input\", !\"user(locn0)\", {interpolation}, !\"air.arg_type_name\", !\"{name}\", !\"air.arg_name\", !\"v\"}}\n", + to_float = c.to_float(), + name = msl_ty(c, n), ) } @@ -124,29 +192,46 @@ fn assemble(text: &str) -> Option> { } } -/// A vertex function whose module states the agx flag as 1 carries it to its stage interface -/// (`StageIo::mismatched_component_counts`); one stating 0 or nothing, and a fragment function, -/// do not. Behind the flagged one, a render pipeline whose fragment function reads the varying at -/// another component count, wider or narrower, is this translator's gap -/// (`Unsupported{UnmatchedVarying, NotImplemented}`): Metal makes it. Behind the others it is -/// Metal's link error (`NotRepresentable`), and at the same count it links. -#[test] -fn the_agx_flag_makes_a_component_count_mismatch_our_gap() { - let p = profile("lavapipe").expect("profile"); +/// The render pipeline the tests link: one `RGBA8Unorm` attachment, and the lowering inputs its +/// fragment function compiles under. +fn pipeline( + p: &crate::device::DeviceProfile, +) -> (LinkInputs, crate::pipeline::lower_inputs::LoweringInputs) { let mut r = RenderLinkInputs::new(); r.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let fs_inputs = fragment_inputs(&r, &p); - let render = LinkInputs::Render(Box::new(r)); + let inputs = fragment_inputs(&r, p); + (LinkInputs::Render(Box::new(r)), inputs) +} + +/// The relocated `Location` literal of `key` in `a`'s words. +fn location(a: &FunctionArtifact, words: &[u32], key: &VaryingKey) -> u32 { + let at = (a.module.relocs.iter()) + .find(|(s, _)| *s == Symbol::Location(key.clone())) + .map(|(_, at)| *at) + .unwrap_or_else(|| panic!("no Location reloc for {key:?}")); + words[at as usize] +} + +/// A vertex function whose module states the agx flag as 1 carries it to its stage interface +/// (`StageIo::mismatched_component_counts`); one stating 0 or nothing, and a fragment function, +/// do not. Without it, a fragment function reading the varying at another component count, wider +/// or narrower, is Metal's link error (`NotRepresentable`); behind it a wider one is this +/// translator's gap (`Unsupported{UnmatchedVarying, NotImplemented}`), whose lanes past the +/// output's Metal leaves undefined. At the same count it links, flag or not. +#[test] +fn the_agx_flag_reaches_link_and_a_wider_input_is_our_gap() { + let p = profile("lavapipe").expect("profile"); + let (render, fs_inputs) = pipeline(&p); let gap: Error = Unsupported::not_implemented(Feature::UnmatchedVarying).into(); let link_error: Error = Unsupported::not_representable(Feature::UnmatchedVarying).into(); for (written, read) in [(4, 2), (2, 4)] { - let Some(fs) = assemble(&fragment_text(read)) else { + let Some(fs) = assemble(&fragment_text(Class::Float, read, PERSPECTIVE)) else { return; }; let fs = compile_with(&fs, "fs", &p, &fs_inputs).unwrap_or_else(|e| panic!("fs: {e}")); assert!(!fs.interface.io.mismatched_component_counts); for flag in [Some(1), Some(0), None] { - let Some(vs) = assemble(&vertex_text(written, flag)) else { + let Some(vs) = assemble(&vertex_text(Class::Float, written, flag)) else { return; }; let vs = compile(&vs, "vs", &p).unwrap_or_else(|e| panic!("vs {flag:?}: {e}")); @@ -155,14 +240,16 @@ fn the_agx_flag_makes_a_component_count_mismatch_our_gap() { vs.interface.io.mismatched_component_counts, flagged, "{flag:?}" ); - let expected = if flagged { &gap } else { &link_error }; - assert_eq!( - link(&[&vs, &fs], &render, &p).err().as_ref(), - Some(expected), - "float{written} written, float{read} read, flag {flag:?}" - ); - // The same count links, flag or not. - let Some(same) = assemble(&vertex_text(read, flag)) else { + let r = link(&[&vs, &fs], &render, &p); + let case = format!("float{written} written, float{read} read, flag {flag:?}"); + match (flagged, read < written) { + (true, true) => { + r.unwrap_or_else(|e| panic!("{case}: {e}")); + } + (true, false) => assert_eq!(r.err().as_ref(), Some(&gap), "{case}"), + (false, _) => assert_eq!(r.err().as_ref(), Some(&link_error), "{case}"), + } + let Some(same) = assemble(&vertex_text(Class::Float, read, flag)) else { return; }; let same = compile(&same, "vs", &p).unwrap_or_else(|e| panic!("vs: {e}")); @@ -171,3 +258,50 @@ fn the_agx_flag_makes_a_component_count_mismatch_our_gap() { } } } + +/// Behind a vertex function whose module states the agx flag as 1, a fragment input narrower +/// than its vertex output (Metal reads the output's first lanes) takes the output's location at +/// component 0, which Vulkan matches under `maintenance4`: for `float` under perspective, +/// no-perspective and flat interpolation and for `uint` and `int` flat, a vector or a scalar read +/// from a wider vector. Both relocated modules pass L3 (`spirv-val` under the profile's settings, +/// `maintenance4` among them), and the input's `Location` is the output's, past `user(locn1)`. +#[test] +fn behind_the_agx_flag_a_narrower_input_links_at_its_output() { + let p = profile("lavapipe").expect("profile"); + let (render, fs_inputs) = pipeline(&p); + let key = VaryingKey::user(b"user(locn0)"); + let cases = [ + (Class::Float, PERSPECTIVE), + (Class::Float, NO_PERSPECTIVE), + (Class::Float, FLAT), + (Class::Uint, FLAT), + (Class::Int, FLAT), + ]; + for (c, interpolation) in cases { + for (written, read) in [(4, 2), (4, 1), (3, 2)] { + let case = format!("{c:?} {interpolation}: {written} written, {read} read"); + let (Some(vs), Some(fs)) = ( + assemble(&vertex_text(c, written, Some(1))), + assemble(&fragment_text(c, read, interpolation)), + ) else { + return; + }; + let vs = compile(&vs, "vs", &p).unwrap_or_else(|e| panic!("{case}: vs: {e}")); + let fs = compile_with(&fs, "fs", &p, &fs_inputs) + .unwrap_or_else(|e| panic!("{case}: fs: {e}")); + let l = link(&[&vs, &fs], &render, &p).unwrap_or_else(|e| panic!("{case}: {e}")); + let words: Vec> = [&vs, &fs] + .iter() + .map(|a| { + let words = relocate(a, &l.table).expect("relocate"); + check_words_valid(&words, &a.requirements, &p) + .unwrap_or_else(|e| panic!("{case}: L3: {e}")); + words + }) + .collect(); + let at = location(&vs, &words[0], &key); + assert_eq!(at, 1, "{case}: past user(locn1)"); + assert_eq!(location(&fs, &words[1], &key), at, "{case}"); + } + } +}