diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 12bfcb0e2..abb44f4ff 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 1965; +pub const SEMANTICS_VERSION: u32 = 1966; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index c56a6322a..7ba6baaa4 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -2273,7 +2273,25 @@ pub(crate) fn with_word( } } +/// The texel a read hands the function, before a heap element's null handle zeroes it: the held +/// texel, the heap element's liveness where the image is one, and the sparse arm's status word +/// where the function observes it. +struct ReadTexel { + texel: SValue, + live: Option, + word: Option, +} + fn read(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult { + let ReadTexel { texel, live, word } = read_texel(cx, fb, r)?; + let texel = live_or_zero(fb, live, texel)?; + // `{T, i8}`: the status word is the sparse arm's where the function observes it, else 0, + // Metal's for a resident access. + with_word(cx, fb, &r.result, texel, word) +} + +/// [`read`]'s texel ([`ReadTexel`]). +fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult { // A two-plane 3D texture's read takes its first texel ([`planes_volume`]). let volume = decl_of(cx, &r.image).is_some_and(|d| planes_volume(&d)); // A storage read's level is its level views'; a sampled read's, its `Lod`. @@ -2546,10 +2564,7 @@ fn read(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult< Some(declared) => reinterpret(fb, r.texel, declared, texel)?, None => texel, }; - let texel = live_or_zero(fb, live, texel)?; - // `{T, i8}`: the status word is the sparse arm's where the function observes it, else 0, - // Metal's for a resident access. - with_word(cx, fb, &r.result, texel, word) + Ok(ReadTexel { texel, live, word }) } /// The texel of heap read `r` (`Read::heap_raw`) where its handle's class index names a form a @@ -2723,6 +2738,17 @@ fn names_class(fb: &mut FunctionBuilder<'_>, index: SValue, class: TexelClass) - /// the handle's class index names ([`names_class`]), its words handed back as `r`'s, else `r` /// itself: Metal reads a member of another class in its own class and hands back the words, as /// at a slot. +/// +/// A `half` read's arms hand the merge their texel's `half` bits ([`ArmValue::HalfBits`]), which +/// it carries as integers, and one widening after it reads them as the value (`narrow::from_bits`): +/// a sibling's `half` is its words' low 16 bits widened where the merge ends, as a slot's read of +/// another class widens them (`reinterpret`), so a store of it moves those bits as the slot's +/// does, a NaN's included. Merged as values, each arm's `half` would be the device's widening of +/// its bits, selected against the zero a null handle reads and merged with the other arms'; Metal's +/// compiler does not fold the widening of such a merge back to the bits (`narrow::moves_unfolded`), +/// and on the Apple M3 Max a NaN's bits became `0x7E00` there. The own arm's bits are its texel's +/// narrowing (`narrow::to_bits`), the device's conversion of a `half` value, which a store of the +/// merged value took before. fn read_crossed(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult { let ImageRef::Heap { handle, .. } = r.image else { return read(cx, fb, r); @@ -2732,29 +2758,70 @@ fn read_crossed(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> } let h = cx.operand(fb, handle)?; let index = heap_class_field(fb, h)?; - read_arms(cx, fb, index, &r.heap_cross, r) + if r.texel.conv != TexelConv::F16 { + return read_arms(cx, fb, index, (&r.heap_cross, r), ArmValue::Read); + } + let half = r.texel.half(); + let bits = read_arms(cx, fb, index, (&r.heap_cross, r), ArmValue::HalfBits(half))?; + let texel = narrow::from_bits(fb, half, bits)?; + with_word(cx, fb, &r.result, texel, None) } -/// The first of `siblings` whose class `index` names, read, else the rest's, else `own`. +/// What each arm of a heap read with siblings hands its merge ([`read_crossed`]). +#[derive(Clone, Copy)] +enum ArmValue { + /// The read's value ([`read`]). + Read, + /// The `half` texel's bits in `u32` lanes, zero-extended, of the texel's form, zero where the + /// handle is null: a `half` read's. A heap read has no status word. + HalfBits(crate::lower::arith::legal::Form), +} + +/// Arm `r`'s value for its merge ([`ArmValue`]). +fn arm_value( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + r: &Read, + what: ArmValue, +) -> BResult { + match what { + ArmValue::Read => read(cx, fb, r), + ArmValue::HalfBits(half) => { + let ReadTexel { texel, live, word } = read_texel(cx, fb, r)?; + if word.is_some() { + return Err(cx.fail("a heap read's status word")); + } + let bits = narrow::to_bits(fb, half, texel)?; + live_or_zero(fb, live, bits) + } + } +} + +/// The first of `siblings` whose class `index` names, its arm's value ([`arm_value`]), else the +/// rest's, else `own`'s. fn read_arms( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, index: SValue, - siblings: &[Read], - own: &Read, + (siblings, own): (&[Read], &Read), + what: ArmValue, ) -> BResult { let Some((first, rest)) = siblings.split_first() else { - return read(cx, fb, own); + return arm_value(cx, fb, own, what); }; let Some(class) = first.heap_class else { return Err(cx.fail("a heap read's sibling without its class")); }; let named = names_class(fb, index, class)?; let then: ArmFn<'_, EmitCx<'_>> = - Box::new(move |fb, cx| Ok(ArmEnd::FallThrough(vec![read(cx, fb, first)?]))); + Box::new(move |fb, cx| Ok(ArmEnd::FallThrough(vec![arm_value(cx, fb, first, what)?]))); let other: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { Ok(ArmEnd::FallThrough(vec![read_arms( - cx, fb, index, rest, own, + cx, + fb, + index, + (rest, own), + what, )?])) }); let Merged(merged) = fb.if_(cx, named, then, Some(other))?; diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 137d26e4d..aebdac6f4 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -335,7 +335,8 @@ pub struct Read { /// The read, of a sampled color heap group of one sample, reads a member of another numeric /// class than its own in that class where the handle's class index names one /// (`metal::texel_format::heap_numeric_base`, or a float format's own class): one sibling - /// read per other class, the read itself for every other member. + /// read per other class, the read itself for every other member. A `half` read's arms merge + /// the texel's `half` bits, widened once after the merge (`emit::read_crossed`). pub heap_cross: Vec, } @@ -347,7 +348,7 @@ pub struct Read { /// clamp-to-edge read's size query, offset, and signed clamp; a `half` texel's call of the /// conversion routine or exact rounding, or an sRGB texel's raw decode; the lanes Metal reads as /// constants; the reinterpretation of another class's words; and each sibling of a heap read with -/// its class test and branch. +/// its class test and branch, and a `half` read's merge of its arms' bits. fn read_words(r: &Read) -> u32 { let own = 64 + if r.checked() { 80 } else { 0 } @@ -382,7 +383,18 @@ fn read_words(r: &Read) -> u32 { }; let declared = if r.declared.is_some() { 16 } else { 0 }; let siblings: u32 = r.heap_cross.iter().map(|x| read_words(x) + 24).sum(); - own + declared + siblings + // A `half` read with siblings merges its arms' bits (`emit::read_crossed`): each arm's + // narrowing (or its noted bits' mask) and null select, and one widening after the merge. + let half_bits = match (r.heap_cross.len() as u32, r.texel.conv) { + (0, _) => 0, + (n, TexelConv::F16) => { + let lanes = + u32::from(r.texel.lanes) * crate::lower::arith::narrow::bits_words(r.texel.half()); + (n + 1) * (lanes + 32) + lanes + } + _ => 0, + }; + own + declared + siblings + half_bits } /// A Metal 4.1 `read(sampler s, ...)` through a constexpr clamp-to-edge sampler (MSL 4.1 diff --git a/crates/metal2vulkan/src/tests/engine_cross_class.rs b/crates/metal2vulkan/src/tests/engine_cross_class.rs index 550af27d1..f22e87ea5 100644 --- a/crates/metal2vulkan/src/tests/engine_cross_class.rs +++ b/crates/metal2vulkan/src/tests/engine_cross_class.rs @@ -844,6 +844,66 @@ fn a_texture_an_argument_buffer_holds_is_read_in_its_own_class() { assert!(compiled > 0, "no committed profile has the sampled heap"); } +/// A `half` read of a texture an argument buffer holds merges its class arms as the texel's `half` +/// bits (`emit::read_crossed`), widened once after the merge: on every committed profile with a +/// sampled heap, the module merges a vector of four `u32`s and merges no texel struct, stays inside +/// the plan's word estimate and passes L3. A member of another class then keeps its words' low 16 +/// bits wherever the value is stored unchanged, where a merge of each arm's widened `half` selected +/// against a null handle's zero is a move Metal's compiler does not fold back to the bits (on the +/// Apple M3 Max a NaN's bits became `0x7E00`). A `float` read, which widens nothing, still merges +/// its texel structs. +#[test] +fn an_argument_buffer_half_read_merges_its_arms_bits() { + use crate::error::{Error, Feature, Unsupported}; + use crate::spirv::ir::Type as SType; + let inputs = LowerInputs::new(); + let mut compiled = 0; + for ty in [Ty::Half, Ty::Float] { + let name = format!("held read {ty:?}"); + let Some(bc) = assemble(&name, &held_kernel(Held::Read, ty)) else { + return; + }; + for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") { + let what = format!("{name} on {stem}"); + let m = match typed_module_with(&bc, "k", &p, &inputs) { + Ok((_, m)) => m, + Err(Error::Unsupported(Unsupported { + feature: Feature::ArgumentBufferTextures, + .. + })) => continue, + Err(e) => panic!("{what}: {e}"), + }; + validate(&bc, &inputs, &p, &what); + let phis: Vec<&SType> = m + .blocks() + .iter() + .flat_map(|b| &b.phis) + .map(|phi| { + let ty = m.value(phi.result).expect("a phi's value").ty; + m.types().get(ty).expect("a phi's type") + }) + .collect(); + let bits = phis.iter().any(|t| match t { + SType::Vector { elem, len: 4 } => matches!( + m.types().get(*elem), + Ok(SType::Int { + width: 32, + signed: false + }) + ), + _ => false, + }); + let texels = phis.iter().any(|t| matches!(t, SType::Struct { .. })); + match ty { + Ty::Half => assert!(bits && !texels, "{what}: {phis:?}"), + _ => assert!(texels, "{what}: {phis:?}"), + } + compiled += 1; + } + } + assert!(compiled > 0, "no committed profile has the sampled heap"); +} + /// A kernel writing the `ty` texel `src[gid.x + 16 gid.y]` (buffer 0) to `access::write` texture /// slot 0 at its thread's texel `gid`. fn write_kernel(ty: Ty) -> String {