From 7cdaa1cc3fd66cfa0fed265290fc68f124b38c91 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 15:29:18 -0800 Subject: [PATCH] Texture buffers: each device holds a format as words only where it lacks the format's own view for an access metal::format::texel_buffer_form is the one place that decides, per format and device: the format's own view where the device holds it directly as a uniform texel buffer, a storage texel buffer and a storage texel buffer written without a format; else words where it has a word layout; else its own view of the first two (whose writes the runtime refuses). The resource ID word is unchanged and the same on every device; a module takes the codes its profile holds as words (texel_buffer_word_codes) and tests a word's code against them, emitting nothing of the words where the profile holds none so. The routines' cases and the precision notes follow those codes. The runtime's texel_form takes the same answer. AGENTS.md rule 2 gains the fourteenth form; the runtime's README records the words' cost (7.3x the own view's GPU time for an R8Unorm texture buffer written on an RTX 3090, job m3-max-80580). This commit alone was not built; the series is checked at its tip. --- AGENTS.md | 10 +- crates/metal2vulkan-runtime/README.md | 44 ++++-- .../src/tests/texture_buffer_words.rs | 34 +++-- crates/metal2vulkan-runtime/src/texture.rs | 64 ++++---- .../metal2vulkan/src/lower/texture/words.rs | 111 ++++++++++---- crates/metal2vulkan/src/metal/format/mod.rs | 5 +- .../src/metal/format/texel_words.rs | 139 ++++++++++++++++-- crates/metal2vulkan/src/pipeline/artifact.rs | 16 +- docs/API.md | 16 +- docs/RESOURCE-ID.md | 30 ++-- 10 files changed, 336 insertions(+), 133 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7223ed3cf..ab75c28ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,7 +58,7 @@ order, and a lower one never overrides a higher one. limit and memory-type queries. Product code holds no vendor, device or driver ID, and no runtime policy switch. A test enforces this for `metal2vulkan-runtime`. One form means one form per Vulkan capability: where the floor cannot require a feature, that feature's query may choose a - second form, for thirteen only: 16-bit floats, storage-image reads without a format, 64-bit + second form, for fourteen only: 16-bit floats, storage-image reads without a format, 64-bit atomics, 64-bit floats, SIMD groups (the subgroup size range with its stages and operations, and maximal reconvergence), unified memory (decided by Vulkan's physical device type alone: one copy of a Managed buffer on an integrated or CPU @@ -95,7 +95,13 @@ order, and a lower one never overrides a higher one. not one (another colour, a depth or stencil, a resolve) renders it through an optimal image of the runtime's with a counted copy into the plane at the pass's end and, where its load action is Load, a counted copy in at its begin; those copies and that image's memory are recorded as a - known gap), and Shared memory's host coherence (decided by the host-coherent flag of the memory type + known gap), texture buffer formats (ruled 12-02; for each format, does the device serve it + natively for every access a texture buffer makes, as a uniform texel buffer, as a storage texel + buffer, and as a storage write without a format? A device that does makes a texture buffer of + it the format's own view; where any of the three is missing, that format's texture buffer is + held as words, an `R32_UINT` view whose texels shaders convert, one answer per format per + device; the words' cost, 7.3 times the own view's GPU time for an `R8Unorm` texture buffer + written on an RTX 3090, is recorded as a known gap), and Shared memory's host coherence (decided by the host-coherent flag of the memory type Shared takes, the first host-visible, host-cached type a buffer can use, a host-coherent one first: a device whose type has it makes no flush or invalidate call; on a device whose type is the cached type without coherence, the Shared memory a submission's command buffers and Managed diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 7ba30999f..88abc175f 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -1993,16 +1993,20 @@ made, with no lock, and never rewritten for layouts. the multiple of 256 every buffer starts at. Metal documents the alignment for the row's bytes too; a texture buffer's one row reads no other, so any `bytes_per_row` that covers the row is taken (`Refusal::BufferTextureLayout` below it, or for texels past the buffer). The view is of a - buffer of both usages, so its format takes both. A colour format whose Vulkan format Vulkan - requires as a storage texel buffer (and with it a uniform one) is the view's own format. Any - other colour format with a word layout, 39 of them (docs/RESOURCE-ID.md, the texture buffer - word), is held as words on every device: the view is of `R32_UINT` over the same bytes, its last - word ending inside the buffer's block past the last texel, and shaders convert each texel - themselves; a texel of one or two bytes shares its word with its neighbours, and a write of it - is an atomic AND that clears its bits and an atomic OR that sets them, which keep the - neighbours' bits. Any other format is one the device holds directly, of one colour texel an - element, whose buffer features hold both texel buffers (`Gap::TextureFormat` otherwise). A - width whose view's elements pass `maxTexelBufferElements` is `Limit::TextureSize`. Its view is + buffer of both usages, so its format takes both. One answer per format per device decides its + form (`metal::format::texel_buffer_form`): where the device holds the format directly, of one + colour texel an element, as a uniform texel buffer, a storage texel buffer and a storage texel + buffer written without a format, the view is of the format's own Vulkan format. Where it lacks + any of the three and the format has a word layout, 39 formats (docs/RESOURCE-ID.md, the texture + buffer word), the texture buffer is held as words: the view is of `R32_UINT` over the same + bytes, its last word ending inside the buffer's block past the last texel, and shaders convert + each texel themselves; a texel of one or two bytes shares its word with its neighbours, and a + write of it is an atomic AND that clears its bits and an atomic OR that sets them, which keep + the neighbours' bits. A format without a word layout (those Vulkan requires as a storage texel + buffer) is its own view where the device holds it for the first two, and `Gap::TextureFormat` + otherwise. The resource ID's word is the same on every device either way: it carries the + format's code wherever the format has a word layout, and the shader holds the device's answer. + A width whose view's elements pass `maxTexelBufferElements` is `Limit::TextureSize`. Its view is the element of the uniform texel-buffer array at its index where shaders read it, and of the storage one where they write it (the known gaps say where a write or a read through it without a format is refused). Its texels are the @@ -2258,6 +2262,13 @@ made, with no lock, and never rewritten for layouts. `RGB10A2` and `BGR10A2`, it holds no word layout, and refuses each as `Gap::TextureFormat` where the device does not hold the format directly as both texel buffers. Its refusal of a compressed or a depth or stencil texture buffer matches Metal, which ends the process for one. +- A texture buffer held as words costs a shader more than the format's own view: each access + converts its texel in an out-of-line routine, and a write of a texel of one or two bytes is + two device-scope atomics on its word. An `R8Unorm` texture buffer of 2^24 texels written one + texel a thread took 7.3 times the GPU time of the format's own view on an RTX 3090 (p50 658 us + against 90.3 us; harness row `texel_buffer_r8_write`, job m3-max-80580). A device holds a format + so only where it lacks the format's own view for one of a texture buffer's accesses; + `metal::format::texel_buffer_form` says which formats a device's profile holds so. - `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 @@ -2346,11 +2357,14 @@ made, with no lock, and never rewritten for layouts. writes the texture buffer's storage element without a format, outside Vulkan's valid usage (`VUID-vkCmdDispatch-OpTypeImage-07029`), as such a read is (`-07030`), and Vulkan does not define what it does. The UHD Graphics 630's Windows - driver (101.2145) answers neither bit for any format: there a texture buffer a function writes - or reads through `access::read_write` is refused, but at a slot a texture atomic updates and one - held as words, and one it reads through `access::read` runs. No second form is built for it; that changes on a - second device above the floor whose formats lack those buffer features, or on a guest's walk - that meets the refusal on any device. + driver (101.2145) answers neither bit for any format: there it holds every format with a word + layout as words, and a texture buffer of a format without one (those Vulkan requires as a + storage texel buffer) that a function writes or reads through `access::read_write` is refused, + but at a slot a texture atomic updates, and one it reads through `access::read` runs. A device + that holds a format with a word layout as its own view, which takes the write bit, and lacks + the read bit refuses a read of it through `access::read_write` alike. No further form is built + for these; that changes on a second device above the floor whose formats lack those buffer + features, or on a guest's walk that meets the refusal on any device. - An upload into a 32-bit float depth (`Depth32Float`, or the depth of `Depth32Float_Stencil8`) by `replace_region`, `upload_region` or a blit's `copy_from_buffer` is the device's copy into the depth aspect, on every device, under the static note `PrecisionNote::RestrictedDepthUpload` diff --git a/crates/metal2vulkan-runtime/src/tests/texture_buffer_words.rs b/crates/metal2vulkan-runtime/src/tests/texture_buffer_words.rs index c502f0a09..85713a83c 100644 --- a/crates/metal2vulkan-runtime/src/tests/texture_buffer_words.rs +++ b/crates/metal2vulkan-runtime/src/tests/texture_buffer_words.rs @@ -1,8 +1,9 @@ -//! Texture buffers of the formats the runtime holds as words, under a device cfg on every device -//! of the cfg's kind: `A8Unorm`, the four 8-bit sRGB formats, `RGB9E5Float`, the four packed -//! 16-bit formats, `BGR10A2Unorm` and the four extended-range formats. Metal makes a texture -//! buffer of each, for reading, writing and both (an Apple M3 Max under macOS 27.0.1, jobs -//! m3-max-79872 and m3-max-79879). +//! Texture buffers of formats a device may hold as words, under a device cfg on every device of +//! the cfg's kind: `A8Unorm`, the four 8-bit sRGB formats, `RGB9E5Float`, the four packed 16-bit +//! formats, `BGR10A2Unorm` and the four extended-range formats. Metal makes a texture buffer of +//! each, for reading, writing and both (an Apple M3 Max under macOS 27.0.1, jobs m3-max-79872 and +//! m3-max-79879). Each device holds each as words or as its own view +//! (`metal::format::texel_buffer_form`), which each format's line names. //! //! The owned fixture `tb_word_formats` reads, writes, and reads then writes (`access::read_write`) //! texture buffers of five texels, one format at a time, with eight threads: thread `t` reads @@ -30,6 +31,7 @@ mod on_device { FunctionDescriptor, IndexClass, Library, MemoryClass, PixelFormat, StageSource, Texture, TextureDescriptor, TextureType, TextureUsage, }; + use metal2vulkan::metal::format as formats; use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; /// The texels of each texture buffer. @@ -418,8 +420,8 @@ mod on_device { /// The `f32` lanes of a Shared buffer, as the host reads them. fn floats(buffer: &Buffer) -> Vec { - (bytes(buffer).chunks_exact(4)) - .map(|c| f32::from_le_bytes(c.try_into().expect("four bytes"))) + (bytes(buffer).as_chunks::<4>().0.iter()) + .map(|&c| f32::from_le_bytes(c)) .collect() } @@ -576,8 +578,8 @@ mod on_device { } } let widths = bytes(&widths); - let widths: Vec = (widths.chunks_exact(4).take(3)) - .map(|c| u32::from_le_bytes(c.try_into().expect("four bytes"))) + let widths: Vec = (widths.as_chunks::<4>().0.iter().take(3)) + .map(|&c| u32::from_le_bytes(c)) .collect(); if widths != [5, 5, 5] { wrong.push(format!("widths {widths:?}")); @@ -585,8 +587,8 @@ mod on_device { wrong } - /// Every format the runtime holds as words, read, written, and read then written as a - /// texture buffer, answers what the CPU decodes of its bytes. + /// Every format a device may hold as words, read, written, and read then written as a + /// texture buffer, answers what the CPU decodes of its bytes, in the form the device holds it. #[test] fn every_device_reads_and_writes_texture_buffers_of_formats_held_as_words() { let name = "tb_word_formats.ll"; @@ -602,13 +604,19 @@ mod on_device { let _grant = (device.grant_indices(IndexClass::Texture, 1, 3)) .unwrap_or_else(|error| panic!("{name}: {error}")); let mut failed = Vec::new(); + let profile = device.translator().profile(); for case in cases() { + let form = match formats::texel_buffer_form(case.format, profile) { + Some(formats::TexelBufferForm::Words(_)) => "words", + Some(formats::TexelBufferForm::View(_)) => "own view", + None => "refused", + }; let wrong = run(&device, &library, &case); match wrong.is_empty() { - true => println!("{name}: {:?}: every answer the CPU's", case.format), + true => println!("{name}: {:?} ({form}): every answer the CPU's", case.format), false => { for w in &wrong { - println!("{name}: {:?}: {w}", case.format); + println!("{name}: {:?} ({form}): {w}", case.format); } failed.push(case.format); } diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index e15d30af7..e5a23a08c 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -7087,54 +7087,44 @@ struct TexelForm { reads: bool, } -/// What a texture buffer of `pf` holds on the device of `core`. A colour format Vulkan does not -/// require as a storage texel buffer is held as words on every device -/// (`metal::format::texel_buffer_words`): its view is `R32_UINT`, which Vulkan requires as both -/// texel buffers, and shaders convert its texels; its storage element is declared with that -/// format, so neither its writes nor its reads ask a format's bits for a storage texel buffer -/// without a format. Any other is a format the device -/// holds directly, of one color texel an element, whose buffer features hold both the uniform and -/// the storage texel buffer, as its one view is of a buffer of both usages and its format takes -/// both (`VUID-VkBufferViewCreateInfo-format-08778`, `-08779`). +/// What a texture buffer of `pf` holds on the device of `core`, as +/// `metal::format::texel_buffer_form` decides for the device: the format's own view, of one color +/// texel an element, which the device holds directly as a uniform texel buffer, a storage texel +/// buffer and a storage texel buffer written without a format, as its one view is of a buffer of +/// both usages and its format takes both (`VUID-VkBufferViewCreateInfo-format-08778`, `-08779`); +/// else words, a view of `R32_UINT`, which Vulkan requires as both texel buffers, whose texels +/// shaders convert, and whose storage element is declared with that format, so neither its writes +/// nor its reads ask a format's bits for a storage texel buffer without a format; else, for a +/// format with no word layout, its own view of the two texel buffers alone, whose write without a +/// format a dispatch then refuses ([`TexelForm`]'s `writes`). /// -/// Err: [`Gap::TextureFormat`] for any other. +/// Err: [`Gap::TextureFormat`] for any other format. fn texel_form(core: &Core, pf: PixelFormat) -> Result { let gap = || Error::Unsupported(Gap::TextureFormat { pixel_format: pf }); TextureWord::of(pf, TextureSwizzleChannels::DEFAULT).ok_or_else(gap)?; - if let Some(words) = formats::texel_buffer_words(pf) { - return Ok(TexelForm { + let profile = core.translator.profile(); + match formats::texel_buffer_form(pf, profile).ok_or_else(gap)? { + formats::TexelBufferForm::Words(words) => Ok(TexelForm { format: words.element_format().into(), bytes: words.bytes, element: words.element_bytes(), words: Some(words), writes: true, reads: true, - }); + }), + formats::TexelBufferForm::View(format) => { + let block = format.block().ok_or_else(gap)?; + let supports = |use_| profile.supports_format(format, use_); + Ok(TexelForm { + format: format.into(), + bytes: block.size, + element: block.size, + words: None, + writes: supports(FormatUsage::StorageTexelBufferWriteWithoutFormat), + reads: supports(FormatUsage::StorageTexelBufferReadWithoutFormat), + }) + } } - let profile = core.translator.profile(); - let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - let mapping = - formats::vk_format(pf, &formats::texture_usages(pf, usage), profile).map_err(|_| gap())?; - let block = mapping.format.block().ok_or_else(gap)?; - let format: vk::Format = mapping.format.into(); - let supports = |use_| profile.supports_format(mapping.format, use_); - let color = block.depth.is_none() && block.stencil.is_none(); - if mapping.emulation != FormatEmulation::Direct - || !color - || formats::block_extent(pf).is_some() - || !supports(FormatUsage::UniformTexelBuffer) - || !supports(FormatUsage::StorageTexelBuffer) - { - return Err(gap()); - } - Ok(TexelForm { - format, - bytes: block.size, - element: block.size, - words: None, - writes: supports(FormatUsage::StorageTexelBufferWriteWithoutFormat), - reads: supports(FormatUsage::StorageTexelBufferReadWithoutFormat), - }) } /// The usage a texture buffer of `d` takes, where `d` is Metal's texture buffer: a width of texels diff --git a/crates/metal2vulkan/src/lower/texture/words.rs b/crates/metal2vulkan/src/lower/texture/words.rs index 3f301230c..18d8fd614 100644 --- a/crates/metal2vulkan/src/lower/texture/words.rs +++ b/crates/metal2vulkan/src/lower/texture/words.rs @@ -1,14 +1,17 @@ -//! Texture buffers held as words (`metal::format::texel_buffer_words`). +//! Texture buffers held as words (`metal::format::texel_buffer_form`). //! -//! Under the identity domains a texture buffer of a colour format whose Vulkan format Vulkan does -//! not require as a storage texel buffer is a view of its bytes as `R32_UINT` on every device, and -//! its resource ID's word says so: its format's code, its texels per word, whether a texel is two -//! words, and the texels its last word holds past its width -//! (`resource_word::TextureWord::of_texture_buffer`). A texture-buffer slot's read, write and width -//! query test the code ([`Words`]): where it is 0 the access is the texture's own view's, as it is -//! for every other texture buffer; elsewhere a read or write calls one of the module's routines -//! ([`Routine`]), defined once and kept out of line (`DontInline`), which takes the texel's word -//! from the view's element and converts it by the code. The width is the view's words times the +//! Under the identity domains a texture buffer of a colour format the device does not hold +//! directly for every access a texture buffer makes is a view of its bytes as `R32_UINT`. Its +//! resource ID's word carries, on every device, its format's code wherever the format has a word +//! layout, its texels per word, whether a texel is two words, and the texels its last word holds +//! past its width (`resource_word::TextureWord::of_texture_buffer`); the module takes the codes its +//! device holds as words from its profile (`metal::format::texel_buffer_word_codes`), and declares +//! nothing of this where there are none. A texture-buffer slot's read, write and width query test +//! the code against those ([`Words`]): where the device does not hold it as words the access is the +//! texture's own view's, as it is for every other texture buffer; elsewhere a read or write calls +//! one of the module's routines ([`Routine`]), defined once and kept out of line (`DontInline`), +//! which takes the texel's word from the view's element and converts it by the code, its cases +//! the profile's codes alone. The width is the view's words times the //! texels per word, halved where a texel is two words, less the padding. The routine tests the //! texel against that width itself: a read outside it is Metal's out-of-bounds texel (zero, alpha //! 1 for a format without alpha, bit 12 of the word), a write outside it is dropped, as Metal @@ -49,7 +52,8 @@ use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; use crate::memory::leaf::Coherence; use crate::metal::format::{ - texel_words, ExtendedRange, FieldKind, TexelField, WordLayout, WORD_FORMATS, + texel_buffer_word_codes, texel_words, ExtendedRange, FieldKind, TexelField, TexelWords, + WordLayout, WORD_FORMATS, }; use crate::metal::resource_word::TextureWord; use crate::pipeline::artifact::PrecisionNote; @@ -105,6 +109,17 @@ pub struct WordsPlan { /// An access is of an argument buffer's texture buffer, whose handle then carries its word's /// low bits ([`HANDLE_WORD`]). pub heap: bool, + /// The codes the profile holds as words: bit `c` for code `c` + /// (`metal::format::texel_buffer_word_codes`). + pub codes: u64, +} + +/// The formats of `codes` ([`WordsPlan::codes`]) with their word layouts. +fn held(codes: u64) -> impl Iterator { + WORD_FORMATS + .iter() + .filter_map(|&pf| texel_words(pf)) + .filter(move |w| codes >> w.code & 1 == 1) } /// Under the identity domains, where a function reaches an argument buffer's texture buffer held as @@ -177,6 +192,10 @@ pub(super) fn wrap( if !crate::lower::access::identity(cx.profile) || dim != ImageDim::Buffer { return Ok(s); } + let codes = texel_buffer_word_codes(cx.profile); + if codes == 0 { + return Ok(s); + } let (storage, _) = super::image_access(cx, image)?; let nonuniform = image.heap(); let class = class.filter(|c| *c != TexelClass::Uint64); @@ -213,6 +232,14 @@ pub(super) fn wrap( false => plan.uniform = true, } plan.heap |= nonuniform; + plan.codes = codes; + // The conversions the routine's cases take: an 8-bit sRGB colour's and an extended-range + // texel's are the device's. + let srgb = held(codes).any(|w| match w.layout { + WordLayout::Fields { fields, .. } => fields.iter().flatten().any(|f| f.srgb), + _ => false, + }); + let extended = held(codes).any(|w| matches!(w.layout, WordLayout::Extended(_))); if let Some(r) = routine { plan.routines.insert(r); match r { @@ -220,13 +247,17 @@ pub(super) fn wrap( class: TexelClass::Float, .. } => { - cx.precision.insert(PrecisionNote::SrgbTexelDecode); - cx.precision.insert(PrecisionNote::DevicePackConversion); + if srgb { + cx.precision.insert(PrecisionNote::SrgbTexelDecode); + } + if extended { + cx.precision.insert(PrecisionNote::DevicePackConversion); + } } Routine::Write { class, .. } => { // A texel of one or two bytes is written by two device-scope atomics. crate::lower::sync::memory_model::note_device_scope(cx); - if class == TexelClass::Float { + if class == TexelClass::Float && (srgb || extended) { cx.precision.insert(PrecisionNote::DevicePackConversion); } } @@ -319,7 +350,7 @@ pub(super) fn declare( storage, nonuniform, }; - define_read(mb, class, array, (coherence, volatile))? + define_read(mb, (class, plan.codes), array, (coherence, volatile))? } Routine::Write { class, nonuniform } => { let Some(g) = d.storage else { continue }; @@ -328,7 +359,7 @@ pub(super) fn declare( storage: true, nonuniform, }; - define_write(mb, class, array, (coherence, volatile))? + define_write(mb, (class, plan.codes), array, (coherence, volatile))? } }; d.routines.insert(r, f); @@ -366,10 +397,7 @@ pub(super) fn emit( w: &Words, ) -> BResult> { let (element, word) = element_word(cx, fb, w.image)?; - let field = ku(fb, TextureWord::TEXEL_BUFFER_WORDS)?; - let code = fb.binary(BinOp::BitwiseAnd, word, field)?; - let zero = ku(fb, 0)?; - let held = fb.binary(BinOp::INotEqual, code, zero)?; + let held = held_test(fb, word, cx.decl.families.texture.words.codes)?; let routine = match w.routine { Some(r) => match cx.decl.families.texture.words.routines.get(&r) { Some(f) => Some(*f), @@ -446,6 +474,34 @@ pub(super) fn emit( Ok(m.first().copied()) } +/// Whether word `word` (`u32`) names a format of `codes` ([`WordsPlan::codes`]): where `codes` are +/// every format's, whether its code is not 0; else the code's bit of `codes`. +fn held_test(fb: &mut FunctionBuilder<'_>, word: SValue, codes: u64) -> BResult { + let every = held(u64::MAX).fold(0u64, |all, w| all | 1 << w.code); + let zero = ku(fb, 0)?; + if codes == every { + let field = ku(fb, TextureWord::TEXEL_BUFFER_WORDS)?; + let code = fb.binary(BinOp::BitwiseAnd, word, field)?; + return fb.binary(BinOp::INotEqual, code, zero); + } + // The code's bit: of the low half of `codes` below 32, of the high half from 32. + let shift = ku(fb, TextureWord::TEXEL_BUFFER_CODE_SHIFT)?; + let code = fb.binary(BinOp::ShiftRightLogical, word, shift)?; + let field = ku(fb, 63)?; + let code = fb.binary(BinOp::BitwiseAnd, code, field)?; + let thirty_two = ku(fb, 32)?; + let low = fb.binary(BinOp::ULessThan, code, thirty_two)?; + let lo = ku(fb, codes as u32)?; + let hi = ku(fb, (codes >> 32) as u32)?; + let half = fb.select(low, lo, hi)?; + let place = ku(fb, 31)?; + let at = fb.binary(BinOp::BitwiseAnd, code, place)?; + let bit = fb.binary(BinOp::ShiftRightLogical, half, at)?; + let one = ku(fb, 1)?; + let bit = fb.binary(BinOp::BitwiseAnd, bit, one)?; + fb.binary(BinOp::INotEqual, bit, zero) +} + /// The fields of word `word` (`u32`) a routine reads. struct Fields { /// The base-2 logarithm of the texels per word. @@ -527,10 +583,10 @@ fn prologue( }) } -/// Define the read routine of `class` through `array`. +/// Define the read routine of `class` through `array`, a case for each format of `codes`. fn define_read( mb: &mut ModuleBuilder, - class: TexelClass, + (class, codes): (TexelClass, u64), array: Array, (coherence, volatile): (Coherence, bool), ) -> BResult { @@ -577,8 +633,7 @@ fn define_read( let place = fb.binary(BinOp::ShiftLeftLogical, sub, place_log)?; let t = fb.binary(BinOp::ShiftRightLogical, lo, place)?; let mut cases: Vec<(Vec, ArmFn<'_, ()>)> = Vec::new(); - for &pf in &WORD_FORMATS { - let Some(w) = texel_words(pf) else { continue }; + for w in held(codes) { if layout_class(w.layout) != Some(class) { continue; } @@ -613,10 +668,11 @@ fn define_read( fb.finish() } -/// Define the write routine of `class` through storage array `array`. +/// Define the write routine of `class` through storage array `array`, a case for each format of +/// `codes`. fn define_write( mb: &mut ModuleBuilder, - class: TexelClass, + (class, codes): (TexelClass, u64), array: Array, (coherence, volatile): (Coherence, bool), ) -> BResult { @@ -640,8 +696,7 @@ fn define_write( let p = prologue(&mut fb, array, (element, word, x))?; let mem = coherence.texel(&mut fb)?.with_volatile(volatile); let mut cases: Vec<(Vec, ArmFn<'_, ()>)> = Vec::new(); - for &pf in &WORD_FORMATS { - let Some(w) = texel_words(pf) else { continue }; + for w in held(codes) { if layout_class(w.layout) != Some(class) { continue; } diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index d2882f40c..6a75fc918 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -40,9 +40,10 @@ mod texel_words; mod word; pub use footprint::{footprint, Footprint}; pub(crate) use packed_codes::packed_codes; +pub(crate) use texel_words::texel_buffer_word_codes; pub use texel_words::{ - required_storage_texel_buffer, texel_buffer_words, texel_words, word_format, FieldKind, - TexelField, TexelWords, WordLayout, WORD_FORMATS, + required_storage_texel_buffer, texel_buffer_form, texel_buffer_words, texel_words, word_format, + FieldKind, TexelBufferForm, TexelField, TexelWords, WordLayout, WORD_FORMATS, }; pub use word::{WordAttachment, WordField}; diff --git a/crates/metal2vulkan/src/metal/format/texel_words.rs b/crates/metal2vulkan/src/metal/format/texel_words.rs index f1a4c5fd5..9e952ff58 100644 --- a/crates/metal2vulkan/src/metal/format/texel_words.rs +++ b/crates/metal2vulkan/src/metal/format/texel_words.rs @@ -1,14 +1,25 @@ -//! Texture buffers held as words: a texture buffer of a colour format whose Vulkan format Vulkan -//! does not require as a storage texel buffer is a view of its bytes as `R32_UINT`, which shaders -//! read and write by converting each texel themselves. +//! Texture buffers held as words: a texture buffer of a colour format the device does not hold +//! directly for every access a texture buffer makes is a view of its bytes as `R32_UINT`, which +//! shaders read and write by converting each texel themselves. //! //! A texture buffer's view is of a buffer of both texel-buffer usages, and without //! `VK_KHR_maintenance5`, which the floor does not require, a view takes its buffer's usages -//! (`VUID-VkBufferViewCreateInfo-format-08778`, `-08779`), so its format must hold both. Vulkan -//! requires both of few formats (its mandatory format tables: the 8-bit four-channel and the 32-bit -//! formats, and the 16-bit four-channel float and integer ones); [`texel_buffer_words`] is the one -//! place that decides, by the format alone, on every device. `R32_UINT` is among the required -//! ones, and its storage texel buffer atomics are required too. +//! (`VUID-VkBufferViewCreateInfo-format-08778`, `-08779`), so its format must hold both; a shader +//! writes it through a storage texel buffer declared without a format, so its format must take +//! that write too. [`texel_buffer_form`] is the one place that decides, for each format on each +//! device: the format's own view where the device holds it directly as a uniform texel buffer, a +//! storage texel buffer and a storage texel buffer written without a format, else words where the +//! format has a word layout ([`texel_buffer_words`]), else its own view of the first two, whose +//! writes the runtime refuses. Vulkan requires the first two of few formats +//! (its mandatory format tables: the 8-bit four-channel and the 32-bit formats, and the 16-bit +//! four-channel float and integer ones, [`required_storage_texel_buffer`]), which have no word +//! layout. `R32_UINT` is among them, and its storage texel buffer atomics are required too; a word +//! view's storage element is declared `R32ui`, so its writes ask no format's bit. +//! +//! A texture buffer's resource ID word carries its format's code wherever the format has a word +//! layout, on every device, so a program's IDs are the same on every device; a module takes the +//! codes its device holds as words from the profile it is compiled for +//! ([`texel_buffer_word_codes`]), and reaches the format's own view for any other. //! //! The view's elements are words: a texel of one or two bytes shares its word with its //! neighbours, read by shifting it out and written by an atomic AND that clears its bits and an @@ -20,7 +31,11 @@ //! is two words: its width is the view's words times its texels per word, halved where a texel is //! two words, less `p`. -use crate::metal::format::ExtendedRange; +use std::collections::BTreeSet; + +use crate::device::requirements::FormatUsage; +use crate::device::DeviceProfile; +use crate::metal::format::{ExtendedRange, FormatEmulation}; use crate::metal::PixelFormat; use crate::vk; @@ -157,8 +172,10 @@ pub fn required_storage_texel_buffer(f: vk::Format) -> bool { /// How a texture buffer of `pf` holds its texels where it holds them as words: `Some` where `pf` /// is a colour format whose direct Vulkan format Vulkan does not require as a storage texel buffer /// ([`required_storage_texel_buffer`]), or which has none, and whose texels the word routines -/// convert; `None` where the format's own view holds them (a format Vulkan requires), and for a -/// format no texture buffer holds. The same on every device. +/// convert; `None` where the format's own view holds them on every device (a format Vulkan +/// requires), and for a format no texture buffer holds. The same on every device: the resource ID +/// word carries its code (`resource_word::TextureWord::of_texture_buffer`), and +/// [`texel_buffer_form`] says whether a device holds it so. pub fn texel_buffer_words(pf: PixelFormat) -> Option { if super::direct_format(pf).is_some_and(required_storage_texel_buffer) && ExtendedRange::of(pf).is_none() @@ -168,6 +185,65 @@ pub fn texel_buffer_words(pf: PixelFormat) -> Option { texel_words(pf) } +/// How a texture buffer holds its texels on a device ([`texel_buffer_form`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum TexelBufferForm { + /// Its view is of the format's own Vulkan format. + View(vk::Format), + /// Its view is of words, whose texels shaders convert. + Words(TexelWords), +} + +/// The Vulkan uses a texture buffer's own view takes: a buffer view of both texel-buffer usages. +const VIEW_USES: [FormatUsage; 2] = [ + FormatUsage::UniformTexelBuffer, + FormatUsage::StorageTexelBuffer, +]; + +/// The further uses a device holds a format for where a texture buffer of a format with a word +/// layout is its own view rather than words: the storage texel buffer's write without a format, +/// with [`VIEW_USES`] every access a texture buffer makes. +const NATIVE_USES: [FormatUsage; 1] = [FormatUsage::StorageTexelBufferWriteWithoutFormat]; + +/// How a texture buffer of `pf` holds its texels on a device of `profile`, the one place that +/// decides it (the module docs). Its own view ([`TexelBufferForm::View`]) where the device holds +/// the format directly (with no component mapping or conversion), of one colour texel an element, +/// for each of [`VIEW_USES`] and [`NATIVE_USES`]; else words ([`TexelBufferForm::Words`]) where the +/// format has a word layout ([`texel_buffer_words`]); else its own view where the device holds it +/// so for [`VIEW_USES`] alone (a format Vulkan requires, on a device that writes none without a +/// format, whose write the runtime then refuses). `None` for any other format, whose texture +/// buffer is refused. +pub fn texel_buffer_form(pf: PixelFormat, profile: &DeviceProfile) -> Option { + let uses: BTreeSet = VIEW_USES.into_iter().collect(); + let own = super::vk_format(pf, &uses, profile).ok().filter(|m| { + m.emulation == FormatEmulation::Direct + && m.aspects == vk::ImageAspectFlags::COLOR + && super::block_extent(pf).is_none() + }); + let native = own.filter(|m| { + NATIVE_USES + .iter() + .all(|&u| profile.supports_format(m.format, u)) + }); + match (native, texel_buffer_words(pf), own) { + (Some(m), _, _) => Some(TexelBufferForm::View(m.format)), + (None, Some(w), _) => Some(TexelBufferForm::Words(w)), + (None, None, own) => own.map(|m| TexelBufferForm::View(m.format)), + } +} + +/// The codes of the formats a device of `profile` holds texture buffers of as words +/// ([`texel_buffer_form`]): bit `c` set for code `c`. +pub(crate) fn texel_buffer_word_codes(profile: &DeviceProfile) -> u64 { + WORD_FORMATS + .iter() + .filter_map(|&pf| match texel_buffer_form(pf, profile)? { + TexelBufferForm::Words(w) => Some(1u64 << w.code), + TexelBufferForm::View(_) => None, + }) + .fold(0, |codes, bit| codes | bit) +} + /// The formats a texture buffer may hold as words, in the order of their codes (1 for the first): /// a resource ID's contract (`docs/RESOURCE-ID.md`), so a format keeps its place. pub const WORD_FORMATS: [PixelFormat; 39] = { @@ -351,6 +427,47 @@ mod tests { } } + /// On every committed profile, a format Vulkan requires as a storage texel buffer is its own + /// view, each format with a word layout is words or its own view, the latter only where the + /// profile holds it directly for every access a texture buffer makes, and the module's codes + /// are the formats held as words. Prints each profile's formats held as words. + #[test] + fn each_profile_holds_each_format_one_way() { + use PixelFormat as P; + let profiles = crate::spirv::testing::committed_profiles().expect("committed profiles"); + assert!(!profiles.is_empty()); + for (stem, profile) in &profiles { + for pf in [P::RGBA8Unorm, P::R32Uint, P::RG32Float, P::RGBA16Float] { + let form = texel_buffer_form(pf, profile); + assert!( + matches!(form, Some(TexelBufferForm::View(_))), + "{stem}: {pf:?}" + ); + } + let mut words = Vec::new(); + let mut codes = 0u64; + for &pf in &WORD_FORMATS { + match texel_buffer_form(pf, profile) { + Some(TexelBufferForm::Words(w)) => { + assert_eq!(Some(w), texel_words(pf), "{stem}: {pf:?}"); + codes |= 1 << w.code; + words.push(format!("{pf:?}")); + } + Some(TexelBufferForm::View(f)) => { + let uses = VIEW_USES.iter().chain(&NATIVE_USES); + assert!( + uses.into_iter().all(|&u| profile.supports_format(f, u)), + "{stem}: {pf:?}" + ); + } + None => panic!("{stem}: {pf:?} has no form"), + } + } + assert_eq!(texel_buffer_word_codes(profile), codes, "{stem}"); + eprintln!("{stem}: held as words: {}", words.join(" ")); + } + } + /// Each layout's fields lie inside its texel and never cross a 32-bit word, so a texel of /// eight bytes reads each field from one of its two words. #[test] diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index f8be67f4e..f9c1e218e 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -901,9 +901,10 @@ pub enum PrecisionNote { /// Metal's table rounds the transfer to a twelve-bit step, up to half a step (`1 / 8190`) from /// it, where MoltenVK's `Pow` read within `1.83e-7` of the transfer through the alias. /// Validation derives no tolerance from it: the class is unbounded. A `float` read of a texture - /// buffer held as words (`metal::format::texel_buffer_words`) decodes an 8-bit sRGB colour - /// code the same way, by the MSL transfer through the device's division and `Pow`, and records - /// the note outright: the routine reads every format the texture buffer's word may name. + /// buffer held as words (`metal::format::texel_buffer_form`) decodes an 8-bit sRGB colour code + /// the same way, by the MSL transfer through the device's division and `Pow`, and records the + /// note where the profile holds an 8-bit sRGB format's texture buffers as words: the routine + /// reads every format the profile holds so. SrgbTexelDecode, /// A vertex or fragment function keeps more private memory (its `alloca`s, a call stack among /// them, or constants held as `Private` variables) than the floor, 16 KiB a thread, on a device @@ -1708,10 +1709,11 @@ pub enum PrecisionNote { /// (`lower::texture::heap_raw`) records it as a specialized note: it holds where a texture /// the stage's handles can name is one (`SpecKey::HeapRawTextures`, which a plan gives), /// unless the stage records it outright for another conversion. A texture buffer held as - /// words (`metal::format::texel_buffer_words`) converts its extended-range texels the same - /// way, and encodes a write's 8-bit sRGB colour by `unorm4x8_srgb`'s pack; its `float` read and - /// write record the note outright, the routine converting every format the texture buffer's - /// word may name. Its other conversions are exact: a normalized code to its correctly rounded + /// words (`metal::format::texel_buffer_form`) converts its extended-range texels the same way, + /// and encodes a write's 8-bit sRGB colour by `unorm4x8_srgb`'s pack; its `float` read and + /// write record the note where the profile holds an extended-range format's texture buffers as + /// words, and its write where it holds an 8-bit sRGB one's so, the routine converting every + /// format the profile holds as words. Its other conversions are exact: a normalized code to its correctly rounded /// quotient, a value to the exact product's code rounded to nearest even, a half or small /// float exactly, and a write's half or small float toward zero, as Metal's kernel writes. /// Validation derives no tolerance from it. diff --git a/docs/API.md b/docs/API.md index fc9028d18..28fe2a2af 100644 --- a/docs/API.md +++ b/docs/API.md @@ -270,8 +270,9 @@ and so do the command line, the compile worker and every validation tool. It hol [RESOURCE-ID.md](RESOURCE-ID.md)), reads, writes and updates atomically its texture buffers, slots and argument buffers' members alike (a uniform texel buffer where it reads one, a storage texel buffer where it writes one, the element of set 1's texel-buffer array at its ID's index; where - the ID's word says the texture buffer is held as words, that element is a view of `R32_UINT` - and the function converts its texels itself: RESOURCE-ID.md, the texture buffer word), and + the ID's word names a format the profile holds as words, `metal::format::texel_buffer_form`, + that element is a view of `R32_UINT` and the function converts its texels itself: + RESOURCE-ID.md, the texture buffer word), and samples its texture slots through its runtime sampler slots and its constexpr samplers and reads them through those (MSL 4.1's `read(sampler, coord)`, its border texel from bits 0-11 of the ID's word). Any other @@ -2064,8 +2065,9 @@ bound. alias (at a slot, or held by an argument buffer), the module decodes the codes (or the device's filter of them) by the MSL transfer through the device's `Pow`, at every such access on every device. A `float` read of a texture buffer held as words decodes an 8-bit sRGB colour code - the same way, and records the note outright: its routine reads every format the texture - buffer's word may name. + the same way, and records the note where the profile holds an 8-bit sRGB format's texture + buffers as words (`metal::format::texel_buffer_form`): its routine reads every format the + profile holds so. - `metal2vulkan-degrade-function-storage-assumed` (precision). `PrecisionNote::FunctionStorageAssumed`: A vertex or fragment function keeps more private memory (its `alloca`s, a call stack among them, or constants held as `Private` variables) than the floor, @@ -2554,8 +2556,10 @@ bound. from the textures the command makes resident or binds), so a reading of the module alone holds it, and so does a command that can name one. A texture buffer held as words converts its extended-range texels the same way, and encodes a write's 8-bit sRGB colour by - `unorm4x8_srgb`'s pack; its `float` read and write record the note outright, the routine - converting every format the texture buffer's word may name. Its other conversions are exact: a + `unorm4x8_srgb`'s pack; its `float` read and write record the note where the profile holds an + extended-range format's texture buffers as words, and its write where it holds an 8-bit sRGB + one's so, the routine converting every format the profile holds as words. Its other + conversions are exact: a normalized code to its correctly rounded quotient, a value to the exact product's code rounded to nearest even, a half or small float exactly, and a write's half or small float toward zero, as Metal's kernel writes. diff --git a/docs/RESOURCE-ID.md b/docs/RESOURCE-ID.md index c83913cbf..e1552bed0 100644 --- a/docs/RESOURCE-ID.md +++ b/docs/RESOURCE-ID.md @@ -91,8 +91,9 @@ A shader takes a texture slot's ID from the slot's push field (`PushField::SlotG argument buffer's texture's ID from the member's 8 bytes, with no table between. It indexes the arrays with the low word, answers `is_null_texture` by whether the index is 0, and, where it checks a `read` itself (a device without `robustImageAccess2`), takes an out-of-bounds -alpha of 1 from bit 12 of the word. A texture buffer held as words takes its format, its texels per -word, whether a texel is two words and its padding from bits 0-10 of its word. A slot's `read` through a sampler (MSL 4.1) takes the border +alpha of 1 from bit 12 of the word. A texture buffer whose word names a format the device holds +as words takes its format, its texels per word, whether a texel is two words and its padding from +bits 0-10 of its word. A slot's `read` through a sampler (MSL 4.1) takes the border texel an index outside the level reads on a border axis from bits 0-11 of the word, for the sampler's border color. The runtime writes a slot's ID, so its index is an element; the program writes an argument buffer's, so the shader masks its index to its low 16 bits: a bad @@ -155,21 +156,26 @@ texture buffer is sampled or read through a sampler: | Bits | Field | |---|---| -| 0-1 | held as words: the texels the view's last word holds past `width`, 0 to 3; otherwise 0 | -| 2-7 | held as words: the format's code, 1 to 39 (below); 0 where the format's own view holds the texels | -| 8-9 | held as words: the base-2 logarithm of the texels one word holds, 0, 1 or 2; otherwise 0 | -| 10 | held as words: a texel is two words, the low word first; otherwise 0 | +| 0-1 | a format with a word layout: the texels the last word holds past `width`, 0 to 3; otherwise 0 | +| 2-7 | a format with a word layout: its code, 1 to 39 (below); otherwise 0 | +| 8-9 | a format with a word layout: the base-2 logarithm of the texels one word holds, 0, 1 or 2; otherwise 0 | +| 10 | a format with a word layout: a texel is two words, the low word first; otherwise 0 | | 11 | 0 | | 12 | the format has no alpha, as in the texture word | | 13-15 | 0 | | 16-31 | the `MTLPixelFormat` raw value | -A texture buffer is held as words where its format is a colour format whose Vulkan format Vulkan -does not require as a storage texel buffer (its mandatory format tables), or that has no Vulkan -format of its own, by the format alone and on every device (`metal::format::texel_buffer_words`). -Its view is then of `R32_UINT`, its texels packed in the buffer's bytes as Metal lays them out: a -texel of `b` bytes, `w` texels wide, views `⌈w · b / 4⌉` words, and its width is the words times -its texels per word, halved where a texel is two words, less its padding. The codes, from 1: +A format has a word layout where it is a colour format whose Vulkan format Vulkan does not +require as a storage texel buffer (its mandatory format tables), or that has no Vulkan format of +its own, and the word carries its fields on every device (`metal::format::texel_buffer_words`), +so the word is the same on every device. A device holds a texture buffer of such a format as words +where it lacks the format's own Vulkan format, held directly, as a uniform texel buffer, a storage +texel buffer or a storage texel buffer written without a format (`metal::format::texel_buffer_form`); +a module holds that answer for the profile it is compiled for. The view is then of `R32_UINT`, its +texels packed in the buffer's bytes as Metal lays them out: a texel of `b` bytes, `w` texels wide, +views `⌈w · b / 4⌉` words, and its width is the words times its texels per word, halved where a +texel is two words, less its padding. Elsewhere the view is of the format's own Vulkan format, +`w` texels, and the shader reads its width from it. The codes, from 1: `A8Unorm`, `R8Unorm`, `R8Unorm_sRGB`, `R8Snorm`, `R8Uint`, `R8Sint`, `R16Unorm`, `R16Snorm`, `R16Uint`, `R16Sint`, `R16Float`, `RG8Unorm`, `RG8Unorm_sRGB`, `RG8Snorm`, `RG8Uint`, `RG8Sint`, `B5G6R5Unorm`, `A1BGR5Unorm`, `ABGR4Unorm`, `BGR5A1Unorm`, `RG16Unorm`, `RG16Snorm`, `RG16Uint`,