diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 9770d1a7b..5c440c8ec 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2285,6 +2285,14 @@ made, with no lock, and never rewritten for layouts. (llvmpipe, job m3-max-80997) a kernel state of the fixture `tb_word_formats` spent 16.9 to 23.5 ms making its twin (specialization and driver create) against at least 2.9 to 5.3 ms creating its plain pipeline, about 4 to 7 times as long, over five formats. +- A texture buffer held as words is read, written and asked its width through the words alone: a + function that reaches one by any other access, a read through a sampler (MSL 4.1's + `read(sampler, coord)`) among them, reads the texture's own view, which such a texture buffer + lacks. Such an access compiles as on a device that holds every format directly + (`RuntimeFact::TexelBufferOwnView`), and a draw or dispatch that binds a texture buffer held as + words where it reaches one is refused (`Gap::TexelBufferOwnView`); through an argument + buffer's texture, any such draw or dispatch while a texture buffer held as words is live on the + device. A texture buffer of a format the device holds directly runs as Metal's. - `replace_region` and `get_bytes` of a texture without named bytes go through the staging region: a copy Metal does not make, counted in `Metrics::bytes_copied`. - A blit copy between textures of a compressed region of whole blocks that ends inside one diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 695561eb7..f55061800 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1018,7 +1018,8 @@ impl ComputeCommandEncoder { /// bound at a multiple of 4 runs on its kernel's variant that holds it to 4); /// [`Gap::SwizzledReadWrite`]; [`Gap::OpenClLineTexture`]; [`Refusal::TextureUsageAtSlot`] /// for a texture the kernel's slot reaches whose usage lacks what the kernel's access there - /// asks; [`Gap::BicubicTexels`]; + /// asks; [`Gap::BicubicTexels`]; [`Gap::TexelBufferOwnView`] for a texture buffer held as words + /// where the kernel reaches a texture buffer's own view alone; /// [`Limit::LevelElements`] where no run of level elements holds a texture of several levels /// the kernel writes or reads at a level other than the constant 0; /// [`Limit::ThreadgroupMemory`], the imageblock's cells at the size @@ -1312,9 +1313,14 @@ impl ComputeCommandEncoder { if direct.is_some_and(|(_, groups, _)| groups.contains(&0)) { return Ok(()); } - // The module's words twin where a texture buffer held as words is bound where it reaches + // No texture buffer held as words where the kernel reaches a texture buffer's own view + // alone, which it lacks; then the module's words twin where one is bound where it reaches // one. let textures = &self.textures; + kernel.own_view_gap(core, |slot| match textures.get(slot as usize) { + Some(Some(t)) if t.held_as_words() => Some(t.descriptor().pixel_format), + _ => None, + })?; let words = kernel.binds_words( core, |slot| matches!(textures.get(slot as usize), Some(Some(t)) if t.held_as_words()), diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index bae7f72ea..bdd00614c 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1601,6 +1601,29 @@ pub enum Gap { /// The kernel's texture slot. slot: u32, }, + /// A draw or dispatch whose function reaches a texture buffer held as words by an access the + /// words do not build, which takes the texture's own view alone. A texture buffer is held as + /// words where the device holds no texel-buffer view of its format + /// (`metal2vulkan::metal::format::texel_buffer_form`), and the function converts its texels + /// from its bytes; the accesses that take the own view alone + /// (`RuntimeFact::TexelBufferOwnView`) are a read through a sampler (MSL 4.1's + /// `read(sampler, coord)`), a read that observes residency, a read or write in another numeric + /// class than the texture's, and a write of fewer than four lanes. + /// With `slot`: a texture buffer held as words bound at that texture slot of a function that + /// reaches it so. Without: a function that reaches a texture buffer so through a handle (an + /// argument buffer's texture), while a texture buffer held as words is live on the device. A + /// program that binds no texture buffer held as words where such an access reaches it runs as + /// on a device that holds every format's texture buffers directly. Metal reads and writes such + /// a texture buffer. + /// + /// Basis: ours (the words build a texel's read, its write and the width; a read through a + /// sampler's address mode is the next). + TexelBufferOwnView { + /// The function's texture slot, or `None` for one it reaches through a handle. + slot: Option, + /// The pixel format of the texture buffer at `slot`. + pixel_format: Option, + }, /// A draw or dispatch whose function writes a texture slot, or reads one through its storage /// image (`access::read_write`), bound to a texture made for shader writes with no storage /// element, or, at a slot declared without a format (`TextureSlot::declared_format`; a texture @@ -3320,6 +3343,20 @@ impl fmt::Display for Gap { "an OpenCL-mode kernel's texture slot {slot} bound to a 1D texture, which Apple's \ OpenCL never binds, is not built" ), + Gap::TexelBufferOwnView { + slot: Some(slot), + pixel_format: Some(pixel_format), + } => write!( + f, + "texture slot {slot}, which a function reads through a sampler or otherwise reaches \ + by its own view, bound to a texture buffer of {pixel_format:?} held as words is \ + not built" + ), + Gap::TexelBufferOwnView { .. } => f.write_str( + "a texture buffer a function reads through a sampler or otherwise reaches by its \ + own view through a handle, while a texture buffer held as words is live, is not \ + built", + ), Gap::StorageElement { slot: Some(slot), pixel_format, diff --git a/crates/metal2vulkan-runtime/src/error/basis.rs b/crates/metal2vulkan-runtime/src/error/basis.rs index a80d1b420..20210e556 100644 --- a/crates/metal2vulkan-runtime/src/error/basis.rs +++ b/crates/metal2vulkan-runtime/src/error/basis.rs @@ -167,6 +167,7 @@ impl Gap { Gap::RenderPipeline { .. } => RefusalBasis::Ours, Gap::SwizzledReadWrite { .. } => RefusalBasis::Ours, Gap::OpenClLineTexture { .. } => RefusalBasis::Ours, + Gap::TexelBufferOwnView { .. } => RefusalBasis::Ours, Gap::StorageElement { .. } => RefusalBasis::Ours, Gap::BicubicTexels { .. } => RefusalBasis::Ours, Gap::TextureView { .. } => RefusalBasis::Ours, diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 7a51df711..e84f26e33 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -78,7 +78,7 @@ use metal2vulkan::cache::Hash256; use metal2vulkan::device::{VkLimit, KERNEL_BUFFER_BINDINGS}; use metal2vulkan::error::{Capability, Error as TranslationError, Feature, Needs, Unsupported}; use metal2vulkan::library::{CompiledFunction, FunctionCompileKey}; -use metal2vulkan::metal::{BindingAccess, BindingType, TextureType, TextureUsage}; +use metal2vulkan::metal::{BindingAccess, BindingType, PixelFormat, TextureType, TextureUsage}; use metal2vulkan::pipeline::{ arena_bytes, threadgroup_constants, AccessSet, BindingSource, BufferKind, CombinedSampler, ComputePipeline, ComputePipelineDescriptor, DescriptorSetLayout, FunctionDescriptor, @@ -856,6 +856,10 @@ pub(crate) struct Interface { /// Where the kernel declares `SpecKey::TexelBufferWords`, what a dispatch reads to pick its /// words twin ([`Kernel::binds_words`]). pub(crate) words: Option, + /// Where the kernel reaches a texture buffer's own view alone (`RuntimeFact::TexelBufferOwnView`), + /// which a texture buffer held as words lacks: a dispatch that binds one there is refused + /// ([`Kernel::own_view_gap`]). + pub(crate) own_views: OwnViews, /// The index of each threadgroup memory argument the kernel takes, in the order of /// [`Variant::lengths`]' words. pub(crate) threadgroups: Vec, @@ -930,6 +934,16 @@ pub(crate) struct WordReach { pub(crate) handles: bool, } +/// Where a function reaches a texture buffer by an access that takes its own view alone +/// (`RuntimeFact::TexelBufferOwnView`), which a texture buffer held as words lacks. +#[derive(Default)] +pub(crate) struct OwnViews { + /// Its texture slots. + pub(crate) slots: Vec, + /// It reaches one through a handle (an argument buffer's texture). + pub(crate) handles: bool, +} + /// What sets a specialization constant. #[derive(Clone, Copy)] pub(crate) enum Constant { @@ -1835,6 +1849,7 @@ pub(crate) fn interface( let mut imageblock = None; let mut own = OwnMemory::Static(pipeline.metal_info.static_threadgroup_memory_length); let mut open_cl_mode = false; + let mut own_views = OwnViews::default(); for dependency in &pipeline.dependencies { match dependency.fact { RuntimeFact::LocalSizeConstraint { multiple } => multiples.push(multiple), @@ -1884,6 +1899,15 @@ pub(crate) fn interface( // the device reads; OpenCL mode decides which textures a dispatch takes. RuntimeFact::CallStackDepth { .. } => {} RuntimeFact::OpenClMode => open_cl_mode = true, + // A texture buffer's own view, which a dispatch that binds one held as words there + // lacks (`Kernel::own_view_gap`). + RuntimeFact::TexelBufferOwnView { + stage: Stage::Kernel, + texture, + } => match texture { + Some(slot) => own_views.slots.push(slot), + None => own_views.handles = true, + }, // `RuntimeFact` is non-exhaustive: a fact this match does not name is one the encoder // does not supply, and the refusal names it. fact => { @@ -2165,6 +2189,7 @@ pub(crate) fn interface( fields, constants, words, + own_views, threadgroups, max_total_threads, metal_max_total_threads, @@ -3056,6 +3081,33 @@ impl Kernel { || reach.handles && core.counters.live(Gauge::WordTextureBuffers) > 0 } + /// Err: [`Gap::TexelBufferOwnView`] where the kernel reaches a texture buffer's own view alone + /// ([`Interface::own_views`]) and a dispatch holds a texture buffer held as words there: at a + /// slot, for which `held` answers its texture's pixel format where it is one, or through a + /// handle, while one is live on the device + /// ([`Gauges::word_texture_buffers`](crate::Gauges::word_texture_buffers)). + pub(crate) fn own_view_gap( + &self, + core: &Core, + held: impl Fn(u32) -> Option, + ) -> Result<(), Error> { + let views = &self.interface.own_views; + let bound = (views.slots.iter()).find_map(|&slot| held(slot).map(|pf| (slot, pf))); + if let Some((slot, pixel_format)) = bound { + return Err(Error::Unsupported(Gap::TexelBufferOwnView { + slot: Some(slot), + pixel_format: Some(pixel_format), + })); + } + if views.handles && core.counters.live(Gauge::WordTextureBuffers) > 0 { + return Err(Error::Unsupported(Gap::TexelBufferOwnView { + slot: None, + pixel_format: None, + })); + } + Ok(()) + } + /// The ids of the kernel's specialization constants and their values for `variant`, 4 bytes /// each, in order: its words twin's where `words`. fn specialization(&self, variant: &Variant, words: bool) -> (Vec, Vec) { diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index b672a2ebe..3f4a9ce3b 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -96,7 +96,8 @@ use ash::vk; use metal2vulkan::cache::{Hash256, VariantKey}; use metal2vulkan::device::EnabledCaps; use metal2vulkan::metal::{ - BindingAccess, PrimitiveTopologyClass, TessellationControlPointIndexType, TextureUsage, + BindingAccess, PixelFormat, PrimitiveTopologyClass, TessellationControlPointIndexType, + TextureUsage, }; use metal2vulkan::pipeline::{ specialize, BufferKind, CombinedSampler, NumberedSampler, PrecisionNote, PushField, PushLoc, @@ -270,6 +271,11 @@ pub(crate) struct Draws { /// words is bound at one, a draw of a content with a words twin runs it /// ([`RenderCompiled::binds_words`]). pub(crate) texel_buffers: Vec<(usize, u32)>, + /// Where a function reaches a texture buffer by an access that takes its own view alone + /// (`RuntimeFact::TexelBufferOwnView`), which a texture buffer held as words lacks: each such + /// texture slot with its function, and whether one does so through a handle + /// ([`RenderCompiled::own_view_gap`]). + pub(crate) own_views: (Vec<(usize, u32)>, bool), /// Each texture slot a function uses, with its function and the usage Metal asks of the /// texture bound there (`crate::pipeline::slot_usage`). pub(crate) usages: Vec<(usize, u32, TextureUsage)>, @@ -910,6 +916,7 @@ fn draws( }; // The slot's address, rounded down to a multiple of its argument's alignment. let mut aligned = Vec::new(); + let mut own_views = (Vec::new(), false); for dependency in &pipeline.dependencies { match dependency.fact { RuntimeFact::AddressAlignment { @@ -963,6 +970,12 @@ fn draws( // A fragment function's stencil output on a device without stencil export, which each // draw takes by bits through its push field (`Draws::stencil_bit`). RuntimeFact::StencilBitDraws => {} + // A texture buffer's own view, which a draw that binds one held as words there lacks + // (`RenderCompiled::own_view_gap`). + RuntimeFact::TexelBufferOwnView { stage, texture } => match texture { + Some(slot) => own_views.0.push((table(stage)?, slot)), + None => own_views.1 = true, + }, // `RuntimeFact` is non-exhaustive: a fact this match does not name is one a draw does // not supply, and the refusal names it. fact => { @@ -1209,6 +1222,7 @@ fn draws( buffers, textures, texel_buffers, + own_views, usages, storage_reads, formatless, @@ -1706,6 +1720,33 @@ impl RenderCompiled { || twin.handles && self.core.counters.live(Gauge::WordTextureBuffers) > 0 } + /// Err: [`Gap::TexelBufferOwnView`] where a function reaches a texture buffer's own view alone + /// ([`Draws::own_views`]) and a draw holds a texture buffer held as words there: at a slot, for + /// which `held` answers its function's texture's pixel format where it is one, or through a + /// handle, while one is live on the device + /// ([`Gauges::word_texture_buffers`](crate::Gauges::word_texture_buffers)). + pub(crate) fn own_view_gap( + &self, + held: impl Fn(usize, u32) -> Option, + ) -> Result<(), Error> { + let (slots, handles) = &self.draws.own_views; + let bound = + (slots.iter()).find_map(|&(table, slot)| held(table, slot).map(|pf| (slot, pf))); + if let Some((slot, pixel_format)) = bound { + return Err(Error::Unsupported(Gap::TexelBufferOwnView { + slot: Some(slot), + pixel_format: Some(pixel_format), + })); + } + if *handles && self.core.counters.live(Gauge::WordTextureBuffers) > 0 { + return Err(Error::Unsupported(Gap::TexelBufferOwnView { + slot: None, + pixel_format: None, + })); + } + Ok(()) + } + /// The `VkPipeline` of `cells` for `class` under `raster`, made by `make` where it is not: /// a main one by [`Main::pipeline`], another by the first draw that takes it, a first-use /// wait, as [`RenderCompiled::pipeline`] counts them. diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index 9f0dd67c2..4fc4bacd3 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -2996,6 +2996,11 @@ impl RenderCommandEncoder { // Points Metal does not rasterize: the vertex function runs, behind an empty scissor. let hidden = topology == vk::PrimitiveTopology::POINT_LIST && !compiled.rasterizes_points(); let tables = &self.tables; + compiled.own_view_gap(|table, slot| { + (tables[table].texture(slot)) + .filter(|t| t.held_as_words()) + .map(|t| t.descriptor().pixel_format) + })?; let words = compiled.binds_words(|table, slot| { tables[table] .texture(slot) @@ -3510,6 +3515,11 @@ impl RenderCommandEncoder { }; let (topology, _) = executed_topology(buffer); let tables = &self.tables; + compiled.own_view_gap(|table, slot| { + (tables[table].texture(slot)) + .filter(|t| t.held_as_words()) + .map(|t| t.descriptor().pixel_format) + })?; let words = compiled.binds_words(|table, slot| { tables[table] .texture(slot) diff --git a/crates/metal2vulkan-runtime/src/tests/compute.rs b/crates/metal2vulkan-runtime/src/tests/compute.rs index e5be31735..c8dfb70c0 100644 --- a/crates/metal2vulkan-runtime/src/tests/compute.rs +++ b/crates/metal2vulkan-runtime/src/tests/compute.rs @@ -66,6 +66,7 @@ pub(crate) mod on_device { (2, Constant::Threadgroup(SpecKey::LocalSize(Axis::Z))), ], words: None, + own_views: Default::default(), threadgroups: Vec::new(), max_total_threads: 1024, metal_max_total_threads: 1024, diff --git a/crates/metal2vulkan-runtime/src/tests/texture_buffer_words.rs b/crates/metal2vulkan-runtime/src/tests/texture_buffer_words.rs index 0c7b3f4fa..a6b8a956d 100644 --- a/crates/metal2vulkan-runtime/src/tests/texture_buffer_words.rs +++ b/crates/metal2vulkan-runtime/src/tests/texture_buffer_words.rs @@ -720,6 +720,181 @@ mod on_device { }); } + /// The bytes of a texel of `format` whose channels (red, green, blue, alpha) are each 0 or + /// 1, for the formats [`a_read_through_a_sampler_refuses_a_texture_buffer_held_as_words`] + /// reads; the alpha of `B5G6R5Unorm`, which has none, reads 1. + fn ones_texel(format: PixelFormat, c: [bool; 4]) -> Vec { + let [r, g, b, a] = c; + let n = |on: bool, max: u32| if on { max } else { 0 }; + match format { + PixelFormat::RGBA32Float => (c.iter()) + .flat_map(|&on| (if on { 1.0f32 } else { 0.0 }).to_le_bytes()) + .collect(), + PixelFormat::RGBA16Float => (c.iter()) + .flat_map(|&on| n(on, 0x3c00).to_le_bytes()[..2].to_vec()) + .collect(), + PixelFormat::RGBA16Unorm => (c.iter()) + .flat_map(|&on| n(on, 0xffff).to_le_bytes()[..2].to_vec()) + .collect(), + PixelFormat::RGBA8Unorm => c.iter().map(|&on| n(on, 255) as u8).collect(), + PixelFormat::BGRA8Unorm => [b, g, r, a].iter().map(|&on| n(on, 255) as u8).collect(), + PixelFormat::B5G6R5Unorm => { + let t = n(r, 31) << 11 | n(g, 63) << 5 | n(b, 31); + t.to_le_bytes()[..2].to_vec() + } + other => panic!("no texel of {other:?}"), + } + } + + /// `kernel_read_through`'s `rt_buffer_ow` reads a texture buffer slot through a sampler + /// (`clamp_to_border`, opaque white), which the words do not build: it compiles on every + /// device as where no format is held as words, and records `RuntimeFact::TexelBufferOwnView` + /// of its slot where some is. Over each of six formats of four channels or none missing but + /// alpha, by the form the device holds it in: + /// + /// - held directly, a dispatch reads each texel in bounds and Metal's border texel, white, + /// past the width: of formats without a word layout (`RGBA32Float`, `RGBA16Float`, + /// `RGBA8Unorm`), whose word holds their border texels, and of formats with one + /// (`BGRA8Unorm`, `RGBA16Unorm`, `B5G6R5Unorm`), whose word holds the layout's fields in + /// their place and whose border texels the function takes from the format's code; + /// - held as words, the dispatch that binds it is `Gap::TexelBufferOwnView` of slot 0 and the + /// format, and the same state's next dispatch, of a format held directly, runs as above. + /// + /// Each line names the form; a device that holds none of the six as words prints that the + /// refusal was not reached. + #[test] + fn a_read_through_a_sampler_refuses_a_texture_buffer_held_as_words() { + let name = "kernel_read_through.ll"; + let library = match llvm_assemble(&engine_dir().join(name)) { + Ok(bitcode) => Library::from_air(&bitcode).expect("the library"), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return; + } + Err(error) => panic!("{name}: {error:?}"), + }; + const FORMATS: [PixelFormat; 6] = [ + PixelFormat::RGBA32Float, + PixelFormat::RGBA16Float, + PixelFormat::RGBA8Unorm, + PixelFormat::BGRA8Unorm, + PixelFormat::RGBA16Unorm, + PixelFormat::B5G6R5Unorm, + ]; + // Thread `t` reads index `AT[t]` of a texture buffer of 4 texels: texel `t` is channel + // `c` 1 where bit `c` of `t + 1` is set, never all four; past the width, the border. + const AT: [i32; THREADS] = [0, 1, 2, 3, 4, -1, 7, 1000]; + let texel_of = |t: usize| -> [bool; 4] { std::array::from_fn(|c| (t + 1) >> c & 1 == 1) }; + each_device( + "texture buffer read through a sampler", + |name, _, device| { + let _grant = (device.grant_indices(IndexClass::Texture, 1, FORMATS.len() as u32)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let function = library.function("rt_buffer_ow").expect("the kernel"); + let descriptor = ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + )); + let state = (device + .new_compute_pipeline_state(&descriptor, |s| Ok(vec![0; s.len()]))) + .unwrap_or_else(|error| panic!("{name}: no state: {error}")); + let block = (device.take_block(MemoryClass::Shared, 16 << 10)).expect("a block"); + let place = + |(at, len)| (device.new_buffer(block.id, at, len, Some(0))).expect("a buffer"); + let data = place((0, 4096)); + let at = place((4096, 256)); + let out = place((8192, 256)); + let ats: Vec = (AT.iter()) + .flat_map(|&x| [x, 0, 0, 0].map(i32::to_le_bytes).concat()) + .collect(); + set_bytes(&at, 0, &ats); + let profile = device.translator().profile(); + let mut failed = Vec::new(); + let mut refused = 0; + for (k, format) in FORMATS.into_iter().enumerate() { + let words = matches!( + formats::texel_buffer_form(format, profile), + Some(formats::TexelBufferForm::Words(_)) + ); + let form = if words { "words" } else { "own view" }; + let texels: Vec = (0..4) + .flat_map(|t| ones_texel(format, texel_of(t))) + .collect(); + let offset = 512 * k; + set_bytes(&data, offset, &texels); + set_bytes(&out, 0, &[0; 256]); + let mut d = TextureDescriptor::new(TextureType::TextureBuffer, format, 4, 1); + d.usage = TextureUsage::SHADER_READ; + let index = 1 + u32::try_from(k).expect("an index"); + let texture = (data.new_texture(&d, Some(index), offset as u64, 256)) + .unwrap_or_else(|error| { + panic!("{name}: {format:?} ({form}) not made: {error}") + }); + let dispatched = dispatch(&device, &state, &[&texture], &[&at, &out]); + match (words, dispatched) { + ( + true, + Err(crate::Error::Unsupported(crate::Gap::TexelBufferOwnView { + slot: Some(0), + pixel_format: Some(f), + })), + ) if f == format => { + refused += 1; + println!( + "{name}: {format:?} ({form}): refused, Gap::TexelBufferOwnView" + ); + continue; + } + (_, Err(error)) => { + println!("{name}: {format:?} ({form}): {error}"); + failed.push(format); + continue; + } + (true, Ok(())) => { + println!("{name}: {format:?} ({form}): dispatched, not refused"); + failed.push(format); + continue; + } + (false, Ok(())) => {} + } + let got = floats(&out); + let mut wrong = Vec::new(); + for (t, &x) in AT.iter().enumerate() { + let want: [bool; 4] = match usize::try_from(x) { + Ok(i) if i < 4 => { + let mut c = texel_of(i); + c[3] |= format == PixelFormat::B5G6R5Unorm; + c + } + _ => [true; 4], + }; + let want = want.map(|on| if on { 1.0f32 } else { 0.0 }); + if got[4 * t..4 * t + 4] != want { + wrong.push(format!( + "index {x}: {:?}, Metal {want:?}", + &got[4 * t..4 * t + 4] + )); + } + } + match wrong.is_empty() { + true => { + println!("{name}: {format:?} ({form}): every texel and border Metal's") + } + false => { + println!("{name}: {format:?} ({form}): {wrong:?}"); + failed.push(format); + } + } + } + if refused == 0 { + println!( + "{name}: none of the formats is held as words: the refusal is not reached" + ); + } + assert!(failed.is_empty(), "{name}: formats that differ: {failed:?}"); + }, + ); + } + /// The colour a fragment reads of `texel`, of `R8Unorm` or of `B5G6R5Unorm` (red in bits 11 /// to 15, green in 5 to 10, blue in 0 to 4). fn draw_colour(format: PixelFormat, texel: &[u8]) -> [f64; 4] { diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index ce8e78346..94983e0ca 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1268,6 +1268,7 @@ codec_enum! { PrivateArena { slot_bytes }, StencilBitDraws, RobustStorageBuffers, + TexelBufferOwnView { stage, texture }, } Mechanism { Specialization, Variant, PushConstant, DynamicState, DynamicStateOrPushConstant, diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 682c8ce28..3bc044697 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -166,6 +166,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::StencilBitDraws => Mechanism::PushConstant, // The pipeline's robustness, which the consumer states as it makes it. RuntimeFact::RobustStorageBuffers => Mechanism::PipelineState, + // The runtime refuses a draw or dispatch that binds a texture buffer held as words where + // the function reaches its own view. + RuntimeFact::TexelBufferOwnView { .. } => Mechanism::PlanTimeCheck, // Keyed by the slots bound to a texture buffer of more texels than one view holds. RuntimeFact::TexelBufferParts { .. } => Mechanism::Variant, // The runtime refuses a dispatch whose slot address is not a multiple of the alignment. diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 62b7d5132..761bc7d3a 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -200,6 +200,14 @@ fn every_fact() -> Vec { RuntimeFact::PrivateArena { slot_bytes: 28_704 }, RuntimeFact::StencilBitDraws, RuntimeFact::RobustStorageBuffers, + RuntimeFact::TexelBufferOwnView { + stage: Stage::Kernel, + texture: Some(0), + }, + RuntimeFact::TexelBufferOwnView { + stage: Stage::Fragment, + texture: None, + }, ] } @@ -294,6 +302,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::PrivateArena { .. } => 68, RuntimeFact::StencilBitDraws => 85, RuntimeFact::RobustStorageBuffers => 86, + RuntimeFact::TexelBufferOwnView { .. } => 87, } } @@ -301,7 +310,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..87).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..88).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -352,7 +361,8 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::HeapStorageReads { .. } | RuntimeFact::ObjectThreadgroupArena { .. } | RuntimeFact::AddressAlignment { .. } - | RuntimeFact::RowLockstep => Mechanism::PlanTimeCheck, + | RuntimeFact::RowLockstep + | RuntimeFact::TexelBufferOwnView { .. } => Mechanism::PlanTimeCheck, RuntimeFact::DispatchGrid | RuntimeFact::TileThreadgroup { .. } | RuntimeFact::PartialObjectThreadgroups diff --git a/crates/metal2vulkan/src/lower/texture/words.rs b/crates/metal2vulkan/src/lower/texture/words.rs index 243410585..5828537ff 100644 --- a/crates/metal2vulkan/src/lower/texture/words.rs +++ b/crates/metal2vulkan/src/lower/texture/words.rs @@ -20,8 +20,14 @@ //! 1 for a format without alpha, bit 12 of the word), a write outside it is dropped, as Metal //! drops it, the padding of the last word included. //! -//! A texture buffer of a word layout carries its fields in its word's border texels; a slot's -//! read through a sampler of one takes its format's from its code ([`border_texels`]). +//! A read through a sampler, a read that observes its residency, a read or write in another +//! numeric class than the bound texture's, a read of an sRGB texture's codes and a write of fewer +//! than four lanes are not built for the words: such an access takes the texture's own view alone, +//! as on a profile that holds no format as words, and the stage records +//! `RuntimeFact::TexelBufferOwnView` for its slot or its handles, where the runtime refuses a +//! texture buffer held as words. A texture buffer of a word layout carries its fields in its word's +//! border texels; a slot's read through a sampler of one takes its format's from its code +//! ([`border_texels`]). //! //! A read converts each channel as Metal reads it: a normalized code `c` of `n` bits to //! `c / (2^n - 1)` correctly rounded ([`unorm_values`]: the code's repeating binary expansion, @@ -63,6 +69,7 @@ use crate::metal::format::{ }; use crate::metal::resource_word::TextureWord; use crate::pipeline::artifact::PrecisionNote; +use crate::pipeline::facts::RuntimeFact; use crate::pipeline::lower_inputs::{ChannelWrite, StorageImageClass}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; @@ -193,7 +200,8 @@ impl Words { /// has a texel: under the identity domains, a texture buffer's read, write and width query, of a /// slot or an argument buffer's texture, become [`Words`], with the routine and arrays they reach /// planned, the device-scope atomics a write may take, and the precision notes of the conversions -/// a `float` access may take. Any other strategy is `s`. +/// a `float` access may take; but a read or write the routines do not build stays `s`, its own +/// view's alone ([`own_view`]). Any other strategy is `s`. pub(super) fn wrap( cx: &mut SelectCx<'_>, (image, dim): (ImageRef, ImageDim), @@ -213,7 +221,7 @@ pub(super) fn wrap( let routine = match (&s, class) { (TextureStrategy::Read(r), Some(class)) => { if r.declared.is_some() || r.residency || r.through.is_some() || r.raw { - return Err(super::refuse()); + return Ok(own_view(cx, image, s)); } Some(Routine::Read { class, @@ -223,7 +231,7 @@ pub(super) fn wrap( } (TextureStrategy::Write(w), Some(class)) => { if w.cross.is_some() || w.texel.lanes != 4 { - return Err(super::refuse()); + return Ok(own_view(cx, image, s)); } Some(Routine::Write { class, nonuniform }) } @@ -283,6 +291,21 @@ pub(super) fn wrap( }))) } +/// `s`, an access of texture buffer `image` the words do not build ([`wrap`]), which takes the +/// texture's own view alone: recorded as `RuntimeFact::TexelBufferOwnView` of the slot, or of the +/// stage's handles, where the binder refuses a texture buffer held as words. +fn own_view(cx: &mut SelectCx<'_>, image: ImageRef, s: TextureStrategy) -> TextureStrategy { + let texture = match image { + ImageRef::Slot(n) => Some(n), + ImageRef::Heap { .. } => None, + }; + cx.facts.insert(RuntimeFact::TexelBufferOwnView { + stage: cx.stage, + texture, + }); + s +} + /// The declaration of a texel-buffer array of unsigned integer elements: the uniform one, or the /// storage one of `R32Uint` (`storage`). fn array_decl(storage: bool) -> ImageDecl { diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 5c1f6cfb7..34e162638 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -617,6 +617,18 @@ pub enum RuntimeFact { /// `max(minStorageBufferOffsetAlignment, 16)` through its last (`docs/API.md` section 5). A /// read outside the range then reads zero and a write there changes nothing. RobustStorageBuffers, + /// Under the identity domains, on a profile that holds some colour format's texture buffers as + /// words (`metal::format::texel_buffer_form`), the function reaches a texture buffer by an + /// access the words do not build (`lower::texture::words`), which takes the texture's own view + /// alone: a read through a sampler, a read that observes its residency, a read or write in + /// another numeric class than the bound texture's, a read of an sRGB texture's codes, or a + /// write of fewer than four lanes. A texture buffer held as words has no such view. `texture`: + /// the slot `[[texture(n)]]` of the stage the access reaches, or `None` for a texture buffer it + /// reaches through a handle (an argument buffer's texture). The binder refuses a draw or + /// dispatch that binds a texture buffer held as words at the slot, or, for `None`, one while a + /// texture buffer held as words may be reached through a handle; any other runs as the + /// function was compiled. + TexelBufferOwnView { stage: Stage, texture: Option }, } impl RuntimeFact { @@ -713,6 +725,7 @@ impl RuntimeFact { RuntimeFact::PrivateArena { .. } => "PrivateArena", RuntimeFact::StencilBitDraws => "StencilBitDraws", RuntimeFact::RobustStorageBuffers => "RobustStorageBuffers", + RuntimeFact::TexelBufferOwnView { .. } => "TexelBufferOwnView", } } } diff --git a/crates/metal2vulkan/src/tests/engine_identity.rs b/crates/metal2vulkan/src/tests/engine_identity.rs index 0e274c827..a5a2d1cf8 100644 --- a/crates/metal2vulkan/src/tests/engine_identity.rs +++ b/crates/metal2vulkan/src/tests/engine_identity.rs @@ -571,6 +571,40 @@ fn a_texture_buffer_is_the_texel_buffer_element_its_resource_id_names() { } } +/// A read through a sampler of a texture buffer slot (`kernel_read_through`'s `rt_buffer`, +/// `rt_buffer_ow` and `rt_arg_buffer`), which the words of a texture buffer held as words do not +/// build, compiles under the identity domains on each profile and passes L3: it reads the slot's +/// own view, and where the profile holds some format's texture buffers as words it records +/// `RuntimeFact::TexelBufferOwnView` of the slot, where the runtime refuses one held as words; on a +/// profile that holds none so it records nothing of it. One of the profiles holds some so. +#[test] +fn a_read_through_a_sampler_of_a_texture_buffer_takes_its_own_view() { + let Some(bc) = assemble("kernel_read_through") else { + return; + }; + let mut holding = 0; + for stem in PROFILES { + let p = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}")); + let held = crate::metal::format::texel_buffer_word_codes(&p) != 0; + holding += usize::from(held); + for entry in ["rt_buffer", "rt_buffer_ow", "rt_arg_buffer"] { + let (a, plan, _) = + compile_kept(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem} {entry}: L3: {e}")); + let own: Vec = (plan.facts.iter().copied()) + .filter(|f| matches!(f, RuntimeFact::TexelBufferOwnView { .. })) + .collect(); + let want = RuntimeFact::TexelBufferOwnView { + stage: Stage::Kernel, + texture: Some(0), + }; + let want: Vec = held.then_some(want).into_iter().collect(); + assert_eq!(own, want, "{stem} {entry}"); + } + } + assert!(holding > 0, "no profile holds a format as words"); +} + /// The words of `sample_up`'s constexpr sampler (`fixtures/public/harness/workloads.ll`). const SAMPLE_UP_WORDS: [u64; 2] = [34_901_797_601_020_489, 0]; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index c64ad479e..e2a72360f 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -8530,6 +8530,7 @@ variant metal2vulkan-runtime::Gap::StageSize StageSize { weight: u64, cause: Sta variant metal2vulkan-runtime::Gap::StorageElement StorageElement { slot: Option, pixel_format: PixelFormat, case: StorageElementCase, backing: TextureBacking } variant metal2vulkan-runtime::Gap::SurfaceUsage SurfaceUsage { pixel_format: PixelFormat, missing: u32 } variant metal2vulkan-runtime::Gap::SwizzledReadWrite SwizzledReadWrite { slot: u32 } +variant metal2vulkan-runtime::Gap::TexelBufferOwnView TexelBufferOwnView { slot: Option, pixel_format: Option } variant metal2vulkan-runtime::Gap::TextureBufferSwizzle TextureBufferSwizzle { pixel_format: PixelFormat } variant metal2vulkan-runtime::Gap::TextureBytes TextureBytes { pixel_format: PixelFormat } variant metal2vulkan-runtime::Gap::TextureCopy TextureCopy { source: PixelFormat, destination: PixelFormat } @@ -10227,6 +10228,7 @@ variant metal2vulkan::pipeline::RuntimeFact::StorageTextureLevelViews StorageTex variant metal2vulkan::pipeline::RuntimeFact::StorageTextureLevels StorageTextureLevels { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureNumericType StorageTextureNumericType { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::StorageTextureWriteRounding StorageTextureWriteRounding { slot: SlotRef, halves: bool } +variant metal2vulkan::pipeline::RuntimeFact::TexelBufferOwnView TexelBufferOwnView { stage: Stage, texture: Option } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferParts TexelBufferParts { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TexelBufferRange TexelBufferRange { slot: SlotRef } variant metal2vulkan::pipeline::RuntimeFact::TextureSwizzle TextureSwizzle { slot: SlotRef } diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 872bd1491..61c1c45b2 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -33,7 +33,7 @@ Columns: | Devices below the runtime's floor | 8 | 8 | 0 | 0 | 0 | 0 | 0 | | The runtime's `Refusal` | 95 | 95 | 0 | 0 | 0 | 0 | 0 | | The runtime's `Limit` | 21 | 21 | 0 | 0 | 0 | 0 | 0 | -| The runtime's `Gap` | 31 | 31 | 0 | 0 | 0 | 0 | 0 | +| The runtime's `Gap` | 32 | 32 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -46,7 +46,7 @@ Columns: | Devices below the runtime's floor | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | | The runtime's `Refusal` | 30 | 27 | 0 | 0 | 38 | 0 | 0 | 0 | | The runtime's `Limit` | 0 | 0 | 0 | 15 | 6 | 0 | 0 | 0 | -| The runtime's `Gap` | 0 | 0 | 0 | 2 | 29 | 0 | 0 | 0 | +| The runtime's `Gap` | 0 | 0 | 0 | 2 | 30 | 0 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -378,6 +378,7 @@ Columns: | `RenderPipeline` | A render pipeline state of something the runtime does not build yet | every device (a public call's own check of its arguments) | `ours`: the replay streams' render pipelines draw into colour, depth and stencil attachments of one sample, with no tessellation and no framebuffer fetch; each other kind is built when a replay stream makes one | 5: `crates/metal2vulkan-runtime/src/render.rs (draw_input)`, `crates/metal2vulkan-runtime/src/render.rs (of)` (+2) | `-` | | `SwizzledReadWrite` | A draw or dispatch whose function declares `access::read_write` at texture slot `slot` and reads it, where the texture bound there has a swizzle... | every device (a public call's own check of its arguments) | `ours`: built when a replay stream counts one | 2: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` | `-` | | `OpenClLineTexture` | A dispatch of a kernel of OpenCL mode (`ComputePipelineDescriptor::open_cl_mode_enabled`) whose texture slot `slot` is bound to a 1D or 1D array... | every device (a public call's own check of its arguments) | `ours`: no reading of it is documented Metal | 1: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)` | `-` | +| `TexelBufferOwnView` | A draw or dispatch whose function reaches a texture buffer held as words by an access the words do not build, which takes the texture's own view alone | every device (a public call's own check of its arguments) | `ours`: the words build a texel's read, its write and the width; a read through a sampler's address mode is the next | 4: `crates/metal2vulkan-runtime/src/pipeline.rs (own_view_gap, 2 sites)`, `crates/metal2vulkan-runtime/src/render.rs (own_view_gap, 2 sites)` | `-` | | `StorageElement` | A draw or dispatch whose function writes a texture slot, or reads one through its storage image (`access::read_write`), bound to a texture made... | every device (a public call's own check of its arguments) | `ours`: the storage element through a view of the nearest format whose storage Vulkan requires of every device, with the translator's conversion, is the form to build | 4: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch, 2 sites)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (find, 2 sites)` | `-` | | `BicubicTexels` | A dispatch or a draw whose function samples texture slot `slot` through a constexpr sampler with Metal's bicubic filter (`filter::bicubic`), where... | every device (a public call's own check of its arguments) | `ours`: each refused format's treatment is built when a guest binds one | 2: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`, `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` | `-` | | `TextureView` | `Texture::new_texture_view` of a kind Metal makes and the runtime does not build | every device (a public call's own check of its arguments) | `ours`: the replay streams' views that compute binds are same-format views of every slice, 2D views of one slice of a 2D array, and level subranges, swizzled or not; each other kind is built when a replay stream binds one | 1: `crates/metal2vulkan-runtime/src/texture.rs (view)` | `-` | @@ -675,6 +676,7 @@ Each refusal's sites, with the function that builds it. - `rt:Gap::RenderPipeline`: `crates/metal2vulkan-runtime/src/render.rs (draw_input)`; `crates/metal2vulkan-runtime/src/render.rs (of)`; `crates/metal2vulkan-runtime/src/render.rs (refuse)`; `crates/metal2vulkan-runtime/src/render.rs (stage_module, 2 sites)` - `rt:Gap::SwizzledReadWrite`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` - `rt:Gap::OpenClLineTexture`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)` +- `rt:Gap::TexelBufferOwnView`: `crates/metal2vulkan-runtime/src/pipeline.rs (own_view_gap, 2 sites)`; `crates/metal2vulkan-runtime/src/render.rs (own_view_gap, 2 sites)` - `rt:Gap::StorageElement`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch, 2 sites)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (find, 2 sites)` - `rt:Gap::BicubicTexels`: `crates/metal2vulkan-runtime/src/encoder.rs (dispatch)`; `crates/metal2vulkan-runtime/src/render_encoder.rs (find)` - `rt:Gap::TextureView`: `crates/metal2vulkan-runtime/src/texture.rs (view)`