SEMANTICS 2114 / RUNTIME 2307: write() through an argument buffer to a two-plane YCbCr texture stores or drops as the slot write does

An argument buffer's texture2d<float|half, write> of a two-plane YCbCr
texture died at dispatch (its storage heap member was refused). Metal
stores through a handle exactly what it stores through a slot (the M3
Max under macOS 27.0.1, measured by the consumer): nothing of
YCBCR8_420_2P, both planes of the unpacked 4:4:4 formats byte for byte
the slot's.

- bind::heap: a storage class holds a texture whose writes Metal drops
  (metal::format::writes_dropped) as its neutral (Fit::Dropped), and a
  4:4:4 texture whose writes Metal stores (ycbcr_writes_stored) through
  the R32G32B32A32_SFLOAT view of its write shadow; its table entry
  carries FLAG_YCBCR_WRITES (bit 15). A stage that reads the storage
  class (new RuntimeFact::HeapStorageReads, a PlanTimeCheck) refuses
  either texture it reaches there, Format / NotImplemented, as a slot
  that reads one is refused.
- memory::handles: the search carries the flag into handle bit 29
  (HANDLE_YCBCR_WRITES) under the stage's new SpecKey::HeapYCbCrWrites,
  a u32 constant the plan gives from the command's members (1 where a
  member it names is such a texture, usage writing). At 0 the carry
  mask, the element mask and the write's test are spec-constant
  folds, so a command naming no such texture runs the pipeline it ran
  before (the predicted bindings name none).
- lower::texture: a float/half 4-lane 2D heap write selects
  (rgb, 1.0) where the handle carries the flag: the mark the write-back
  kernel reads (nonzero), in place of any member conversion.
- runtime: the write shadow's image is MUTABLE_FORMAT with an
  R32G32B32A32_SFLOAT view where the device stores that format; the
  heap's float storage element is that view; a command making such a
  texture resident for writing names the shadow in its uses (its copies
  clear the marks and encode the marked texels into the planes), and
  the texture's own image only where it reads it too.

Tests: src/tests/engine_heap_ycbcr_writes.rs (interpreter run at the
constant's 0 and 1, plan values and one variant for every command
naming no shadowed texture, the storage-read refusal);
runtime_lane::ycbcr_argument_writes (500/503/507/523/527/542/545
through an argument buffer against the slot's bytes, and the pipeline
count). REFUSALS.md regenerated; api_signatures blessed: two new
variants of #[non_exhaustive] enums, nothing breaks for a consumer.

Metal (M3 Max, macOS 27.0.1, m3-max-29643): argument-buffer writes are byte-identical to slot writes
for 500/503/507/523/527.

Verified (msi lavapipe, --cfg m2v_cpu_icd): m3-max-29859 clippy translator/runtime/validation 0,
runtime 243/243, lavapipe lanes 75/75, translator 246/247 (a word bound the mark raised, fixed in
ce01da189e); m3-max-29865 at ce01da189e clippy 0, translator 4/4, lavapipe 2/2: argument-buffer
writes byte-equal to slot writes for all 7 formats (alpha-0 writes, so an unmarked write stores
nothing); pipelines 1 after RGBA8/RGBA16Float/500 commands, 2 after the first 503 and still 2
after a second.
This commit is contained in:
Anees Iqbal committed 2026-11-14 10:46:27 -08:00
1 parent 15fc7f62a5
commit 2960070096
31 files changed
+1475 -108

No files matched your search

+41 -2
View File
@@ -79,7 +79,9 @@ use metal2vulkan::bind::{
SamplerSource, UseTarget, ViewSetup, WriteSource,
};
use metal2vulkan::metal::sampler::{AddressModeMap, OpaqueBlackBorder, SamplerUse};
use metal2vulkan::pipeline::{HandleClass, SlotClass, SlotRef, Stage, StorageAttachmentView};
use metal2vulkan::pipeline::{
HandleClass, ImageAccess, SlotClass, SlotRef, Stage, StorageAttachmentView,
};
use std::collections::BTreeSet;
use std::ops::{Deref, Range};
use std::sync::atomic::Ordering;
@@ -3152,10 +3154,31 @@ fn resident_uses_into(
Some(Used::IndirectCommandBuffer(icb)) => icb.storage(),
Some(Used::Texture(texture)) => {
let (read, write) = image_access(resource.class)?;
let used = texture.bound_use(
let (read, write) = (
access(read, resource.access.read),
access(write, resource.access.write),
);
// A 4:4:4 two-plane YCbCr texture a heap's float storage array holds through its
// write shadow (`bind::heap`), written: the shadow, whose copies clear its marks
// and encode the marked texels into the planes, and the texture's own image where
// the command reads it too.
let shadowed = resource.class == AccessClass::StorageImage
&& resource.access.write
&& texture.takes_ycbcr_writes(true)
&& holds_write_shadow(plan, token);
if shadowed {
let used = texture.ycbcr_write_use("useResource:usage:", write)?;
named.insert(used.key);
uses.push(used);
sources.push(at as u32);
if read.is_empty() {
continue;
}
}
let used = match shadowed {
true => texture.bound_use(read, Access::NONE),
false => texture.bound_use(read, write),
};
named.insert(used.key);
uses.push(used);
sources.push(at as u32);
@@ -3182,6 +3205,22 @@ fn resident_uses_into(
Ok(())
}
/// Whether `plan` holds the texture it makes resident as token `token` in a storage heap array
/// (a `WriteSource::HeapEntry` of a storage class): for a 4:4:4 two-plane YCbCr texture, its write
/// shadow's view (`bind::heap`), which a stage of the plan writes.
fn holds_write_shadow(plan: &BindingPlan, token: u32) -> bool {
plan.descriptors.iter().any(|d| {
matches!(
d.source,
WriteSource::HeapEntry {
class: HandleClass::Image(class),
source: HeapSource::Used(used),
..
} if used == token && class.access == ImageAccess::Storage
)
})
}
/// The use `resource`, a use of the plan's or the command's other than of a resource made
/// resident, makes as `tables` bind it, a draw's index buffer `index` and argument buffer
/// `indirect` (each with its offset): `None` for an unbound slot (a neutral, fresh for the
+44 -16
View File
@@ -43,7 +43,13 @@
//! element is its shadow image's view, which holds the texels an encoder that named it last
//! copied in ([`Degradation::UnnamedShadowedTexture`], announced at the first command that
//! binds a set holding it while neither naming it nor making it resident, [`bind`]: one that
//! does has its shadow copied in). A carried texture's element is its decoded twin's view
//! does has its shadow copied in). A 4:4:4 two-plane YCbCr texture whose writes Metal stores
//! into its planes (`metal::format::ycbcr_writes_stored`) is, in a float storage array, its
//! write shadow's float view (`texture/usage_shadow.rs`), made as the texture is placed there:
//! a command that makes it resident for writing names the shadow (`binding.rs`), whose copies
//! clear its marks before the command and encode the texels a write through its handle marked
//! into the planes after it, and one that does not is announced as for a shadowed texture.
//! A carried texture's element is its decoded twin's view
//! (`texture/decoded_twin.rs`), and placing it is no read: where the twin's texels are not
//! Metal's decode exactly, `decoded-texel-precision` is announced at the first command that
//! binds a set holding it, named or not, or as it is placed in a set a command buffer that
@@ -1667,11 +1673,8 @@ fn texture_writes<'a>(
};
let (info, shadowed, twin, raw) = texture_info(device, array, texture, notes)?;
match shadowed {
true => {
let key = texture.bound_use(Access::NONE, Access::NONE).key;
array.shadows.insert(id, key)
}
false => array.shadows.remove(&id),
Some(key) => array.shadows.insert(id, key),
None => array.shadows.remove(&id),
};
if let Some(read) = noted(&mut array.twins, id, twin) {
placed.twin = Some(read);
@@ -1691,17 +1694,19 @@ fn texture_writes<'a>(
Ok(placed)
}
/// What an element of `array` holds for `texture` (the module docs), whether it is the
/// texture's shadow image's view, what a read of it announces where it is a decoded twin's
/// view whose texels are not Metal's decode exactly (`Texture::held_view`), and whether it is
/// the raw view of a texture a heap holds by its raw texels alone ([`RawRead`]).
/// What an element of `array` holds for `texture` (the module docs), the key a command names it
/// by where it is a shadow image's view (the texture's shadow, or a 4:4:4 two-plane YCbCr
/// texture's write shadow in a storage array, `Texture::ycbcr_write_use`), what a read of it
/// announces where it is a decoded twin's view whose texels are not Metal's decode exactly
/// (`Texture::held_view`), and whether it is the raw view of a texture a heap holds by its raw
/// texels alone ([`RawRead`]).
fn texture_info(
device: &Device,
array: &ImageArray,
texture: &Texture,
notes: &mut Notes,
) -> Result<(Info, bool, Option<TwinRead>, bool), Error> {
let neutral = || Ok((image_info(array.neutral), false, None, false));
) -> Result<(Info, Option<ResourceKey>, Option<TwinRead>, bool), Error> {
let neutral = || Ok((image_info(array.neutral), None, None, false));
let profile = device.compile_device().profile();
let class = HandleClass::Image(array.class);
let facts = texture.facts();
@@ -1724,14 +1729,30 @@ fn texture_info(
let raw = array.class.access == ImageAccess::Sampled
&& array.class.sampled_type == SampledType::Uint
&& heap_raw_form(&facts).is_some();
// A storage element of a 4:4:4 two-plane YCbCr texture whose writes Metal stores into its
// planes is its write shadow's float view (`bind::heap`), named by the shadow's key.
let write_shadow = texture.takes_ycbcr_writes(storage);
match texture.held_view("new_texture", &desc, storage) {
Ok((view, twin)) => Ok((image_info(view), texture.shadow().is_some(), twin, raw)),
Ok((view, twin)) => {
let shadowed = match write_shadow {
true => texture.ycbcr_write_key(),
false => (texture.shadow().is_some())
.then(|| texture.bound_use(Access::NONE, Access::NONE).key),
};
Ok((image_info(view), shadowed, twin, raw))
}
// The class needs what the texture's usage or levels lack: Metal's read is undefined.
Err(Error::Invalid(_)) => neutral(),
Err(Error::Unsupported(_)) => {
notes.unviewable(texture);
neutral()
}
// A write shadow refused (rows of codes that share bytes): a command that writes the
// texture through its handle is refused as it names it (`Texture::ycbcr_write_use`).
Err(Error::NotImplemented(_)) if write_shadow => {
notes.unviewable(texture);
neutral()
}
Err(error) => Err(error),
}
}
@@ -2878,10 +2899,17 @@ pub(super) fn bind(
// shadow through the ID, which the command's copies leave as the last encoder that named
// it copied it (Metal's own non-resident read is undefined). One its uses name has its
// shadow copied in (`shadow::shadow_uses`, compute's and render's alike).
// A texture is named by any key an array holds it by (a YCbCr texture's write shadow's in
// a storage array, its own image's elsewhere).
let named = |id: &u64| {
(entry.images.iter())
.filter_map(|array| array.shadows.get(id))
.any(|key| uses.iter().any(|used| used.key == *key))
};
notes.shadowed = (entry.images.iter())
.flat_map(|array| &array.shadows)
.find(|(_, key)| !uses.iter().any(|used| used.key == **key))
.map(|(&id, _)| id);
.flat_map(|array| array.shadows.keys())
.find(|id| !named(id))
.copied();
// A decoded twin whose texels are not Metal's decode exactly, which the command's
// function may read through its ID whether or not the command names it.
notes.twin_read = (entry.images.iter())
@@ -6481,6 +6481,12 @@ impl Texture {
desc: &ImageViewDesc,
storage: bool,
) -> Result<(vk::ImageView, Option<&TwinRead>), Error> {
// A storage view of a 4:4:4 two-plane YCbCr texture whose writes Metal stores into its
// planes is its write shadow's (`texture/usage_shadow.rs`): a heap's float storage element,
// as a slot's storage binding.
if self.takes_ycbcr_writes(storage) {
return Ok((self.ycbcr_write_view(call, desc)?, None));
}
let image: &Image = self.image()?;
// A sampled view of a texture with a decoded twin presents the twin.
if !storage {
@@ -43,7 +43,9 @@
//! (`metal::format::ycbcr_writes_stored`), whose image has both shader usages, holds its write
//! shadow here instead (`texture/ycbcr_image.rs`, `shadow.rs`): every storage binding of it
//! writes the shadow's view and names the shadow in its uses, and every other binding names its
//! own image. It is exact and announces nothing.
//! own image. A heap's float storage element holds the shadow's float view (`heap_sets.rs`),
//! which a command that makes the texture resident for writing through it names in its uses
//! (`binding.rs`). It is exact and announces nothing.
use super::{Image, Owner, Start, Storage, Texture};
use crate::binding_view::binding_view;
@@ -166,16 +168,8 @@ impl Texture {
storage: bool,
attached: bool,
) -> Result<vk::ImageView, Error> {
// The write shadow's texels are written, never read: no alpha reads 1 there.
if self.takes_ycbcr_writes(storage) {
let shadow = self.usage_shadow(call, Need::YCbCrWrites)?;
let record = ViewRecord {
alpha_reads_one: false,
..self.0.record.bound()
};
let view = binding_view(shadow.image.plan(), &record, desc, storage)
.map_err(|refusal| view_error(call, refusal))?;
return shadow.image.view(&view);
return self.ycbcr_write_view(call, desc);
}
let Some(shadow) = self.slot_shadow(call, storage, attached)? else {
return self.bound_view(call, desc, storage);
@@ -217,10 +211,61 @@ impl Texture {
/// (`texture/ycbcr_image.rs`) in this slot's place: a storage binding of a 4:4:4 two-plane
/// YCbCr texture whose writes Metal stores into its planes (`ycbcr_writes_stored`), which
/// the binding plan gives a view of the shadow's format (`StorageImageClass::YCbCrWrite`).
fn takes_ycbcr_writes(&self, storage: bool) -> bool {
pub(crate) fn takes_ycbcr_writes(&self, storage: bool) -> bool {
storage && ycbcr_writes_stored(self.0.record.pixel_format)
}
/// The `VkImageView` of `desc`, a storage binding's view, of the texture's YCbCr write shadow
/// (`texture/ycbcr_image.rs`), made at its first need for Metal's `call`: a slot's
/// `R32G32B32A32_UINT` view (`StorageImageClass::YCbCrWrite`), or a heap's float storage
/// element's `R32G32B32A32_SFLOAT` one (`bind::heap`). Its texels are written, never read: no
/// alpha reads 1 there.
pub(crate) fn ycbcr_write_view(
&self,
call: &'static str,
desc: &ImageViewDesc,
) -> Result<vk::ImageView, Error> {
let shadow = self.usage_shadow(call, Need::YCbCrWrites)?;
let record = ViewRecord {
alpha_reads_one: false,
..self.0.record.bound()
};
let view = binding_view(shadow.image.plan(), &record, desc, true)
.map_err(|refusal| view_error(call, refusal))?;
shadow.image.view(&view)
}
/// A use of the texture's YCbCr write shadow written by `write`, made at its first need for
/// Metal's `call`: of a command whose function writes the texture through an argument buffer's
/// handle, which the heap's float storage element holds the shadow for (`binding.rs`). Its
/// copies clear the shadow's marks before the command and encode the marked texels' codes into
/// the planes after it (`shadow.rs`), as a slot's do.
pub(crate) fn ycbcr_write_use(
&self,
call: &'static str,
write: Access,
) -> Result<Use<ResourceKey>, Error> {
let shadow = self.usage_shadow(call, Need::YCbCrWrites)?;
Ok(Use {
key: shadow.copies.shadow_key,
tracked: shadow.copies.tracked,
range: shadow.copies.shadow_range.clone(),
read: Access::NONE,
write,
})
}
/// The key a command names the texture's YCbCr write shadow by ([`ycbcr_write_use`]), where
/// a binding made it.
///
/// [`ycbcr_write_use`]: Self::ycbcr_write_use
pub(crate) fn ycbcr_write_key(&self) -> Option<ResourceKey> {
match self.takes_ycbcr_writes(true) {
true => (self.s().usage_shadow.get()).map(|shadow| shadow.copies.shadow_key),
false => None,
}
}
/// A slot binding's use of everything the texture presents, reading by `read` and writing by
/// `write`: of the shadow where a binding of the kind `storage`, `attached` as
/// [`slot_view`](Self::slot_view) takes it, says takes it, else the texture's own
@@ -626,7 +626,9 @@ impl Texture {
/// The write shadow of a 4:4:4 two-plane YCbCr texture whose writes Metal stores into its
/// planes (`metal::format::ycbcr_writes_stored`), for Metal's `call`: an `RGBA32Uint` image of
/// the texture's size, which a function writes each texel to as its red, green and blue bits
/// and the mark 1 (`StorageImageClass::YCbCrWrite`), and its copies, a clear in and the
/// and the mark 1 (`StorageImageClass::YCbCrWrite`), or, through a heap's float storage
/// element (`bind::heap`), as its `R32G32B32A32_SFLOAT` view's red, green and blue and the
/// mark 1.0, where the device stores that format, and its copies, a clear in and the
/// encoding of the marked texels' codes back into the planes (`ShadowSource::YCbCrWrite`,
/// `ycbcr.rs`). Refused (`Unsupported`, `NotImplemented`, `Feature::Format`, naming the
/// format) for a texture over plane 1 of its surface, whose writes are not measured, and one
@@ -677,6 +679,20 @@ impl Texture {
if plan.format != Format::R32G32B32A32_UINT || !plan.usage.contains(needed) {
return Err(gap());
}
// A heap's float storage element views it as floats too (`bind::heap`), where the device
// stores them; elsewhere a heap write reaches none of it, and only a slot's bits do.
let floats = Format::R32G32B32A32_SFLOAT;
let plan = match facts
.optimal(floats)
.contains(FormatFeatureFlags2::STORAGE_IMAGE)
{
true => crate::image_plan::ImagePlan {
flags: plan.flags | ImageCreateFlags::MUTABLE_FORMAT,
view_formats: vec![plan.format, floats],
..plan
},
false => plan,
};
let [w, h] = planes.size.map(u64::from);
let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA32Uint, w, h, false);
descriptor.usage = usage;
@@ -1014,6 +1014,8 @@ mod write_routes;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod xr_codes;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod ycbcr_argument_writes;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod ycbcr_device_reads;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod ycbcr_in_place;
@@ -0,0 +1,239 @@
//! Device tests of a kernel's `write()` to a two-plane YCbCr texture through an argument buffer
//! (`bind::heap`, `memory::handles::FLAG_YCBCR_WRITES`), on the device the cfg selects, under the
//! validation layer. Metal stores the same bytes through an argument buffer's texture as through a
//! slot (an Apple M3 Max under macOS 27.0.1: `YCBCR8_444_2P`, `YCBCR10_444_2P` and the `_sRGB`
//! twins byte for byte the slot's, `RGB8_444_2P` and `RGB10_444_2P` as their slot's, and nothing
//! of `YCBCR8_420_2P`, the command buffer completed), so each format's argument-buffer write is
//! checked against its slot write over identical surfaces ([`super::ycbcr_srgb_twins`]'s layout),
//! whose codes the slot lanes check against Metal's. The writes' alpha is 0, so a write that did
//! not mark the texels it stores leaves the planes as they were.
//!
//! A command whose argument buffer names no such texture specializes the kernel as before the
//! writes were built (`SpecKey::HeapYCbCrWrites` 0): it makes no new pipeline.
use super::buffer_with;
use super::degrade_notices::on_device;
use super::read_buffer;
use super::ycbcr_srgb_twins::{
complete, library, surface_bytes, twin_texture, COLORS, H, LENGTH, W,
};
use crate::air_library::AirLibrary;
use metal2vulkan::error::{Error as CompileError, Feature};
use metal2vulkan::metal::{PixelFormat, ResourceUsage, TextureUsage};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use metal2vulkan_devtools::llvm_assemble_text;
use metal2vulkan_runtime::{
Buffer, CommandQueue, ComputePipelineState, Device, Error, Library, PipelineOptions, Size,
Texture, TextureDescriptor,
};
/// Synthetic AIR written for this lane: kernel `write_held` writes buffer 0's `float4` `gid.x` to
/// texel `gid` of the `texture2d<float, write>` the argument buffer at buffer 1 holds.
const HELD: &str = r#"; Owned synthetic shader.
%struct.Held = type { ptr addrspace(1) }
define void @write_held(ptr addrspace(2) noalias %held, ptr addrspace(1) noalias %colors, <2 x i32> %gid) {
entry:
%pt = getelementptr inbounds %struct.Held, ptr addrspace(2) %held, i64 0, i32 0
%t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8
%x = extractelement <2 x i32> %gid, i64 0
%j = zext i32 %x to i64
%p = getelementptr inbounds <4 x float>, ptr addrspace(1) %colors, i64 %j
%v = load <4 x float>, ptr addrspace(1) %p, align 16
tail call void @air.write_texture_2d.v4f32(ptr addrspace(1) %t, <2 x i32> %gid, <4 x float> %v, i32 0, i32 2)
ret void
}
declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32)
!air.kernel = !{!0}
!air.version = !{!97}
!air.language_version = !{!98}
!0 = !{ptr @write_held, !1, !2}
!1 = !{}
!2 = !{!3, !6, !7}
!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"Held", !"air.arg_name", !"held"}
!4 = !{i32 0, i32 8, i32 0, !"texture2d<float, write>", !"t", !"air.indirect_argument", !5}
!5 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d<float, write>", !"air.arg_name", !"t"}
!6 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"colors"}
!7 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"gid"}
!97 = !{i32 2, i32 8, i32 0}
!98 = !{!"Metal", i32 4, i32 0, i32 0}
"#;
/// The formats, each over a surface of its OSType, and whether Metal stores its writes.
const FORMATS: [(PixelFormat, &str, bool); 7] = [
(PixelFormat::YCBCR84202P, "420v", false),
(PixelFormat::YCBCR84442P, "444v", true),
(PixelFormat::YCBCR104442P, "x444", true),
(PixelFormat::YCBCR84442PSRGB, "444v", true),
(PixelFormat::YCBCR104442PSRGB, "x444", true),
(PixelFormat::RGB84442P, "444v", true),
(PixelFormat::RGB104442P, "x444", true),
];
/// The library of [`HELD`].
fn held_library(device: &Device) -> Library {
device
.new_library_with_air(&llvm_assemble_text(HELD).unwrap())
.unwrap()
}
/// The compute pipeline state of kernel `name` of `library`; `None` where the device refuses it
/// for a heap it lacks (`ArgumentBufferTextures`).
fn state(device: &Device, library: &Library, name: &str) -> Option<ComputePipelineState> {
let function = library.new_function_with_name(name).unwrap();
let made = device.new_compute_pipeline_state(
&ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())),
&PipelineOptions::default(),
);
match made {
Ok(state) => Some(state),
Err(Error::Unsupported(u)) | Err(Error::Compile(CompileError::Unsupported(u)))
if u.feature == Feature::ArgumentBufferTextures =>
{
println!("YCBCR-HELD {}: {name} refused: {u}", device.name());
None
}
Err(e) => panic!("{name}: {e}"),
}
}
/// [`COLORS`] as `float4`s, alpha 0.
fn colors(device: &Device) -> Buffer {
let bytes: Vec<u8> = COLORS
.iter()
.flat_map(|&[r, g, b]| [r, g, b, 0.0])
.flat_map(f32::to_le_bytes)
.collect();
buffer_with(device, &bytes).unwrap()
}
/// Run `state` on `device`'s `queue` over the whole of `texture`, with `values` at buffer 0: the texture at slot 0, or,
/// with `held`, its resource ID in a buffer at buffer 1, the texture resident for writing.
fn write(
(device, queue): (&Device, &CommandQueue),
state: &ComputePipelineState,
(texture, held): (&Texture, bool),
values: &Buffer,
) {
let ids = buffer_with(device, &texture.gpu_resource_id().0.to_le_bytes()).unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(state).unwrap();
encoder.set_buffer(Some(values), 0, 0).unwrap();
match held {
true => {
encoder.set_buffer(Some(&ids), 0, 1).unwrap();
encoder
.use_resource(texture.as_resource(), ResourceUsage::WRITE)
.unwrap();
}
false => encoder.set_texture(Some(texture), 0).unwrap(),
}
encoder
.dispatch_threads(Size::new(W, H, 1), Size::new(W, H, 1))
.unwrap();
encoder.end_encoding().unwrap();
complete(&command_buffer);
}
/// A kernel's writes of the eight colors through an argument buffer's texture store the bytes its
/// writes through a slot store, over identical random surfaces, keeping every other byte: of each
/// 4:4:4 format whose writes Metal stores, codes in both planes; of `YCBCR8_420_2P`, whose writes
/// Metal drops, nothing.
#[test]
fn argument_buffer_writes_to_ycbcr_textures_store_the_slot_s_bytes() {
on_device(|device, _| {
let Some(held) = state(device, &held_library(device), "write_held") else {
return;
};
let slot = state(device, &library(device), "write_columns").unwrap();
let queue = device.new_command_queue().unwrap();
let values = colors(device);
let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE;
for (seed, (pf, ostype, stored)) in (0x5300..).zip(FORMATS) {
let bytes = surface_bytes(seed);
let after: Vec<Vec<u8>> = [(&slot, false), (&held, true)]
.into_iter()
.map(|(state, through)| {
let surface = buffer_with(device, &bytes).unwrap();
let texture = twin_texture(&surface, pf, ostype, usage).unwrap();
write((device, &queue), state, (&texture, through), &values);
read_buffer(&surface, 0, LENGTH).unwrap()
})
.collect();
let apart = (after[0].iter().zip(&after[1])).filter(|(a, b)| a != b);
assert_eq!(
apart.count(),
0,
"{pf:?} over {ostype}: the bytes the argument buffer's writes stored differ from \
the slot's"
);
assert_eq!(
after[0] != bytes,
stored,
"{pf:?} over {ostype}: the slot's writes stored codes"
);
println!("YCBCR-HELD {pf:?} over {ostype}: the slot's bytes, stored {stored}");
}
});
}
/// A command whose argument buffer holds no texture whose writes go to a write shadow makes no new
/// pipeline of the kernel: after an `RGBA8Unorm` member's, an `RGBA16Float` member's and a
/// `YCBCR8_420_2P` member's (whose writes Metal drops) dispatches make none; a `YCBCR8_444_2P`
/// member's makes its variant once, which a second such dispatch takes.
#[test]
fn argument_buffer_writes_without_a_ycbcr_member_make_no_new_pipeline() {
on_device(|device, _| {
let Some(held) = state(device, &held_library(device), "write_held") else {
return;
};
let queue = device.new_command_queue().unwrap();
let values = colors(device);
let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE;
let plain = |pf| {
let mut d = TextureDescriptor::texture_2d(pf, W, H, false);
d.usage = usage;
device.new_texture(&d).unwrap()
};
let surface = buffer_with(device, &surface_bytes(0x5310)).unwrap();
let dropped = twin_texture(&surface, PixelFormat::YCBCR84202P, "420v", usage).unwrap();
let other = buffer_with(device, &surface_bytes(0x5311)).unwrap();
let shadowed = twin_texture(&other, PixelFormat::YCBCR84442P, "444v", usage).unwrap();
let made = || device.work_counts().variant_pipelines_made;
write(
(device, &queue),
&held,
(&plain(PixelFormat::RGBA8Unorm), true),
&values,
);
let first = made();
write(
(device, &queue),
&held,
(&plain(PixelFormat::RGBA16Float), true),
&values,
);
write((device, &queue), &held, (&dropped, true), &values);
assert_eq!(
made(),
first,
"a command naming no shadowed texture made a pipeline"
);
write((device, &queue), &held, (&shadowed, true), &values);
let shadowing = made();
assert!(shadowing > first, "the shadowed texture's variant was made");
write((device, &queue), &held, (&shadowed, true), &values);
assert_eq!(
made(),
shadowing,
"a second shadowed command made a pipeline"
);
println!(
"YCBCR-HELD pipelines: {first} after the plain and dropped members, {shadowing} after \
the shadowed one"
);
});
}
@@ -29,18 +29,18 @@ use std::time::Duration;
const WAIT: Duration = Duration::from_secs(60);
/// The texture's width and height, as the probe's.
const W: u64 = 8;
const H: u64 = 2;
pub(super) const W: u64 = 8;
pub(super) const H: u64 = 2;
/// The bytes between rows of either plane.
const ROW: u64 = 64;
/// The chroma plane's first byte.
const CHROMA_AT: u64 = 4096;
/// The surface's bytes: both planes.
const LENGTH: u64 = CHROMA_AT + ROW * H;
pub(super) const LENGTH: u64 = CHROMA_AT + ROW * H;
/// The probe's colors, column `x` the color `x`: black, white, gray 0.5, red, green, blue, and
/// two mixed ones.
const COLORS: [[f32; 3]; 8] = [
pub(super) const COLORS: [[f32; 3]; 8] = [
[0.0, 0.0, 0.0],
[1.0, 1.0, 1.0],
[0.5, 0.5, 0.5],
@@ -176,14 +176,14 @@ impl Random {
}
/// A surface's random bytes, of `seed`.
fn surface_bytes(seed: u64) -> Vec<u8> {
pub(super) fn surface_bytes(seed: u64) -> Vec<u8> {
let mut random = Random(seed);
(0..LENGTH).map(|_| random.next()).collect()
}
/// The texture of `pf` over plane 0 of `surface`, a surface of OSType `ostype` without a matrix
/// laid out by [`ROW`] and [`CHROMA_AT`], of `usage`.
fn twin_texture(
pub(super) fn twin_texture(
surface: &Buffer,
pf: PixelFormat,
ostype: &str,
@@ -199,7 +199,7 @@ fn twin_texture(
}
/// The library of [`SHADERS`].
fn library(device: &Device) -> Library {
pub(super) fn library(device: &Device) -> Library {
device
.new_library_with_air(&llvm_assemble_text(SHADERS).unwrap())
.unwrap()
@@ -276,7 +276,7 @@ fn apart(after: &[u8], want: &[u8], bits: u32) -> (BTreeSet<u64>, bool) {
}
/// Commit `command_buffer`, wait for it, and expect it to have completed without an error.
fn complete(command_buffer: &CommandBuffer) {
pub(super) fn complete(command_buffer: &CommandBuffer) {
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.error(), None);
+9 -4
View File
@@ -332,10 +332,10 @@ use crate::bind::plan::compute::{internal, not_implemented, spec_key, tile_memor
use crate::bind::plan::resources::{separate_samplers, ResourcePlanner};
use crate::bind::plan::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, large_view_candidates,
mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted, record_specialized,
snapshot_forms, srgb_variant, storage_view_variant, used_uses, ycbcr_in_place_variant,
ycbcr_planes_sampled_variant,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes,
large_view_candidates, mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted,
record_specialized, snapshot_forms, srgb_variant, storage_view_variant, used_uses,
ycbcr_in_place_variant, ycbcr_planes_sampled_variant,
};
use crate::bind::plan::{
AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorSite, FactorTemplate,
@@ -2399,6 +2399,11 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
// What a stage's handles can name: its raw arms drop where it names no texture held
// by its raw texels.
SpecKey::HeapRawTextures(stage) => u64::from(heap_raw(shape, stage, &heap_reach)),
// Its YCbCr writes' marks drop where it names no texture whose writes go to its write
// shadow.
SpecKey::HeapYCbCrWrites(stage) => {
u64::from(heap_ycbcr_writes(shape, stage, &heap_reach))
}
other => {
return Err(internal(format!(
"a render specialization constant {other:?}"
+89 -10
View File
@@ -32,7 +32,16 @@
//! (`metal::format::without_format_gaps`: the device's features and the format's own
//! `VkFormatFeatureFlags2` bits). A fitting member the heap cannot view (another storage choice,
//! a format the profile cannot sample or store) is `Unsupported`, as for a slot: a handle may
//! name it. Every other element up to the members' count is the class's neutral; the elements
//! name it. A storage class holds a texture whose writes Metal drops
//! (`metal::format::writes_dropped`: the 4:2:2 formats, the subsampled and packed two-plane
//! YCbCr ones) as its neutral ([`Fit::Dropped`]), which the writes leave as Metal leaves the
//! texture, and a 4:4:4 two-plane YCbCr texture whose writes Metal stores into its planes
//! (`metal::format::ycbcr_writes_stored`) through the `R32G32B32A32_SFLOAT` view of its write
//! shadow, whose texels a heap write marks where the handle carries [`FLAG_YCBCR_WRITES`] and
//! which the consumer encodes into the planes as a slot's writes; a stage that reads such a
//! class (`RuntimeFact::HeapStorageReads`) refuses either texture it reaches there,
//! `Unsupported { feature: Format, needs: NotImplemented }`, as a slot that reads one is
//! refused. Every other element up to the members' count is the class's neutral; the elements
//! past it are left unwritten (the arrays are `PARTIALLY_BOUND`, and no table entry names them).
//! All heap writes of one member share one layout, `GENERAL` when some storage array holds it; a
//! member bound at a slot shares it with the slot's own writes, `GENERAL` when either is a
@@ -68,7 +77,9 @@
//! its pixel format is blue-first (`metal::format::red_blue_exchanged`); its border texels in
//! [`FLAG_BORDER_TEXELS`] (`metal::sampler::border_texels` of its pixel format and swizzle, a
//! placeholder format's those of the neutral it reads), which a read through a sampler hands
//! back at a border; and its texel class in [`FLAG_TEXEL_CLASS`]. Every other bit is 0.
//! back at a border; [`FLAG_YCBCR_WRITES`] where it is a 4:4:4 two-plane YCbCr texture whose
//! writes Metal stores (`metal::format::ycbcr_writes_stored`); and its texel class in
//! [`FLAG_TEXEL_CLASS`]. Every other bit is 0.
//! - **Heap samplers**. A heap image is sampled through a separate sampler binding
//! (`BindingSource::HeapSampler`) in set 0: a constexpr sampler is the layout's immutable sampler
//! and takes no write; a runtime `[[sampler(n)]]` is written with the sampler bound at slot `n`
@@ -148,12 +159,12 @@ use crate::device::DeviceProfile;
use crate::error::{BindError, Feature, Unsupported};
use crate::memory::handles::{
lookup_host, ENTRY_ELEMENT, ENTRY_FLAGS, ENTRY_ID_HI, ENTRY_ID_LO, FLAG_BORDER_TEXELS,
FLAG_OUT_OF_BOUNDS_ALPHA_ONE, FLAG_RED_BLUE, FLAG_TEXEL_CLASS, NEUTRAL_ELEMENT, TABLE_CAPACITY,
TABLE_ENTRY_BYTES,
FLAG_OUT_OF_BOUNDS_ALPHA_ONE, FLAG_RED_BLUE, FLAG_TEXEL_CLASS, FLAG_YCBCR_WRITES,
NEUTRAL_ELEMENT, TABLE_CAPACITY, TABLE_ENTRY_BYTES,
};
use crate::metal::format::{
is_depth_stencil, red_blue_exchanged, sampled_type, storage_choice, storage_view_formats,
vk_format, without_format_gaps, StorageUse,
vk_format, without_format_gaps, writes_dropped, ycbcr_writes_stored, StorageUse,
};
use crate::metal::sampler::{
check_argument_sampler, check_border_view, vk_filtering, SamplerUse, SamplerWord,
@@ -230,6 +241,9 @@ pub(crate) enum Fit {
Raw,
/// It fits in everything but its numeric type.
NumericType,
/// A storage class's member whose writes Metal drops (`metal::format::writes_dropped`): the
/// class's array holds its neutral, which the writes leave as Metal leaves the texture.
Dropped,
/// It is another class's.
No,
}
@@ -281,6 +295,7 @@ pub(crate) fn fit(shape: &TextureShape, class: &ImageHandleClass) -> Fit {
// does not know which of its textures the function reads.
match sampled_type(pixel_format) {
_ if !shaped => Fit::No,
_ if storage && writes_dropped(pixel_format) => Fit::Dropped,
// A form a heap reads: its raw texels in the unsigned integer class, the neutral in the
// float one.
_ if raw_held(shape) && class.access == ImageAccess::Sampled => match class.sampled_type {
@@ -411,6 +426,28 @@ fn member_view(
// The class does not say which accesses the function makes, so the member serves
// every access the device lets a heap make.
let use_ = heap_storage_use(profile);
// A 4:4:4 two-plane YCbCr texture whose writes Metal stores into its planes: its write
// shadow's float view, whose texels a heap write marks (`FLAG_YCBCR_WRITES`), the
// consumer's to encode into the planes.
if ycbcr_writes_stored(pixel_format) {
let format = vk::Format::R32G32B32A32_SFLOAT;
let gaps = without_format_gaps(format, use_, profile);
if !gaps.is_empty() {
return Err(BindError::Unsupported(Unsupported::needs_any_of(
Feature::ArgumentBufferTextures,
vec![gaps],
)));
}
return Ok(ImageViewDesc {
view_type: view_type(class)?,
format,
aspect: vk::ImageAspectFlags::COLOR,
layout,
components: vk::ComponentMapping::IDENTITY,
level: None,
shader_swizzle: false,
});
}
let c = storage_choice(pixel_format, use_, profile).map_err(bind_error)?;
// The class's one formatless declaration cannot convert per element: a member is viewed
// through its own format.
@@ -516,7 +553,7 @@ pub fn heap_element(
Fit::Holds => member_view(profile, &shape, image, layout).map(HeapElement::View),
// The float array holds its neutral, and a function's float read takes its raw texels
// from the unsigned integer array, which views it ([`Fit::Holds`] there).
Fit::Raw | Fit::NumericType | Fit::No => Ok(HeapElement::Neutral),
Fit::Raw | Fit::NumericType | Fit::No | Fit::Dropped => Ok(HeapElement::Neutral),
}
}
@@ -528,8 +565,10 @@ pub fn heap_element(
/// (`metal::sampler::border_texels` of its pixel format and swizzle), which a Metal 4.1 read
/// through a sampler hands back at a border; bits 16 to 28 the index of the texture's texel class
/// (`metal::texel_format::heap_class_index` of its pixel format and swizzle), by which the shader
/// emulates Metal's linear filter of the texture's texels, 0 for a swizzled texture; every other
/// bit 0. A caller passes the word through as is.
/// emulates Metal's linear filter of the texture's texels, 0 for a swizzled texture; bit 15 where
/// it is a 4:4:4 two-plane YCbCr texture whose writes Metal stores into its planes
/// (`metal::format::ycbcr_writes_stored`), so a heap write marks its write shadow
/// ([`FLAG_YCBCR_WRITES`]); every other bit 0. A caller passes the word through as is.
pub fn handle_entry_flags(facts: &TextureFacts) -> u32 {
entry_flags(&facts.shape())
}
@@ -553,7 +592,11 @@ fn entry_flags(shape: &TextureShape) -> u32 {
<< FLAG_BORDER_TEXELS.trailing_zeros();
let index = crate::metal::texel_format::heap_class_index(pixel_format, swizzle);
let class = index << FLAG_TEXEL_CLASS.trailing_zeros();
alpha | red_blue | (border & FLAG_BORDER_TEXELS) | (class & FLAG_TEXEL_CLASS)
let ycbcr = match ycbcr_writes_stored(pixel_format) {
true => FLAG_YCBCR_WRITES,
false => 0,
};
alpha | red_blue | ycbcr | (border & FLAG_BORDER_TEXELS) | (class & FLAG_TEXEL_CLASS)
}
/// A conversion a storage access through a heap handle makes of the texels of a member its
@@ -800,6 +843,8 @@ pub(crate) struct HeapPlanner<'a> {
/// neutral (`RuntimeFact::HeapCrossClassNeutral`), each with whether every such member does
/// (else only one of a format a crossing read does not take).
cross_neutral: BTreeMap<Stage, BTreeMap<ImageHandleClass, bool>>,
/// The storage classes each stage reads (`RuntimeFact::HeapStorageReads`).
storage_reads: BTreeMap<Stage, BTreeSet<ImageHandleClass>>,
/// The sampler tables, `(stage, set, binding)`.
sampler_tables: Vec<(Stage, u32, u32)>,
/// The argument samplers' shape, the entries of every sampler array and table, and what
@@ -891,6 +936,12 @@ impl<'a> HeapPlanner<'a> {
*write_rounding.entry(stage).or_insert(false) |= halves;
}
}
let mut storage_reads: BTreeMap<Stage, BTreeSet<ImageHandleClass>> = BTreeMap::new();
for d in dependencies {
if let RuntimeFact::HeapStorageReads { stage, class } = d.fact {
storage_reads.entry(stage).or_default().insert(class);
}
}
for set in &layout.sets {
for b in &set.bindings {
match b.source {
@@ -1122,6 +1173,7 @@ impl<'a> HeapPlanner<'a> {
sampling,
write_rounding,
cross_neutral,
storage_reads,
sampler_tables,
samplers,
directories,
@@ -1355,7 +1407,15 @@ impl<'a> HeapPlanner<'a> {
for (i, m) in self.members.iter().enumerate() {
let element =
u32::try_from(i + 1).map_err(|_| internal("a heap element beyond u32"))?;
let source = match fit(&m.shape, &image) {
let fits = fit(&m.shape, &image);
// A texture whose writes Metal drops or stores through its write shadow, in a storage
// class a stage it reaches reads: Metal's read of it is not measured.
if matches!(fits, Fit::Holds | Fit::Dropped) && self.reads_unmeasured(m, &image) {
return Err(BindError::Unsupported(Unsupported::not_implemented(
Feature::Format,
)));
}
let source = match fits {
// A texture a stage may write by a mode-2 write the function has not built.
Fit::Holds if image.access == ImageAccess::Storage && self.rounds(m) => {
return Err(BindError::Unsupported(Unsupported::not_implemented(
@@ -1388,6 +1448,8 @@ impl<'a> HeapPlanner<'a> {
)));
}
Fit::Raw => WriteSource::Neutral(n),
// The writes Metal drops leave the neutral as Metal leaves the texture.
Fit::Dropped => WriteSource::Neutral(n),
fit => {
if fit == Fit::NumericType && self.defaulted.contains(&image) {
self.diagnostics
@@ -1432,6 +1494,23 @@ impl<'a> HeapPlanner<'a> {
Ok(out)
}
/// Whether a stage member `m` reaches reads it in the storage class `class`
/// (`RuntimeFact::HeapStorageReads`) where `m` is a texture whose writes Metal drops
/// (`metal::format::writes_dropped`) or stores into its planes through its write shadow
/// (`metal::format::ycbcr_writes_stored`), whose read there is not measured.
fn reads_unmeasured(&self, m: &HeapMember, class: &ImageHandleClass) -> bool {
let TextureShape::Texture { pixel_format, .. } = m.shape else {
return false;
};
class.access == ImageAccess::Storage
&& (writes_dropped(pixel_format) || ycbcr_writes_stored(pixel_format))
&& m.stages.iter().any(|s| {
self.storage_reads
.get(s)
.is_some_and(|classes| classes.contains(class))
})
}
/// Whether a stage member `m` reaches writes it by a mode-2 write the function states it has
/// not built (`RuntimeFact::HeapWriteRounding`): `m` is an `RG11B10Float` or `RGB9E5Float`
/// texture, or a half-float one where the stage writes `float` texels
@@ -623,6 +623,7 @@ fn a_storage_member_is_viewed_through_the_alias_a_heap_access_converts() {
sampling: BTreeSet::new(),
write_rounding: BTreeMap::new(),
cross_neutral: BTreeMap::new(),
storage_reads: BTreeMap::new(),
sampler_tables: Vec::new(),
samplers: None,
directories: Vec::new(),
@@ -1398,6 +1399,7 @@ fn a_form_a_heap_reads_is_held_raw_in_the_unsigned_class() {
sampling,
write_rounding: BTreeMap::new(),
cross_neutral: BTreeMap::new(),
storage_reads: BTreeMap::new(),
sampler_tables: Vec::new(),
samplers: None,
directories: Vec::new(),
@@ -1508,6 +1510,7 @@ fn a_heap_member_a_mode_two_write_would_round_is_refused() {
sampling: BTreeSet::new(),
write_rounding: BTreeMap::from([(stage, halves)]),
cross_neutral: BTreeMap::new(),
storage_reads: BTreeMap::new(),
sampler_tables: Vec::new(),
samplers: None,
directories: Vec::new(),
+8 -3
View File
@@ -62,9 +62,9 @@
use super::resources::{separate_samplers, ResourcePlanner};
use super::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, mark_disjoint, plan_buffer,
psb_variant, record_noted, record_specialized, srgb_variant, storage_view_variant, used_uses,
ycbcr_in_place_variant, ycbcr_planes_sampled_variant,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes,
mark_disjoint, plan_buffer, psb_variant, record_noted, record_specialized, srgb_variant,
storage_view_variant, used_uses, ycbcr_in_place_variant, ycbcr_planes_sampled_variant,
};
use super::{
BindingPlan, BoundKind, ComputeTemplate, DescriptorWrite, FieldLocation, LocalRules,
@@ -722,6 +722,11 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
SpecKey::HeapRawTextures(stage) => {
u64::from(heap_raw(shape, stage, &|_| vec![Stage::Kernel]))
}
// What the kernel's handles can name: its YCbCr writes' marks drop where it names no
// texture whose writes go to its write shadow.
SpecKey::HeapYCbCrWrites(stage) => {
u64::from(heap_ycbcr_writes(shape, stage, &|_| vec![Stage::Kernel]))
}
other => return Err(internal(format!("a compute specialization {other:?}"))),
};
fixed.push((c.key, v));
@@ -349,6 +349,33 @@ fn heap_ycbcr(
})
}
/// The `SpecKey::HeapYCbCrWrites` of `stage` for `shape`: whether a heap member of `shape` that
/// reaches `stage` (as for [`heap_ycbcr`]) is a 4:4:4 two-plane YCbCr texture whose writes Metal
/// stores into its planes (`metal::format::ycbcr_writes_stored`) whose usage a storage class takes
/// (`ShaderWrite`, or `BlockWritesOnly`, as `bind::heap::fit` takes it): its write shadow is the
/// element a heap write marks. The stage's constant, under which its handle-table search carries
/// the entry's `FLAG_YCBCR_WRITES`: a command that names no such texture runs a pipeline without
/// the test.
pub(crate) fn heap_ycbcr_writes(
shape: &BindShape,
stage: Stage,
reach: &dyn Fn(metal::RenderStages) -> Vec<Stage>,
) -> bool {
let writes = metal::TextureUsage::SHADER_WRITE | metal::TextureUsage::BLOCK_WRITES_ONLY;
crate::bind::heap::members(shape, &[stage], reach)
.iter()
.any(|m| match m.shape {
TextureShape::Texture {
pixel_format,
usage,
..
} => {
crate::metal::format::ycbcr_writes_stored(pixel_format) && usage.intersects(writes)
}
_ => false,
})
}
/// The `SpecKey::HeapRawTextures` of `stage` for `shape`: of the heap members of `shape` that reach
/// `stage` (as for [`heap_ycbcr`]), the bit `bind::heap::HELD` where one is a texture a heap holds
/// by its raw texels alone (`bind::heap::heap_raw_form`), which the stage's `float` read, sample or
+2 -1
View File
@@ -887,7 +887,7 @@ codec_enum! {
SamplerAnisotropy(f0), RangeAtBindOffset(f0), PlainHalfTexels(f0),
NearestPixelSampler(f0), BoundSamplerWord(f0), HeapYCbCrTextures(f0),
FilteringArgumentSampler, StageInReach, HeapRawTextures(f0), BorderTexels(f0),
HeapNanFamilies(f0),
HeapNanFamilies(f0), HeapYCbCrWrites(f0),
}
PushField {
RootTableAddress, ExecutionStatusAddress, DispatchRegion, BaseVertexInstance,
@@ -1307,6 +1307,7 @@ codec_enum! {
HeapWriteRounding { stage, halves },
HeapCrossClassNeutral { stage, class, every_member },
HeapResidency { stage },
HeapStorageReads { stage, class },
AnisotropicSampler { slot },
StorageTextureIntegerChannels { slot },
MovableStorageWrites { early_variant },
+2 -2
View File
@@ -61,7 +61,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 = 2113;
pub const SEMANTICS_VERSION: u32 = 2114;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 2306;
pub const RUNTIME_VERSION: u32 = 2307;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -263,6 +263,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
RuntimeFact::HeapCrossClassNeutral { .. } => Mechanism::PlanTimeCheck,
// The planner refuses a sparse texture the stage's handle tables reach.
RuntimeFact::HeapResidency { .. } => Mechanism::PlanTimeCheck,
// The planner refuses a texture of a dropped or shadowed write the stage reaches in a
// storage class it reads.
RuntimeFact::HeapStorageReads { .. } => Mechanism::PlanTimeCheck,
// Keyed by the slots bound to a sampler whose word states anisotropy, where the
// function's samples take Metal's anisotropic filter, emulated.
RuntimeFact::AnisotropicSampler { .. } => Mechanism::Variant,
@@ -255,6 +255,18 @@ fn every_fact() -> Vec<RuntimeFact> {
RuntimeFact::HeapResidency {
stage: Stage::Fragment,
},
RuntimeFact::HeapStorageReads {
stage: Stage::Kernel,
class: crate::pipeline::sym::ImageHandleClass {
dim: crate::pipeline::sym::ImageDim::D2,
arrayed: false,
multisampled: false,
sampled_type: crate::pipeline::sym::SampledType::Float,
depth_compare: false,
access: crate::pipeline::sym::ImageAccess::Storage,
format: crate::pipeline::sym::StorageFormatClass::Unknown,
},
},
RuntimeFact::AnisotropicSampler {
slot: SlotRef {
stage: Stage::Fragment,
@@ -390,6 +402,7 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::CallThreadgroups => 97,
RuntimeFact::PartialThreadgroups => 98,
RuntimeFact::TexelRows { .. } => 99,
RuntimeFact::HeapStorageReads { .. } => 100,
}
}
@@ -397,7 +410,7 @@ fn variant(f: &RuntimeFact) -> usize {
fn mechanism_is_total_over_every_fact_and_profile() {
let facts = every_fact();
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
assert_eq!(covered, (0..100).collect(), "every_fact misses a variant");
assert_eq!(covered, (0..101).collect(), "every_fact misses a variant");
for (stem, _) in super::committed_profiles() {
let dev = device(&stem);
let p = dev.profile();
@@ -446,6 +459,7 @@ fn mechanism_is_total_over_every_fact_and_profile() {
| RuntimeFact::HeapWriteRounding { .. }
| RuntimeFact::HeapCrossClassNeutral { .. }
| RuntimeFact::HeapResidency { .. }
| RuntimeFact::HeapStorageReads { .. }
| RuntimeFact::ObjectThreadgroupArena { .. }
| RuntimeFact::RowLockstep => Mechanism::PlanTimeCheck,
RuntimeFact::DispatchGrid
+9 -1
View File
@@ -789,6 +789,11 @@ pub struct AccessPlan {
/// red-blue order (`lower::texture::heap_storage_conversions`): the handle-table search
/// carries the entry's `FLAG_RED_BLUE` too (`memory::handles::Lookup::Flagged`).
pub heap_red_blue: bool,
/// A `float` or `half` texel the function writes through a heap handle marks the texel it
/// stores in a member's write shadow where the handle carries the entry's
/// `FLAG_YCBCR_WRITES` (`lower::texture::emit`): the handle-table search carries it, under
/// the stage's `SpecKey::HeapYCbCrWrites` (`memory::handles::Lookup::Flagged`).
pub heap_ycbcr_writes: bool,
/// A heap texture's read through a sampler may hand back its border texels
/// (`lower::texture::Through`), which its handle-table entry holds
/// (`memory::handles::FLAG_BORDER_TEXELS`): the search yields each heap handle's entry index
@@ -814,17 +819,20 @@ impl AccessPlan {
pub fn lookup(&self) -> crate::memory::handles::Lookup {
use crate::memory::handles::Lookup;
let (alpha, class, red_blue) = (self.heap_alpha, self.carries_class(), self.heap_red_blue);
let ycbcr = self.heap_ycbcr_writes;
if self.heap_border {
Lookup::Indexed {
alpha,
class,
red_blue,
ycbcr,
}
} else if alpha || class || red_blue {
} else if alpha || class || red_blue || ycbcr {
Lookup::Flagged {
alpha,
class,
red_blue,
ycbcr,
}
} else {
Lookup::Element
+50 -2
View File
@@ -547,10 +547,16 @@ pub(crate) struct HeapElement {
/// masked to its element where the search carries anything beside it
/// (`memory::handles::Lookup::element_mask`), else the handle itself.
fn heap_element_index(cx: &EmitCx<'_>, fb: &mut FunctionBuilder<'_>, h: SValue) -> BResult<SValue> {
let Some(element) = cx.plan.families.access.lookup().element_mask() else {
let form = cx.plan.families.access.lookup();
let Some(element) = form.element_mask() else {
return Ok(h);
};
let mask = u32s(fb, 1, element)?;
// A search that carries `FLAG_YCBCR_WRITES` carries it only under the stage's constant: its
// mask clears the bit only there (`memory::handles::ycbcr_element_mask`).
let mask = match form.carries_ycbcr() {
true => crate::memory::handles::ycbcr_element_mask(fb, cx.plan.stage, element)?,
false => u32s(fb, 1, element)?,
};
fb.binary(BinOp::BitwiseAnd, h, mask)
}
@@ -802,6 +808,38 @@ fn alpha_in_red(fb: &mut FunctionBuilder<'_>, x: SValue, read: bool) -> BResult<
/// comparison, the shuffle and the select.
pub(crate) const HEAP_ALPHA_IN_RED_WORDS: u32 = 40;
/// The words [`heap_ycbcr_mark`] and its select emit, at most: the flag's mask and comparison,
/// the constant's test and its conjunction, the mark's insertion, the select, and their constants.
pub(crate) const HEAP_YCBCR_WRITE_WORDS: u32 = 48;
/// Whether a write through heap handle `handle` stores into a 4:4:4 two-plane YCbCr member's
/// write shadow, and what it stores there of image texel `x` (four `f32` lanes, the function's
/// own values): its red, green and blue, and alpha 1.0, whose bits are nonzero: the mark a slot of
/// such a texture writes as the integer 1 (`StorageImageClass::YCbCrWrite`,
/// [`ycbcr_write_texel`]), which the shadow's encoding reads as written (`bind::ycbcr_write`). The handle carries the entry's
/// `memory::handles::FLAG_YCBCR_WRITES` in `HANDLE_YCBCR_WRITES`; the test holds only under the
/// stage's `SpecKey::HeapYCbCrWrites` (`memory::handles::ycbcr_writes_set`), so a pipeline whose
/// command names no such texture compiles none of it.
fn heap_ycbcr_mark(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
handle: ValueId,
x: SValue,
) -> BResult<(SValue, SValue)> {
use crate::memory::handles::{ycbcr_writes_set, HANDLE_YCBCR_WRITES};
let h = cx.operand(fb, handle)?;
let HeapFlags(h) = heap_flags(cx, fb, h)?;
let bit = u32s(fb, 1, HANDLE_YCBCR_WRITES)?;
let flag = fb.binary(BinOp::BitwiseAnd, h, bit)?;
let zero = u32s(fb, 1, 0)?;
let flagged = fb.binary(BinOp::INotEqual, flag, zero)?;
let set = ycbcr_writes_set(fb, cx.plan.stage)?;
let is = fb.binary(BinOp::LogicalAnd, set, flagged)?;
let one = f32s(fb, 1, 1.0)?;
let shadow = fb.composite_insert(one, x, &[3])?;
Ok((is, shadow))
}
/// Image texel `x` (four `f32` lanes) of a storage access through heap handle `handle`, as
/// [`alpha_in_red`] converts it (`read`: the image's to Metal's; else Metal's to the image's) where
/// the handle's class index is `A8Unorm`'s (`metal::texel_format::heap_alpha_in_red_index`), as
@@ -3054,6 +3092,12 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul
};
// An integer texel's lanes, saturated to the format's channels as Metal stores them.
let texel = saturated(cx, fb, &decl, (w.saturate, w.texel), texel)?;
// A 4:4:4 two-plane YCbCr member's write shadow: the texel's red, green and blue as written,
// and the mark, in place of any member's conversion below.
let marked = match (w.heap_ycbcr, w.image) {
(true, ImageRef::Heap { handle, .. }) => Some(heap_ycbcr_mark(cx, fb, handle, texel)?),
_ => None,
};
// An `A8Unorm` storage member's alpha, stored in its image's red.
let texel = match (w.heap_alpha_red, w.image) {
(true, ImageRef::Heap { handle, .. }) => heap_alpha_in_red(cx, fb, handle, texel, false)?,
@@ -3067,6 +3111,10 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul
}
ImageRef::Slot(_) => texel,
};
let texel = match marked {
Some((is, shadow)) => fb.select(is, shadow, texel)?,
None => texel,
};
// The write's notes account for the texel's stored NaN (`moves_unfolded`).
fb.module().note_stored_texel(texel);
let mem = texel_memory(cx, fb, &w.image)?;
@@ -531,6 +531,13 @@ pub struct Write {
/// exchanges red and blue where the handle's class and red-blue order name a member the heap
/// views through its storage choice's alias ([`heap_storage_conversions`]).
pub heap_conversions: HeapConversions,
/// A `float` or `half` texel of four lanes written through a heap handle of a 2D texture:
/// where the handle carries its entry's `FLAG_YCBCR_WRITES` (a 4:4:4 two-plane YCbCr member
/// whose element is its write shadow, `bind::heap`) under the stage's
/// `SpecKey::HeapYCbCrWrites`, the write stores the texel's red, green and blue as the
/// function wrote them and alpha 1, the mark a slot of the texture writes
/// (`StorageImageClass::YCbCrWrite`), in place of the converted texel ([`heap_ycbcr_writes`]).
pub heap_ycbcr: bool,
/// The slot is one of `LoweringInputs::swizzled_storage`: the write undoes the bound
/// texture's swizzle on its held value, before converting it, under the slot's
/// `TextureSwizzle` specialization (`emit::unswizzled`).
@@ -932,6 +939,11 @@ impl TextureStrategy {
0
}
+ w.heap_conversions.words(false)
+ if w.heap_ycbcr {
emit::HEAP_YCBCR_WRITE_WORDS
} else {
0
}
+ if w.cross.is_some() { 48 } else { 0 }
+ w.saturate.words()
}
@@ -3707,6 +3719,8 @@ fn select_write(
if !heap_conversions.srgb.is_empty() {
cx.precision.insert(PrecisionNote::DevicePackConversion);
}
// A 4:4:4 two-plane YCbCr member's write shadow, marked where the handle carries its flag.
let heap_ycbcr = heap_ycbcr_writes(cx, image, shape, texel);
// A constant texel none of whose lanes is a NaN stores none, whatever the device's encoding.
let nans = !holds_no_nan(cx, value);
if texel.conv == TexelConv::F32 {
@@ -3744,12 +3758,38 @@ fn select_write(
class,
heap_alpha_red,
heap_conversions,
heap_ycbcr,
swizzle,
cross,
saturate,
}))
}
/// Whether a write of `texel` through `image` of shape `shape` marks a 4:4:4 two-plane YCbCr
/// member's write shadow ([`Write::heap_ycbcr`]): a `float` or `half` texel of four lanes through a
/// heap handle of a 2D texture, neither arrayed nor multisampled, the one class whose array holds
/// such a member (`bind::heap::fit`). The handle-table search then carries the entry's
/// `FLAG_YCBCR_WRITES` under the stage's `SpecKey::HeapYCbCrWrites`
/// (`memory::handles::Lookup::Flagged`'s `ycbcr`).
fn heap_ycbcr_writes(
cx: &mut SelectCx<'_>,
image: ImageRef,
shape: ImageShape,
texel: TexelForm,
) -> bool {
let applies = image.heap()
&& matches!(texel.conv, TexelConv::F32 | TexelConv::F16)
&& texel.lanes == 4
&& shape.dim == ImageDim::D2
&& !shape.array
&& !shape.ms
&& !shape.depth;
if applies {
cx.families.access.heap_ycbcr_writes = true;
}
applies
}
/// How a write of `texel` (the image's own class's form) to `image` saturates its lanes
/// ([`IntRange`]): an integer texel's to the widths of the format the slot's storage choice
/// declares, or, where it declares none, to those the binder pushes for the bound texture. A
@@ -1414,6 +1414,16 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
u.atomic |= h.uses.atomic;
}
}
// A storage class the function reads: the planner refuses a texture whose writes Metal drops
// or stores through its write shadow that the stage reaches there, whose read is not measured.
for (class, u) in &class_uses {
if class.access == ImageAccess::Storage && u.read {
facts.push(RuntimeFact::HeapStorageReads {
stage: cx.stage,
class: *class,
});
}
}
let volatile_classes: Vec<ImageHandleClass> = class_uses
.iter()
.filter(|(class, u)| forwards(cx, u, class.dim == SymDim::Buffer))
+282 -35
View File
@@ -48,6 +48,16 @@
//! read selects its out-of-bounds alpha by. An element is below [`TABLE_CAPACITY`], so the bit is
//! never an element's.
//!
//! **YCbCr writes**. A texture entry's flags carry [`FLAG_YCBCR_WRITES`] when the resident
//! texture's pixel format is a 4:4:4 two-plane YCbCr one whose writes Metal stores into its planes
//! (`metal::format::ycbcr_writes_stored`), whose element in the heap's float storage array is its
//! write shadow (`bind::heap`). A module with a `float` or `half` write through a heap handle
//! calls the search's flagged form with `ycbcr`: the handle carries the flag in bit 29
//! ([`HANDLE_YCBCR_WRITES`]), by which the write marks the texel it stores there, as a slot of the
//! texture marks it. The search carries the flag only under the stage's `SpecKey::HeapYCbCrWrites`
//! ([`ycbcr_writes_spec`]): a pipeline specialized where the command names no such texture carries
//! and loads nothing for it.
//!
//! **Border texels**. A texture entry's flags also hold Metal's border texels of the resident
//! texture, its pixel format's and swizzle's ([`FLAG_BORDER_TEXELS`]), which a Metal 4.1 read
//! through a sampler hands back at an index outside the level on a border axis. A module with such
@@ -81,11 +91,13 @@ use crate::memory::leaf::k32;
use crate::memory::views::{self, View};
use crate::pipeline::sym::ImageAccess;
use crate::pipeline::sym::ResourceSlot;
use crate::pipeline::sym::{SpecKey, Stage};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{FuncId, GlobalId as SGlobalId, TypeId, Value as SValue};
use crate::spirv::ids::{ConstId, FuncId, GlobalId as SGlobalId, TypeId, Value as SValue};
use crate::spirv::ir::{
natural_layout, BinOp, ConvOp, LayoutRule, MemAccess, StorageClass, Type as SType,
natural_layout, BinOp, ConstBits, Constant, ConvOp, LayoutRule, MemAccess, SpecOp,
StorageClass, Type as SType,
};
use super::abi_index::AbiIndex;
@@ -393,8 +405,8 @@ pub const ENTRY_ELEMENT: u32 = 2;
/// Word of an entry holding the flags: for a sampler, its
/// [`SamplerWord`](crate::metal::sampler::SamplerWord); for a texture,
/// [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`], [`FLAG_RED_BLUE`], its border texels in
/// [`FLAG_BORDER_TEXELS`], and the index of its texel class in [`FLAG_TEXEL_CLASS`], every other
/// bit 0.
/// [`FLAG_BORDER_TEXELS`], [`FLAG_YCBCR_WRITES`], and the index of its texel class in
/// [`FLAG_TEXEL_CLASS`], every other bit 0.
pub const ENTRY_FLAGS: u32 = 3;
/// The flag of a texture entry whose pixel format has no alpha
/// (`metal::format::out_of_bounds_alpha_one`): Metal's out-of-bounds read of such a texture
@@ -409,6 +421,14 @@ pub const FLAG_OUT_OF_BOUNDS_ALPHA_ONE: u32 = 1 << 1;
/// (`bind::heap::storage_conversions`). A handle carries it beside its class
/// ([`HANDLE_RED_BLUE`]).
pub const FLAG_RED_BLUE: u32 = 1 << 2;
/// The flag of a texture entry whose pixel format is a 4:4:4 two-plane YCbCr one whose writes
/// Metal stores into both its planes (`metal::format::ycbcr_writes_stored`): the heap's float
/// storage array holds such a member's write shadow (`bind::heap`), and a `float` or `half` write
/// through its handle stores the texel's red, green and blue there with alpha 1, the mark the
/// shadow's encoding reads as written, as a slot of the texture writes its texel
/// (`StorageImageClass::YCbCrWrite`). A handle carries it in [`HANDLE_YCBCR_WRITES`], in a module
/// whose search carries it ([`Lookup::Flagged`]'s `ycbcr`).
pub const FLAG_YCBCR_WRITES: u32 = 1 << 15;
/// The field of a texture entry's flags holding the index of its texel class in
/// `metal::texel_format::heap_classes`: the class a slot bound to the texture would state in its
/// `TexelFormat` specialization, `OTHER` (index 0) for a swizzled texture, by which a function
@@ -426,6 +446,10 @@ pub const HANDLE_ALPHA_ONE: u32 = 1 << 31;
/// The bit of a heap handle that carries its entry's [`FLAG_RED_BLUE`], in a module whose search
/// carries the texel class ([`Lookup::Flagged`]'s `class`).
pub const HANDLE_RED_BLUE: u32 = 1 << 30;
/// The bit of a heap handle that carries its entry's [`FLAG_YCBCR_WRITES`], in a module whose
/// search carries it ([`Lookup::Flagged`]'s `ycbcr`) where the stage's `SpecKey::HeapYCbCrWrites`
/// is set ([`ycbcr_writes_spec`]).
pub const HANDLE_YCBCR_WRITES: u32 = 1 << 29;
/// The field of a texture entry's flags holding Metal's border texels of its texture
/// (`metal::sampler::border_texels` of its pixel format and swizzle, the layout of a slot's
/// `BorderTexels` specialization moved up by the field's first bit): bit `3c + b` of the field is
@@ -448,6 +472,13 @@ const _: () = assert!((FLAG_TEXEL_CLASS | FLAG_OUT_OF_BOUNDS_ALPHA_ONE) & FLAG_R
const _: () = assert!(
(FLAG_TEXEL_CLASS | FLAG_OUT_OF_BOUNDS_ALPHA_ONE | FLAG_RED_BLUE) & FLAG_BORDER_TEXELS == 0
);
const _: () =
assert!((HANDLE_TEXEL_CLASS | HANDLE_ALPHA_ONE | HANDLE_RED_BLUE) & HANDLE_YCBCR_WRITES == 0);
const _: () = assert!(
(FLAG_TEXEL_CLASS | FLAG_OUT_OF_BOUNDS_ALPHA_ONE | FLAG_RED_BLUE | FLAG_BORDER_TEXELS)
& FLAG_YCBCR_WRITES
== 0
);
const _: () = assert!(TABLE_CAPACITY <= 1 << HANDLE_ENTRY.trailing_zeros());
const _: () = assert!(TABLE_CAPACITY <= 1 << HANDLE_ENTRY.count_ones());
@@ -1262,6 +1293,9 @@ pub struct Table {
/// in one instruction; `None` for a word view `{ u32 words[]; }`, which compares an id's two
/// words.
u64_ty: Option<TypeId>,
/// The stage whose table it is: its search carries [`FLAG_YCBCR_WRITES`] under the stage's
/// `SpecKey::HeapYCbCrWrites` ([`ycbcr_writes_spec`]).
stage: Stage,
}
/// Declare the handle table at binding symbol `sym`: an entry array when `int64` (the profile
@@ -1273,6 +1307,7 @@ pub fn declare_table(mb: &mut ModuleBuilder, sym: ResourceSlot, int64: bool) ->
global: v.global,
u32_ty: v.u32_ty,
u64_ty: None,
stage: sym.stage,
});
}
let int = |width| SType::Int {
@@ -1300,6 +1335,7 @@ pub fn declare_table(mb: &mut ModuleBuilder, sym: ResourceSlot, int64: bool) ->
global,
u32_ty,
u64_ty: Some(u64_ty),
stage: sym.stage,
})
}
@@ -1344,24 +1380,29 @@ pub enum Lookup {
/// shader-checked heap read observes the alpha; where `class`, its [`FLAG_TEXEL_CLASS`] in
/// [`HANDLE_TEXEL_CLASS`], the handle of a module that reads a heap texture's texel class;
/// where `red_blue`, its [`FLAG_RED_BLUE`] in [`HANDLE_RED_BLUE`], the handle of a module whose
/// storage access converts a member by it (`bind::heap::storage_conversions`). Every heap
/// access masks them off ([`Lookup::element_mask`]).
/// storage access converts a member by it (`bind::heap::storage_conversions`); where `ycbcr`,
/// its [`FLAG_YCBCR_WRITES`] in [`HANDLE_YCBCR_WRITES`] under the stage's
/// `SpecKey::HeapYCbCrWrites` ([`ycbcr_writes_spec`]), the handle of a module with a `float`
/// or `half` write through a heap handle. Every heap access masks them off
/// ([`Lookup::element_mask`]).
Flagged {
alpha: bool,
class: bool,
red_blue: bool,
ycbcr: bool,
},
/// The entry's element with the entry's index beside it, in [`HANDLE_ENTRY`] (0 for a miss,
/// the null entry's): the handle of a module whose read through a sampler of a heap texture
/// may hand back its border texels, which its entry holds ([`FLAG_BORDER_TEXELS`],
/// [`border_texels`]). The handle has no room for them beside the flags `Flagged` carries, so
/// it carries none: a use reads the ones its module reads (`alpha`, `class` and `red_blue`
/// as `Flagged`'s) from the entry, in the handle `Flagged` would have yielded
/// it carries none: a use reads the ones its module reads (`alpha`, `class`, `red_blue` and
/// `ycbcr` as `Flagged`'s) from the entry, in the handle `Flagged` would have yielded
/// ([`flagged_handle`]). Every heap access masks the index off ([`Lookup::element_mask`]).
Indexed {
alpha: bool,
class: bool,
red_blue: bool,
ycbcr: bool,
},
/// The index of the entry found, 0 (the null entry) for a miss: the handle of an argument
/// buffer's sampler, whose uses read the entry's element and word ([`entry_field`]).
@@ -1377,11 +1418,13 @@ impl Lookup {
alpha,
class,
red_blue,
ycbcr,
}
| Lookup::Indexed {
alpha,
class,
red_blue,
ycbcr,
}) = self
else {
return Vec::new();
@@ -1395,7 +1438,24 @@ impl Lookup {
FLAG_RED_BLUE,
HANDLE_RED_BLUE.trailing_zeros() - FLAG_RED_BLUE.trailing_zeros(),
));
alpha.into_iter().chain(class).chain(red_blue).collect()
let ycbcr = ycbcr.then_some((
FLAG_YCBCR_WRITES,
HANDLE_YCBCR_WRITES.trailing_zeros() - FLAG_YCBCR_WRITES.trailing_zeros(),
));
alpha
.into_iter()
.chain(class)
.chain(red_blue)
.chain(ycbcr)
.collect()
}
/// Whether the handle this form yields carries [`FLAG_YCBCR_WRITES`] in
/// [`HANDLE_YCBCR_WRITES`] (`Flagged`'s `ycbcr`), under the stage's `SpecKey::HeapYCbCrWrites`:
/// its element mask clears the bit only there ([`ycbcr_element_mask`]). An `Indexed` handle
/// carries the entry's index in that bit's place, which its mask clears whatever the constant.
pub fn carries_ycbcr(self) -> bool {
matches!(self, Lookup::Flagged { ycbcr: true, .. })
}
/// The bits of a handle this form yields that are its element, where it carries anything
@@ -1415,16 +1475,20 @@ impl Lookup {
}
/// `word` with each of `form`'s carried fields of the entry flags `flags` (both `u32`) moved into
/// its handle bits ([`Lookup::carried`]).
/// its handle bits ([`Lookup::carried`]): [`FLAG_YCBCR_WRITES`] where `stage`'s
/// `SpecKey::HeapYCbCrWrites` is set ([`ycbcr_flag_mask`]).
fn carry(
fb: &mut FunctionBuilder<'_>,
word: SValue,
flags: SValue,
form: Lookup,
(form, stage): (Lookup, Stage),
) -> BResult<SValue> {
let mut word = word;
for (carried_flags, shift) in form.carried() {
let mask = k32(fb, carried_flags)?;
let mask = match carried_flags {
FLAG_YCBCR_WRITES => ycbcr_flag_mask(fb, stage)?,
_ => k32(fb, carried_flags)?,
};
let carried = fb.binary(BinOp::BitwiseAnd, flags, mask)?;
let shift = k32(fb, shift)?;
let carried = fb.binary(BinOp::ShiftLeftLogical, carried, shift)?;
@@ -1454,7 +1518,80 @@ pub fn flagged_handle(
let mask = k32(fb, !HANDLE_ENTRY)?;
let element = fb.binary(BinOp::BitwiseAnd, h, mask)?;
let flags = entry_field(fb, t, k, EntryField::Flags)?;
carry(fb, element, flags, form)
carry(fb, element, flags, (form, t.stage))
}
/// The stage's `SpecKey::HeapYCbCrWrites`, a `u32` specialization constant: 1 where a texture the
/// stage's handles can name is one whose writes a heap stores into its write shadow
/// ([`FLAG_YCBCR_WRITES`]), which a plan gives from the command's heap members
/// (`bind::plan::slots::heap_ycbcr_writes`), else 0. It defaults to 1, every such write marked,
/// where nothing specializes it.
pub fn ycbcr_writes_spec(fb: &mut FunctionBuilder<'_>, stage: Stage) -> BResult<ConstId> {
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
fb.module()
.spec(SpecKey::HeapYCbCrWrites(stage), u32_, ConstBits(1))
}
/// The `u32` constant `v`, as a module constant.
fn k32_const(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult<ConstId> {
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
fb.module().constant(Constant::Scalar {
ty: u32_,
bits: ConstBits(u64::from(v)),
})
}
/// The mask of the entry flags a search carries [`FLAG_YCBCR_WRITES`] by: the flag where `stage`'s
/// `SpecKey::HeapYCbCrWrites` is 1, else 0, a constant fixed at pipeline creation, so a pipeline
/// specialized for a command whose handles name no such texture carries nothing for it.
fn ycbcr_flag_mask(fb: &mut FunctionBuilder<'_>, stage: Stage) -> BResult<SValue> {
let spec = ycbcr_writes_spec(fb, stage)?;
let flag = k32_const(fb, FLAG_YCBCR_WRITES)?;
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let mask = fb.module().spec_op(SpecOp::IMul, u32_, &[spec, flag])?;
fb.module().const_value(mask)
}
/// The element mask of a handle whose search may carry [`HANDLE_YCBCR_WRITES`] (`mask`, which
/// clears it, [`Lookup::element_mask`]): `mask` where `stage`'s `SpecKey::HeapYCbCrWrites` is 1,
/// else `mask` with the bit set, which no handle then carries, a constant fixed at pipeline
/// creation (all bits set where the search carries nothing else, an `and` a compiler drops).
pub fn ycbcr_element_mask(
fb: &mut FunctionBuilder<'_>,
stage: Stage,
mask: u32,
) -> BResult<SValue> {
let spec = ycbcr_writes_spec(fb, stage)?;
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let open = k32_const(fb, mask | HANDLE_YCBCR_WRITES)?;
let minus = k32_const(fb, 0u32.wrapping_sub(HANDLE_YCBCR_WRITES))?;
let cleared = fb.module().spec_op(SpecOp::IMul, u32_, &[spec, minus])?;
let mask = fb.module().spec_op(SpecOp::IAdd, u32_, &[open, cleared])?;
fb.module().const_value(mask)
}
/// Whether `stage`'s `SpecKey::HeapYCbCrWrites` is set, a `bool` constant fixed at pipeline
/// creation: a write that tests [`HANDLE_YCBCR_WRITES`] under it is dead code where it is not.
pub fn ycbcr_writes_set(fb: &mut FunctionBuilder<'_>, stage: Stage) -> BResult<SValue> {
let spec = ycbcr_writes_spec(fb, stage)?;
let bool_ = fb.module().ty(SType::Bool)?;
let zero = k32_const(fb, 0)?;
let set = fb
.module()
.spec_op(SpecOp::ULessThan, bool_, &[zero, spec])?;
fb.module().const_value(set)
}
/// The border texels of the texture of the [`Lookup::Indexed`] handle `h` (a `u32`) of the
@@ -1620,7 +1757,7 @@ pub fn lookup(
_ if form.carried().is_empty() => element,
_ => {
let flags = entry_field(fb, t, base, EntryField::Flags)?;
carry(fb, element, flags, form)?
carry(fb, element, flags, (form, t.stage))?
}
};
let neutral = k32(fb, NEUTRAL_ELEMENT)?;
@@ -1920,29 +2057,35 @@ mod tests {
/// and beyond them) gets [`lookup_host`]'s element, through an entry array (`u64` ids) and a
/// word view. [`Lookup::Flagged`] also carries a found entry's [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`]
/// in [`HANDLE_ALPHA_ONE`] where it carries the alpha, its texel class where it carries that,
/// and its [`FLAG_RED_BLUE`] in [`HANDLE_RED_BLUE`] where it carries that, carrying no other
/// bit of the entry; [`Lookup::Indexed`] carries the found entry's index in [`HANDLE_ENTRY`]
/// beside the element, whatever flags its uses read; and [`Lookup::Entry`] yields the index
/// of the last entry of the key's id, 0 for a miss.
/// its [`FLAG_RED_BLUE`] in [`HANDLE_RED_BLUE`] where it carries that, and its
/// [`FLAG_YCBCR_WRITES`] in [`HANDLE_YCBCR_WRITES`] where it carries that (the stage's
/// `SpecKey::HeapYCbCrWrites` at its default), carrying no other bit of the entry;
/// [`Lookup::Indexed`] carries the found entry's index in [`HANDLE_ENTRY`] beside the element,
/// whatever flags its uses read; and [`Lookup::Entry`] yields the index of the last entry of
/// the key's id, 0 for a miss.
#[test]
fn the_emitted_search_matches_the_host_model() {
for int64 in [true, false] {
let flagged = |alpha, class, red_blue| Lookup::Flagged {
let flagged = |alpha, class, red_blue, ycbcr| Lookup::Flagged {
alpha,
class,
red_blue,
ycbcr,
};
for form in [
Lookup::Element,
flagged(true, false, false),
flagged(false, true, false),
flagged(false, false, true),
flagged(true, true, false),
flagged(true, true, true),
flagged(true, false, false, false),
flagged(false, true, false, false),
flagged(false, false, true, false),
flagged(false, false, false, true),
flagged(true, true, false, false),
flagged(true, true, true, false),
flagged(true, true, true, true),
Lookup::Indexed {
alpha: true,
class: true,
red_blue: false,
ycbcr: true,
},
Lookup::Entry,
] {
@@ -1951,34 +2094,130 @@ mod tests {
}
}
/// A search that carries [`FLAG_YCBCR_WRITES`] carries it only under the stage's
/// `SpecKey::HeapYCbCrWrites`: over the CPU interpreter, every key of a table of 17 entries
/// gets [`HANDLE_YCBCR_WRITES`] beside its element exactly where its entry has the flag and
/// the constant is 1 (given, or at its default), and its element alone where it is 0; the
/// constant's element mask clears the bit where it is 1 and leaves every bit where it is 0.
#[test]
fn a_search_carries_the_ycbcr_flag_only_under_its_constant() {
use crate::pipeline::sym::{ResourceKind, ResourceSlot};
use crate::spirv::interp::{run, Buffer, Config, Resources};
let sym = |index| ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index,
};
let form = Lookup::Flagged {
alpha: false,
class: false,
red_blue: false,
ycbcr: true,
};
let t = table(17);
let bytes = table_bytes(&t);
assert!(
t.iter().any(|(_, e)| flags(*e) & FLAG_YCBCR_WRITES != 0)
&& t.iter()
.any(|(_, e)| *e != 0 && flags(*e) & FLAG_YCBCR_WRITES == 0),
"the flag occurs set and clear"
);
for int64 in [true, false] {
// The search's handle, then its element through the constant's mask.
let m = search_module(int64, form, |fb, _, h| {
let mask = ycbcr_element_mask(fb, Stage::Kernel, !HANDLE_YCBCR_WRITES)?;
Ok(vec![h, fb.binary(BinOp::BitwiseAnd, h, mask)?])
})
.expect("module");
for spec in [None, Some(0u64), Some(1)] {
for chunk in keys(&t).chunks(KEYS as usize) {
let mut io: Vec<u8> = Vec::new();
for i in 0..KEYS as usize {
let id = chunk.get(i).copied().unwrap_or(0);
io.extend((id as u32).to_le_bytes());
io.extend(((id >> 32) as u32).to_le_bytes());
}
io.extend(vec![0xAA; 8 * KEYS as usize]);
let res = Resources {
buffers: vec![
Buffer {
slot: Some(sym(0)),
address: None,
bytes: bytes.clone(),
},
Buffer {
slot: Some(sym(1)),
address: None,
bytes: io,
},
],
push: Vec::new(),
spec: spec
.map(|v| (SpecKey::HeapYCbCrWrites(Stage::Kernel), v))
.into_iter()
.collect(),
};
let out = run(&m, &Config::default(), res).expect("run");
let io = &out.buffers[1];
let word = |w: usize| {
let at = 4 * (2 * KEYS as usize + w);
u32::from_le_bytes(io[at..at + 4].try_into().expect("word"))
};
for (i, id) in chunk.iter().enumerate() {
let e = lookup_host(&t, *id);
let carried = spec != Some(0) && flags(e) & FLAG_YCBCR_WRITES != 0;
let want = match carried {
true => e | HANDLE_YCBCR_WRITES,
false => e,
};
let what = format!("int64 {int64} spec {spec:?} id {id:#x}");
assert_eq!(word(2 * i), want, "{what}");
assert_eq!(word(2 * i + 1), e, "{what}: the element");
}
}
}
}
}
/// Each flagged form's element mask clears exactly the bits it carries.
#[test]
fn a_flagged_handle_masks_off_the_bits_it_carries() {
let flagged = |alpha, class, red_blue| {
let flagged = |alpha, class, red_blue, ycbcr| {
Lookup::Flagged {
alpha,
class,
red_blue,
ycbcr,
}
.element_mask()
};
assert_eq!(Lookup::Element.element_mask(), None);
assert_eq!(Lookup::Entry.element_mask(), None);
assert_eq!(flagged(false, false, false), None);
assert_eq!(flagged(true, false, false), Some(!HANDLE_ALPHA_ONE));
assert_eq!(flagged(false, false, false, false), None);
assert_eq!(flagged(true, false, false, false), Some(!HANDLE_ALPHA_ONE));
assert_eq!(HANDLE_TEXEL_CLASS, 0x1fff << 16);
assert_eq!(flagged(false, true, false), Some(!HANDLE_TEXEL_CLASS));
assert_eq!(flagged(false, false, true), Some(!HANDLE_RED_BLUE));
assert_eq!(
flagged(true, true, true),
Some(!(HANDLE_ALPHA_ONE | HANDLE_TEXEL_CLASS | HANDLE_RED_BLUE)),
flagged(false, true, false, false),
Some(!HANDLE_TEXEL_CLASS)
);
assert_eq!(flagged(false, false, true, false), Some(!HANDLE_RED_BLUE));
assert_eq!(
flagged(false, false, false, true),
Some(!HANDLE_YCBCR_WRITES)
);
assert_eq!(
flagged(true, true, true, true),
Some(!(HANDLE_ALPHA_ONE | HANDLE_TEXEL_CLASS | HANDLE_RED_BLUE | HANDLE_YCBCR_WRITES)),
"every carried field is masked off, and the element's 16 bits stay"
);
for (alpha, class, red_blue) in [(false, false, false), (true, true, true)] {
for (alpha, class, red_blue, ycbcr) in
[(false, false, false, false), (true, true, true, true)]
{
let indexed = Lookup::Indexed {
alpha,
class,
red_blue,
ycbcr,
};
assert_eq!(
indexed.element_mask(),
@@ -1989,8 +2228,8 @@ mod tests {
}
/// The flags of the test tables' entry of `element`: none on the null entry, else its low six
/// bits and a class index of it, so each carried flag occurs set and clear, beside bits no
/// form carries.
/// bits, a class index of it, and [`FLAG_YCBCR_WRITES`] where its bit 4 is set, so each
/// carried flag occurs set and clear, beside bits no form carries.
fn flags(element: u32) -> u32 {
if element == NEUTRAL_ELEMENT {
return 0;
@@ -1998,6 +2237,7 @@ mod tests {
(element % 64)
| ((element.wrapping_mul(2_654_435_761) >> 7) & FLAG_TEXEL_CLASS)
| ((element.wrapping_mul(40_503) << 3) & FLAG_BORDER_TEXELS)
| ((element & 16) << 11)
}
/// The bytes of table `t`, each entry's flags [`flags`] of its element.
@@ -2025,16 +2265,20 @@ mod tests {
index,
};
for int64 in [true, false] {
for (alpha, class, red_blue) in [(true, true, true), (false, true, false)] {
for (alpha, class, red_blue, ycbcr) in
[(true, true, true, true), (false, true, false, false)]
{
let indexed = Lookup::Indexed {
alpha,
class,
red_blue,
ycbcr,
};
let flagged = Lookup::Flagged {
alpha,
class,
red_blue,
ycbcr,
};
let m = search_module(int64, indexed, |fb, t, h| {
Ok(vec![
@@ -2084,6 +2328,7 @@ mod tests {
let want = e
| carried(alpha, FLAG_OUT_OF_BOUNDS_ALPHA_ONE, HANDLE_ALPHA_ONE)
| carried(red_blue, FLAG_RED_BLUE, HANDLE_RED_BLUE)
| carried(ycbcr, FLAG_YCBCR_WRITES, HANDLE_YCBCR_WRITES)
| match class {
true => flags(e) & FLAG_TEXEL_CLASS,
false => 0,
@@ -2160,9 +2405,11 @@ mod tests {
alpha,
class,
red_blue,
ycbcr,
} => {
e | carried(alpha, FLAG_OUT_OF_BOUNDS_ALPHA_ONE, HANDLE_ALPHA_ONE)
| carried(red_blue, FLAG_RED_BLUE, HANDLE_RED_BLUE)
| carried(ycbcr, FLAG_YCBCR_WRITES, HANDLE_YCBCR_WRITES)
| match class {
true => flags(e) & FLAG_TEXEL_CLASS,
false => 0,
+9 -6
View File
@@ -2152,8 +2152,9 @@ pub fn ycbcr(pf: PixelFormat) -> bool {
/// binding), and the packed ones, `YCBCR10_444_2P_PACKED` and its `_sRGB` twin among them (the
/// M3 Max under macOS 27.0.1, our probe `ycw` over `p444` and `pf44` surfaces: every byte of both
/// planes kept, the command buffer completed; an Apple M4 stores them). A storage slot a function
/// only writes takes its neutral there (`bind::plan`), which the writes leave as Metal leaves the
/// texture.
/// only writes takes its neutral there (`bind::plan`), and so does a heap's storage class
/// (`bind::heap`, an argument buffer's texture, whose writes Metal drops alike: the M3 Max under
/// macOS 27.0.1, `YCBCR8_420_2P`), which the writes leave as Metal leaves the texture.
///
/// An unpacked 4:4:4 YCbCr format's writes are not dropped: Metal stores each texel's codes into
/// both planes, which a slot that only writes one of [`ycbcr_writes_stored`]
@@ -2167,10 +2168,12 @@ pub fn writes_dropped(pf: PixelFormat) -> bool {
/// Whether a function's writes to a two-plane YCbCr texture of `pf` ([`ycbcr`]) store into its
/// planes as Metal stores them, at a slot that only writes it
/// (`pipeline::lower_inputs::StorageImageClass::YCbCrWrite`): the 4:4:4 formats of unpacked 8-
/// and 10-bit codes read converted, as codes or through the sRGB curve, `YCBCR8_444_2P`,
/// `YCBCR10_444_2P`, `RGB8_444_2P`, `RGB10_444_2P`, `YCBCR8_444_2P_sRGB` and
/// `YCBCR10_444_2P_sRGB`. Metal stores each written texel's luma code into the luma plane and its
/// (`pipeline::lower_inputs::StorageImageClass::YCbCrWrite`), and through an argument buffer's
/// handle, which a heap's float storage class holds through the texture's write shadow
/// (`bind::heap`; Metal stores the same bytes either way, an Apple M3 Max under macOS 27.0.1):
/// the 4:4:4 formats of unpacked 8- and 10-bit codes read converted, as codes or through the sRGB
/// curve, `YCBCR8_444_2P`, `YCBCR10_444_2P`, `RGB8_444_2P`, `RGB10_444_2P`,
/// `YCBCR8_444_2P_sRGB` and `YCBCR10_444_2P_sRGB`. Metal stores each written texel's luma code into the luma plane and its
/// own chroma pair into the chroma plane, the codes `bind::ycbcr_write` states (an Apple M4 under
/// macOS 27.0.1, and an Apple M3 Max under macOS 26.7, byte for byte the same; the `_sRGB` twins'
/// on an Apple M3 Max under macOS 27.0.1, each channel through the sRGB curve first). Not the
+12
View File
@@ -719,6 +719,18 @@ pub enum RuntimeFact {
/// names, or one resident for the command), `Unsupported { feature: ArgumentBufferTextures,
/// needs: NotImplemented }`.
HeapResidency { stage: Stage },
/// The `stage` function reads members of the heap's storage array of `class` (a `read_write`
/// argument-buffer texture's read). Such an array holds a texture whose writes Metal drops
/// (`metal::format::writes_dropped`) as its neutral, and a 4:4:4 two-plane YCbCr texture whose
/// writes Metal stores into its planes (`metal::format::ycbcr_writes_stored`) as its write
/// shadow, which its writes mark and nothing reads; Metal's read of either through such a
/// texture is not measured, as for a slot that reads one. The planner refuses such a texture
/// the stage reaches in that class (a member the plan names, or one resident for the
/// command), `Unsupported { feature: Format, needs: NotImplemented }`.
HeapStorageReads {
stage: Stage,
class: ImageHandleClass,
},
/// The function samples a texture through the runtime sampler bound to the slot where Metal's
/// anisotropic filter, emulated (`lower::sampler::anisotropic`), reaches the sample: bound to a
/// sampler whose word states anisotropy (`SamplerWord::ANISOTROPIC`, `maxAnisotropy` above 1),
+11
View File
@@ -912,6 +912,17 @@ pub enum SpecKey {
/// the texture's swizzle deciding it (`metal::sampler::border_texels`,
/// `RuntimeFact::BorderTexels`).
BorderTexels(SlotRef),
/// Boolean (`u32`, default 1): a texture the stage's handles can name is a 4:4:4 two-plane
/// YCbCr one whose writes Metal stores into its planes (`metal::format::ycbcr_writes_stored`)
/// that a storage class can hold (its usage writes): a heap member of the command reaching the
/// stage, as for [`HeapYCbCrTextures`](Self::HeapYCbCrTextures), given by a plan
/// (`bind::plan::slots::heap_ycbcr_writes`). A stage with a `float` or `half` write through a
/// heap handle declares it as a constant, under which its handle-table search carries the
/// entry's `memory::handles::FLAG_YCBCR_WRITES` and the write marks the texel it stores in
/// such a member's write shadow (`lower::texture::emit`): where it is 0 the search carries
/// nothing for it and the write's test is dead code at pipeline creation, exactly, since no
/// handle the command names then names such a texture. A pipeline's key carries it.
HeapYCbCrWrites(Stage),
}
impl SpecKey {
@@ -1708,7 +1708,12 @@ declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32)
"{stem}"
);
let converted = if conversions.is_empty() { 0 } else { 700 };
let bound = alpha + converted + if p.fields().leaf.int64 { 1_600 } else { 2_300 };
// And a 4:4:4 two-plane YCbCr member's write shadow marked under the stage's
// `SpecKey::HeapYCbCrWrites` (`memory::handles::FLAG_YCBCR_WRITES`): the flag's
// carry and element mask by the constant, and the write's test and select.
let ycbcr = 100;
let bound =
alpha + converted + ycbcr + if p.fields().leaf.int64 { 1_600 } else { 2_300 };
assert!(
a.module.words.len() <= bound,
"{stem}: {} words over {bound} (alpha in red {a8}, {} conversions)",
@@ -600,6 +600,7 @@ fn a_sampled_heap_writes_each_member_and_its_table() {
alpha: true,
class: false,
red_blue: false,
ycbcr: false,
};
assert_eq!(emitted_lookup_in(bytes, &keys, flagged), alpha);
// The table's element of an id is the element the plan wrote that texture to.
@@ -1156,6 +1157,7 @@ fn table_entries_state_each_members_texel_class() {
alpha: true,
class: false,
red_blue: false,
ycbcr: false,
};
let one = HANDLE_ALPHA_ONE;
assert_eq!(
@@ -1166,6 +1168,7 @@ fn table_entries_state_each_members_texel_class() {
alpha: false,
class: true,
red_blue: false,
ycbcr: false,
};
assert_eq!(
emitted_lookup_in(bytes, &keys, classes),
@@ -1175,6 +1178,7 @@ fn table_entries_state_each_members_texel_class() {
alpha: true,
class: true,
red_blue: false,
ycbcr: false,
};
let entry = |k: u32| k << HANDLE_ENTRY.trailing_zeros();
assert_eq!(
@@ -0,0 +1,464 @@
//! An argument buffer's `write()` to a two-plane YCbCr texture (`bind::heap`,
//! `memory::handles::FLAG_YCBCR_WRITES`).
//!
//! Metal stores such a write as it stores a slot's (an Apple M3 Max under macOS 27.0.1): a 4:4:4
//! format whose writes it stores into both planes (`metal::format::ycbcr_writes_stored`) through
//! the texture's write shadow, whose texels the heap's float storage element holds and a write
//! through the handle marks, and nothing of a format whose writes it drops
//! (`metal::format::writes_dropped`), whose storage element is the class's neutral. The handle
//! carries the entry's flag only under the stage's `SpecKey::HeapYCbCrWrites`, which a plan gives
//! from what the command names: a command that names no such texture keeps its pipeline's key.
//! A stage that reads the storage class (a `read_write` member) refuses such a texture it reaches
//! there, as a slot that reads one is refused. No GPU is used.
use std::collections::BTreeMap;
use std::path::Path;
use crate::bind::{
handle_entry_flags, heap_element, BindState, BindingPlan, Dispatch, HeapElement, ResourceClass,
TextureFacts, UsedResource, WriteSource,
};
use crate::budget::Budget;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::error::{BindError, Error, Feature, Needs, Unsupported};
use crate::library::Library;
use crate::memory::handles::FLAG_YCBCR_WRITES;
use crate::metal::{PixelFormat, TextureType, TextureUsage};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::sym::{
Axis, HandleClass, ImageAccess, ImageHandleClass, ResourceKind, ResourceSlot, SpecKey, Stage,
SyntheticBinding,
};
use crate::pipeline::testing::typed_module;
use crate::pipeline::{
ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, StageSource,
};
use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Resources};
use crate::vk;
use super::engine_binder::assemble_text;
const HEADER: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n";
/// Kernel `heap_ycbcr_write` writes buffer 1's `float4` at its index through the
/// `texture2d<float, write>` argument buffer 0 holds, at `(gid, 0)`; kernel `heap_ycbcr_rw` reads
/// the `read_write` texture argument buffer 0 holds at `(gid, 0)` into buffer 1 and writes buffer
/// 1's `float4` there.
const KERNELS: &str = r#"%struct.T = type { ptr addrspace(1) }
define void @heap_ycbcr_write(ptr addrspace(2) %r, ptr addrspace(1) %src, i32 %gid) {
%pt = getelementptr inbounds %struct.T, ptr addrspace(2) %r, i64 0, i32 0
%t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8
%p = getelementptr inbounds <4 x float>, ptr addrspace(1) %src, i32 %gid
%v = load <4 x float>, ptr addrspace(1) %p, align 16
%c = insertelement <2 x i32> zeroinitializer, i32 %gid, i64 0
call void @air.write_texture_2d.v4f32(ptr addrspace(1) %t, <2 x i32> %c, <4 x float> %v, i32 0, i32 2)
ret void
}
define void @heap_ycbcr_rw(ptr addrspace(2) %r, ptr addrspace(1) %src, i32 %gid) {
%pt = getelementptr inbounds %struct.T, ptr addrspace(2) %r, i64 0, i32 0
%t = load ptr addrspace(1), ptr addrspace(2) %pt, align 8
%p = getelementptr inbounds <4 x float>, ptr addrspace(1) %src, i32 %gid
%v = load <4 x float>, ptr addrspace(1) %p, align 16
%c = insertelement <2 x i32> zeroinitializer, i32 %gid, i64 0
%smp = call ptr addrspace(2) @air.get_read_sampler()
%x = call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) %smp, <2 x i32> %c, <2 x i32> zeroinitializer, i32 0, i32 3)
%xv = extractvalue { <4 x float>, i8 } %x, 0
store <4 x float> %xv, ptr addrspace(1) %p, align 16
call void @air.write_texture_2d.v4f32(ptr addrspace(1) %t, <2 x i32> %c, <4 x float> %v, i32 0, i32 3)
ret void
}
declare ptr addrspace(2) @air.get_read_sampler()
declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32)
declare void @air.write_texture_2d.v4f32(ptr addrspace(1), <2 x i32>, <4 x float>, i32, i32)
!air.kernel = !{!0, !20}
!air.version = !{!9}
!air.language_version = !{!10}
!0 = !{ptr @heap_ycbcr_write, !1, !2}
!1 = !{}
!2 = !{!3, !7, !8}
!3 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !4, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"T", !"air.arg_name", !"r"}
!4 = !{i32 0, i32 8, i32 0, !"texture2d<float, write>", !"t", !"air.indirect_argument", !5}
!5 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.write", !"air.arg_type_name", !"texture2d<float, write>", !"air.arg_name", !"t"}
!7 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"src"}
!8 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"}
!9 = !{i32 2, i32 8, i32 0}
!10 = !{!"Metal", i32 4, i32 0, i32 0}
!20 = !{ptr @heap_ycbcr_rw, !1, !21}
!21 = !{!22, !27, !8}
!22 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !23, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"T", !"air.arg_name", !"r"}
!23 = !{i32 0, i32 8, i32 0, !"texture2d<float, read_write>", !"t", !"air.indirect_argument", !24}
!24 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.arg_type_name", !"texture2d<float, read_write>", !"air.arg_name", !"t"}
!27 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"src"}
"#;
/// The resource IDs of the members: a 4:4:4 YCbCr texture's, and a plain one's.
const YCBCR_ID: u64 = 0x0000_0001_0000_0010;
const PLAIN_ID: u64 = 0x0000_0001_0000_0020;
/// The committed profiles each kernel is tried on; one without a storage heap refuses it.
const STEMS: [&str; 3] = ["lavapipe", "moltenvk-m3", "amd-780m-radv"];
/// The device of committed profile `stem`.
fn device(stem: &str) -> Device {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join(format!("../metal2vulkan-validation/profiles/{stem}.json"));
let text = std::fs::read_to_string(path).expect("profile");
let desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
Device::new(desc, DevicePolicy::default()).expect("device")
}
/// [`KERNELS`], assembled; `None` where `llvm-as` is missing (the test then skips visibly).
fn kernels() -> Option<Vec<u8>> {
assemble_text("heap_ycbcr_writes", &format!("{HEADER}{KERNELS}"))
}
/// Kernel `entry` of `bc` on `dev`, `None` where the device has no heap for it.
fn pipeline(dev: &Device, bc: &[u8], entry: &str) -> Option<ComputePipeline> {
let lib = Library::from_air(bc).expect("library");
let f = lib.function(entry).expect("entry");
let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f)));
match dev.compile_compute_pipeline(&d, &Budget::standard()) {
Ok(p) => Some(p),
Err(Error::Unsupported(u)) if u.feature == Feature::ArgumentBufferTextures => None,
Err(e) => panic!("{entry}: {e}"),
}
}
/// A 2D texture of `pf` and `usage`.
fn facts(pf: PixelFormat, usage: TextureUsage) -> TextureFacts {
let mut f = TextureFacts::new(TextureType::Type2D, pf);
f.usage = usage;
f
}
/// A command making the textures of `members` resident, each with its resource ID.
fn state(members: &[(TextureFacts, u64)]) -> BindState {
BindState {
used_resources: (members.iter().zip(1u32..))
.map(|(&(f, id), token)| {
let mut u = UsedResource::new(ResourceClass::Texture(f), token);
u.resource_id = Some(id);
u
})
.collect(),
..Default::default()
}
}
/// The value `plan` gives `pipe`'s constant of `key`.
fn given(pipe: &ComputePipeline, plan: &BindingPlan, key: SpecKey) -> Option<u64> {
let constant = (pipe.stage.specialization.constants.iter()).find(|c| c.key == key)?;
let entry = (plan.specialization.entries.iter()).find(|e| e.constant_id == constant.id)?;
let at = entry.offset as usize;
let bytes = &plan.specialization.data[at..at + entry.size as usize];
let mut word = [0u8; 8];
word[..bytes.len()].copy_from_slice(bytes);
Some(u64::from_le_bytes(word))
}
/// The heap's float 2D storage class.
fn storage_class() -> ImageHandleClass {
ImageHandleClass {
dim: crate::pipeline::sym::ImageDim::D2,
arrayed: false,
multisampled: false,
sampled_type: crate::pipeline::sym::SampledType::Float,
depth_compare: false,
access: ImageAccess::Storage,
format: crate::pipeline::sym::StorageFormatClass::Unknown,
}
}
const WRITE: TextureUsage = TextureUsage::SHADER_WRITE;
/// A heap write marks a 4:4:4 YCbCr member's write shadow, and only under its constant: end to
/// end on the interpreter, the binder's plan and table bytes for a command making a
/// `YCBCR8_444_2P` texture and an `RGBA32Float` one resident (the YCbCr one's element its write
/// shadow's `R32G32B32A32_SFLOAT` view, its entry flagged `FLAG_YCBCR_WRITES`, the plan giving
/// `SpecKey::HeapYCbCrWrites` 1), and the emitted search and write. Four texels of alpha 0.25
/// written through the YCbCr texture's handle store their red, green and blue and alpha 1, the
/// mark, where the constant is 1, and their alpha where it is 0; through the plain texture's,
/// their alpha under either value.
#[test]
fn a_heap_write_marks_a_ycbcr_member_s_write_shadow_under_its_constant() {
let Some(bc) = kernels() else {
return;
};
let entry = "heap_ycbcr_write";
let key = SpecKey::HeapYCbCrWrites(Stage::Kernel);
let fl = |v: f32| v.to_bits();
let texels: [[f32; 4]; 4] = [
[0.2, 0.6, 0.9, 0.25],
[1.0, 0.0, 0.0, 0.25],
[0.5, 0.5, 0.5, 0.25],
[0.0, 0.0, 1.0, 0.25],
];
let mut ran = 0;
for stem in STEMS {
let dev = device(stem);
let Some(pipe) = pipeline(&dev, &bc, entry) else {
continue;
};
let constant = (pipe.stage.specialization.constants.iter())
.find(|c| c.key == key)
.unwrap_or_else(|| panic!("{stem}: no {key:?} constant"));
assert_eq!(constant.default, 1, "{stem}");
let ycbcr = facts(PixelFormat::YCBCR84442P, WRITE);
let plain = facts(PixelFormat::RGBA32Float, WRITE);
let state = state(&[(ycbcr, YCBCR_ID), (plain, PLAIN_ID)]);
let bplan = pipe.plan(&dev, &state.shape()).expect("plan");
assert_eq!(given(&pipe, &bplan, key), Some(1), "{stem}");
let views: Vec<(u32, vk::Format)> = (bplan.descriptors.iter())
.filter_map(|d| match &d.source {
WriteSource::HeapEntry { element, view, .. } => Some((*element, view.format)),
_ => None,
})
.collect();
assert_eq!(
views,
vec![
(1, vk::Format::R32G32B32A32_SFLOAT),
(2, vk::Format::R32G32B32A32_SFLOAT)
],
"{stem}: the write shadow's float view, and the plain texture's own"
);
let dispatch = Dispatch::Threadgroups {
groups: [4, 1, 1],
threads_per_group: [1, 1, 1],
};
let cmds = bplan
.instantiate_dispatch(&state, &dispatch)
.expect("dispatch");
let (set, binding) = (bplan.descriptors.iter())
.find_map(|d| {
matches!(d.source, WriteSource::HandleTable { .. }).then_some((d.set, d.binding))
})
.expect("a handle table");
let table = (cmds.descriptor_bytes.iter())
.find(|b| (b.set, b.binding) == (set, binding))
.expect("table bytes")
.bytes
.clone();
// The entries past the null one, by ID: the YCbCr texture's flagged, the plain one's not.
let flags: Vec<(u64, u32)> = table
.chunks(16)
.map(|e| {
let word = |w: usize| u32::from_le_bytes(e[4 * w..4 * w + 4].try_into().unwrap());
(u64::from(word(0)) | u64::from(word(1)) << 32, word(3))
})
.filter(|(id, _)| *id != 0)
.collect();
assert_eq!(
flags
.iter()
.map(|(id, f)| (*id, f & FLAG_YCBCR_WRITES))
.collect::<Vec<_>>(),
vec![(YCBCR_ID, FLAG_YCBCR_WRITES), (PLAIN_ID, 0)],
"{stem}"
);
let (plan, m) = typed_module(&bc, entry, dev.profile()).expect("module");
assert!(plan.families.access.heap_ycbcr_writes, "{stem}");
let class = (plan.families.texture.heap.values())
.find_map(|h| h.class)
.expect("a heap class");
assert_eq!(class, storage_class(), "{stem}");
let slot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Heap(HandleClass::Image(class)),
index: 0,
};
let images: Vec<Image> = [(0, 1), (1, 4), (2, 4)]
.into_iter()
.map(|(e, width)| Image::new(slot, [width, 1, 1], 1, 1, 1).at_element(e))
.collect();
let src: Vec<u8> = texels
.iter()
.flatten()
.flat_map(|v| v.to_le_bytes())
.collect();
let buffer = |kind, index, bytes| Buffer {
slot: Some(ResourceSlot {
stage: Stage::Kernel,
kind,
index,
}),
address: None,
bytes,
};
for (id, element) in [(YCBCR_ID, 1usize), (PLAIN_ID, 2)] {
for value in [0u64, 1] {
let mut spec = BTreeMap::new();
for axis in [Axis::X, Axis::Y, Axis::Z] {
spec.insert(SpecKey::LocalSize(axis), 1);
}
spec.insert(SpecKey::FlatLocalSize, 1);
spec.insert(key, value);
let res = Resources {
buffers: vec![
buffer(ResourceKind::Buffer, 0, id.to_le_bytes().to_vec()),
buffer(ResourceKind::Buffer, 1, src.clone()),
buffer(
ResourceKind::Synthetic(SyntheticBinding::HandleTable),
0,
table.clone(),
),
],
push: vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)],
spec,
};
let cfg = Config {
workgroups: [4, 1, 1],
..Config::default()
};
let (_, out) = run_with_images(&m, &cfg, res, images.clone())
.unwrap_or_else(|e| panic!("{stem}: {id:#x} under {value}: {e:?}"));
let marked = id == YCBCR_ID && value == 1;
let want: Vec<[u32; 4]> = texels
.iter()
.map(|&[r, g, b, a]| [fl(r), fl(g), fl(b), fl(if marked { 1.0 } else { a })])
.collect();
assert_eq!(
out[element].texels, want,
"{stem}: {id:#x} under {value}: the stored texels"
);
for other in (0..3).filter(|&e| e != element) {
assert_eq!(
out[other].texels, images[other].texels,
"{stem}: {id:#x} under {value}: element {other} untouched"
);
}
}
}
ran += 1;
}
assert!(ran > 0, "no committed profile has a storage heap");
}
/// The plan gives `SpecKey::HeapYCbCrWrites` 1 exactly where a texture the command makes resident
/// is a 4:4:4 YCbCr one whose writes Metal stores and whose usage writes (`YCBCR8_444_2P`,
/// `RGB10_444_2P` beside an `RGBA8Unorm` one), and 0 where it makes none, plain ones
/// (`RGBA8Unorm`, `RGBA16Float`), one whose writes Metal drops (`YCBCR8_420_2P`), or a 4:4:4 one
/// for reading alone resident: every command of the second kind specializes the pipeline as the
/// others of it do (one key, one variant), so a command that names no such texture makes no new
/// one. The dropped one's storage element is the class's neutral, its entry and the plain ones'
/// unflagged; the stored one's element is its write shadow's float view, its entry flagged.
#[test]
fn a_heap_write_s_ycbcr_constant_is_its_command_s() {
let Some(bc) = kernels() else {
return;
};
let key = SpecKey::HeapYCbCrWrites(Stage::Kernel);
let read = TextureUsage::SHADER_READ;
let cases: [(&[(PixelFormat, TextureUsage)], u64); 7] = [
(&[], 0),
(&[(PixelFormat::RGBA8Unorm, WRITE)], 0),
(&[(PixelFormat::RGBA16Float, WRITE)], 0),
(&[(PixelFormat::YCBCR84202P, WRITE)], 0),
(&[(PixelFormat::YCBCR84442P, read)], 0),
(&[(PixelFormat::YCBCR84442P, WRITE)], 1),
(
&[
(PixelFormat::RGBA8Unorm, WRITE),
(PixelFormat::RGB104442P, WRITE),
],
1,
),
];
let mut planned = 0;
for stem in STEMS {
let dev = device(stem);
let Some(pipe) = pipeline(&dev, &bc, "heap_ycbcr_write") else {
continue;
};
let mut unnamed = Vec::new();
for (members, value) in cases {
let what = format!("{members:?} on {stem}");
let members: Vec<(TextureFacts, u64)> = (members.iter().zip(1u64..))
.map(|(&(pf, usage), i)| (facts(pf, usage), 0x0000_0001_0000_0000 | i << 4))
.collect();
let plan = pipe
.plan(&dev, &state(&members).shape())
.unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(given(&pipe, &plan, key), Some(value), "{what}");
if value == 0 {
unnamed.push((plan.variant.clone(), plan.specialization.clone()));
}
planned += 1;
}
assert!(
unnamed.windows(2).all(|w| w[0] == w[1]),
"{stem}: a command naming no stored YCbCr texture takes another key"
);
// The elements and flags the device-wide heap writes as each texture is made.
let profile = dev.profile();
let class = HandleClass::Image(storage_class());
let layout = vk::ImageLayout::GENERAL;
let dropped = facts(PixelFormat::YCBCR84202P, WRITE);
assert_eq!(
heap_element(profile, &class, &dropped, layout),
Ok(HeapElement::Neutral),
"{stem}"
);
let stored = facts(PixelFormat::YCBCR84442P, WRITE);
match heap_element(profile, &class, &stored, layout) {
Ok(HeapElement::View(v)) => {
assert_eq!(v.format, vk::Format::R32G32B32A32_SFLOAT, "{stem}")
}
other => panic!("{stem}: the stored texture's element {other:?}"),
}
for (pf, flagged) in [
(PixelFormat::YCBCR84442P, true),
(PixelFormat::YCBCR104442PSRGB, true),
(PixelFormat::RGB84442P, true),
(PixelFormat::YCBCR84202P, false),
(PixelFormat::RGBA8Unorm, false),
] {
let flags = handle_entry_flags(&facts(pf, WRITE));
assert_eq!(flags & FLAG_YCBCR_WRITES != 0, flagged, "{pf:?}");
}
}
assert!(planned > 0, "no committed profile has a storage heap");
}
/// A stage that reads the heap's storage class (a `read_write` texture's read) states
/// `RuntimeFact::HeapStorageReads`, and its plan refuses a texture of a dropped or shadowed write
/// it reaches there (`YCBCR8_420_2P`, `YCBCR8_444_2P`), `Unsupported { feature: Format, needs:
/// NotImplemented }`, as a slot that reads one is refused; it plans an `RGBA32Float` one.
#[test]
fn a_heap_storage_read_of_a_ycbcr_texture_is_refused_typed() {
let Some(bc) = kernels() else {
return;
};
let mut planned = 0;
for stem in STEMS {
let dev = device(stem);
let Some(pipe) = pipeline(&dev, &bc, "heap_ycbcr_rw") else {
continue;
};
assert!(
pipe.dependencies.iter().any(|d| d.fact
== RuntimeFact::HeapStorageReads {
stage: Stage::Kernel,
class: storage_class(),
}),
"{stem}: {:?}",
pipe.dependencies
);
let usage = TextureUsage::SHADER_READ | WRITE;
let plan = |pf| pipe.plan(&dev, &state(&[(facts(pf, usage), YCBCR_ID)]).shape());
for pf in [PixelFormat::YCBCR84202P, PixelFormat::YCBCR84442P] {
match plan(pf) {
Err(BindError::Unsupported(Unsupported {
feature: Feature::Format,
needs: Needs::NotImplemented,
..
})) => {}
other => panic!("{stem}: {pf:?}: {other:?}"),
}
}
plan(PixelFormat::RGBA32Float).unwrap_or_else(|e| panic!("{stem}: RGBA32Float: {e}"));
planned += 1;
}
assert!(planned > 0, "no committed profile has a storage heap");
}
+1
View File
@@ -77,6 +77,7 @@ mod engine_half_storage_notes;
mod engine_handles;
mod engine_heap_binder;
mod engine_heap_residency;
mod engine_heap_ycbcr_writes;
mod engine_helper_picks;
mod engine_helper_threads;
mod engine_image_shapes;
@@ -15084,6 +15084,7 @@ variant metal2vulkan::pipeline::RuntimeFact::HeapCrossClassNeutral HeapCrossClas
variant metal2vulkan::pipeline::RuntimeFact::HeapNumericType HeapNumericType { class: ImageHandleClass }
variant metal2vulkan::pipeline::RuntimeFact::HeapRawSamples HeapRawSamples { stage: Stage, sampler: Option<u32> }
variant metal2vulkan::pipeline::RuntimeFact::HeapResidency HeapResidency { stage: Stage }
variant metal2vulkan::pipeline::RuntimeFact::HeapStorageReads HeapStorageReads { stage: Stage, class: ImageHandleClass }
variant metal2vulkan::pipeline::RuntimeFact::HeapWriteRounding HeapWriteRounding { stage: Stage, halves: bool }
variant metal2vulkan::pipeline::RuntimeFact::ImageViewShape ImageViewShape { slot: SlotRef }
variant metal2vulkan::pipeline::RuntimeFact::ImageblockSize ImageblockSize { cell_bytes: u32 }
@@ -15196,6 +15197,7 @@ variant metal2vulkan::pipeline::SpecKey::FlatLocalSize FlatLocalSize
variant metal2vulkan::pipeline::SpecKey::HeapNanFamilies HeapNanFamilies(Stage)
variant metal2vulkan::pipeline::SpecKey::HeapRawTextures HeapRawTextures(Stage)
variant metal2vulkan::pipeline::SpecKey::HeapYCbCrTextures HeapYCbCrTextures(Stage)
variant metal2vulkan::pipeline::SpecKey::HeapYCbCrWrites HeapYCbCrWrites(Stage)
variant metal2vulkan::pipeline::SpecKey::ImageblockHeight ImageblockHeight
variant metal2vulkan::pipeline::SpecKey::ImageblockWidth ImageblockWidth
variant metal2vulkan::pipeline::SpecKey::LocalSize LocalSize(Axis)
Can't render this file because it is too large.
+4 -4
View File
@@ -77,7 +77,7 @@ Columns:
| `QuadOperations` | Quad operations in a stage without quad support | devices without VkLimit::MinSubgroupSize; devices without VkProperty::SubgroupQuadOperationsInAllStages | `device` | 2: `crates/metal2vulkan/src/device/subgroup.rs (subgroup_tier, 2 sites)` | `app`: quad shuffles in kernels on devices without quad operations there |
| `SimdgroupMatrix` | Simdgroup matrix operations | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/simd/matrix.rs (not_implemented)` | `rare`: simdgroup matrix kernels |
| `ArgumentBufferPointers` | Argument buffers holding buffer pointers (dynamic roots) | devices without buffer device addresses (`addressed_needs`) | `device` | 1: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)` | `app`: argument buffers holding buffer pointers |
| `ArgumentBufferTextures` | Argument buffers holding textures or samplers (handle domain) | devices short of a device limit the site names; devices without a capability the site computes (`gaps`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`needs`); every device (not implemented) | `ours` | 17: `crates/metal2vulkan-runtime/src/families/features.rs (tier2)`, `crates/metal2vulkan-runtime/src/pipeline/objects.rs (create_set_layout)` (+10) | `app`: argument buffers holding textures and samplers (bindless) |
| `ArgumentBufferTextures` | Argument buffers holding textures or samplers (handle domain) | devices short of a device limit the site names; devices without a capability the site computes (`gaps`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`needs`); every device (not implemented) | `ours` | 18: `crates/metal2vulkan-runtime/src/families/features.rs (tier2)`, `crates/metal2vulkan-runtime/src/pipeline/objects.rs (create_set_layout)` (+10) | `app`: argument buffers holding textures and samplers (bindless) |
| `ArgumentBufferObjects` | Argument-buffer members that are pipeline states, ICBs, function tables, or acceleration structures | every device (not implemented) | `ours` | 5: `crates/metal2vulkan/src/lower/access/encode.rs (select_command, 3 sites)`, `crates/metal2vulkan/src/memory/provenance.rs (access)` (+1) | `rare`: pipeline states and ICBs in argument buffers |
| `DereferenceLoadedPointer` | Dereferencing a pointer loaded from memory or made from an integer | devices short of a Vulkan feature the site names; devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism) | `device` | 4: `crates/metal2vulkan/src/lower/access/dynamic.rs (plan_misses)`, `crates/metal2vulkan/src/lower/access/local.rs (access_ptr)` (+2) | `app`: pointers loaded from argument buffers |
| `PointerToInteger` | Storing a pointer or converting it to an integer | - | `-` | via a helper: 1: `crates/metal2vulkan/src/lower/access/dynamic.rs (require_addresses)` | `rare`: pointer to integer casts |
@@ -93,7 +93,7 @@ Columns:
| `BufferRange` | A buffer window beyond the descriptor range limits | devices without a capability the site computes (`needs`); devices without buffer device addresses (`addressed_needs`); every device (no Vulkan mechanism) | `device` | 8: `crates/metal2vulkan-runtime/src/function_table.rs (past_storage_buffer_range)`, `crates/metal2vulkan/src/bind/graphics.rs (patch_binding, 3 sites)` (+4) | `app`: a buffer window past a device's descriptor range |
| `Int64Arithmetic` | 64-bit integer arithmetic | devices without VkFeature::ShaderInt64 | `device` | 2: `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)`, `crates/metal2vulkan/src/lower/select.rs (selector_form)` | `rare`: 64-bit integers on a device without shaderInt64 |
| `Float64Arithmetic` | 64-bit float arithmetic | devices without VkFeature::ShaderFloat64 | `device` | 2: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)` | `rare`: doubles (MSL has none outside Apple's own code) |
| `Format` | A pixel format not supported for the required use | devices without VkFeature::ShaderStorageImageExtendedFormats; devices without a capability the site computes; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`c`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`routes`); devices without a format's usage; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 125: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`, `crates/metal2vulkan-runtime/src/blit_fill.rs (fill)` (+82) | `system`: pixel formats a device lacks for a use (CoreVideo's 4:2:x and 10-bit formats among them) |
| `Format` | A pixel format not supported for the required use | devices without VkFeature::ShaderStorageImageExtendedFormats; devices without a capability the site computes; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`c`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`routes`); devices without a format's usage; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 126: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`, `crates/metal2vulkan-runtime/src/blit_fill.rs (fill)` (+83) | `system`: pixel formats a device lacks for a use (CoreVideo's 4:2:x and 10-bit formats among them) |
| `DivergentImplicitLod` | Divergent implicit-LOD sampling or LOD query through a multi-candidate handle | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/sampler/select.rs (tangled)` | `app`: implicit-LOD sampling through a dynamically chosen texture |
| `ImplicitLodOutsideFragment` | Implicit-LOD sampling outside fragment | every device (not implemented) | `ours` | 3: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (query_min_level)`, `crates/metal2vulkan/src/lower/sampler/select.rs (query_level_measured)` (+1) | `rare`: implicit-LOD sampling outside fragment functions |
| `MinLodClamp` | `min_lod_clamp` without `shaderResourceMinLod` | devices without VkFeature::ShaderResourceMinLod; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/sampler/select.rs (min_lod)`, `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)` | `rare`: min_lod_clamp on a device without shaderResourceMinLod |
@@ -609,7 +609,7 @@ Each refusal's sites, with the function that builds it.
- `feature::QuadOperations`: `crates/metal2vulkan/src/device/subgroup.rs (subgroup_tier, 2 sites)`
- `feature::SimdgroupMatrix`: `crates/metal2vulkan/src/lower/simd/matrix.rs (not_implemented)`
- `feature::ArgumentBufferPointers`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`
- `feature::ArgumentBufferTextures`: `crates/metal2vulkan-runtime/src/families/features.rs (tier2)`; `crates/metal2vulkan-runtime/src/pipeline/objects.rs (create_set_layout)`; `crates/metal2vulkan-runtime/src/resource_ids.rs (check_capacity, 2 sites)`; `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/heap.rs (member_view, 4 sites)`; `crates/metal2vulkan/src/bind/heap.rs (new)`; `crates/metal2vulkan/src/lower/access/handle.rs (select)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_sampling)`; `crates/metal2vulkan/src/lower/texture/atomic.rs (select)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap, 2 sites)`; `crates/metal2vulkan/src/pipeline/link.rs (heap_set)`
- `feature::ArgumentBufferTextures`: `crates/metal2vulkan-runtime/src/families/features.rs (tier2)`; `crates/metal2vulkan-runtime/src/pipeline/objects.rs (create_set_layout)`; `crates/metal2vulkan-runtime/src/resource_ids.rs (check_capacity, 2 sites)`; `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/heap.rs (member_view, 5 sites)`; `crates/metal2vulkan/src/bind/heap.rs (new)`; `crates/metal2vulkan/src/lower/access/handle.rs (select)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_sampling)`; `crates/metal2vulkan/src/lower/texture/atomic.rs (select)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap, 2 sites)`; `crates/metal2vulkan/src/pipeline/link.rs (heap_set)`
- `feature::ArgumentBufferObjects`: `crates/metal2vulkan/src/lower/access/encode.rs (select_command, 3 sites)`; `crates/metal2vulkan/src/memory/provenance.rs (access)`; `crates/metal2vulkan/src/memory/provenance.rs (classify)`
- `feature::DereferenceLoadedPointer`: `crates/metal2vulkan/src/lower/access/dynamic.rs (plan_misses)`; `crates/metal2vulkan/src/lower/access/local.rs (access_ptr)`; `crates/metal2vulkan/src/lower/access/local.rs (threadgroup_constant_refusal)`; `crates/metal2vulkan/src/memory/plan.rs (analyze)`
- `feature::PointerToInteger`: `crates/metal2vulkan/src/lower/access/dynamic.rs (require_addresses)`
@@ -625,7 +625,7 @@ Each refusal's sites, with the function that builds it.
- `feature::BufferRange`: `crates/metal2vulkan-runtime/src/function_table.rs (past_storage_buffer_range)`; `crates/metal2vulkan/src/bind/graphics.rs (patch_binding, 3 sites)`; `crates/metal2vulkan/src/bind/graphics.rs (rebind_with)`; `crates/metal2vulkan/src/bind/instantiate.rs (bind_buffers)`; `crates/metal2vulkan/src/lower/access/function_table.rs (select)`; `crates/metal2vulkan/src/lower/access/mod.rs (place_slots)`
- `feature::Int64Arithmetic`: `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)`; `crates/metal2vulkan/src/lower/select.rs (selector_form)`
- `feature::Float64Arithmetic`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)`
- `feature::Format`: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`; `crates/metal2vulkan-runtime/src/blit_fill.rs (fill)`; `crates/metal2vulkan-runtime/src/blit_plan.rs (check_formats, 3 sites)`; `crates/metal2vulkan-runtime/src/blit_plan.rs (pair_unit)`; `crates/metal2vulkan-runtime/src/blit_plan.rs (plan_levels_copy)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (through_buffer)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (shape_over, 3 sites)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (texture_buffer_texel)`; `crates/metal2vulkan-runtime/src/color_resolve.rs (of_attachment)`; `crates/metal2vulkan-runtime/src/copy_plan.rs (colour_unit)`; `crates/metal2vulkan-runtime/src/copy_plan.rs (copy_unit, 2 sites)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs (usable_twin)`; `crates/metal2vulkan-runtime/src/families/features.rs (read_write_tier)`; `crates/metal2vulkan-runtime/src/families/formats.rs (answers, 3 sites)`; `crates/metal2vulkan-runtime/src/families/formats.rs (atomic_gap)`; `crates/metal2vulkan-runtime/src/families/formats.rs (lacking)`; `crates/metal2vulkan-runtime/src/families/formats.rs (none)`; `crates/metal2vulkan-runtime/src/families/formats.rs (probe, 2 sites)`; `crates/metal2vulkan-runtime/src/families/formats.rs (sparse_missing)`; `crates/metal2vulkan-runtime/src/families/formats.rs (unsupported)`; `crates/metal2vulkan-runtime/src/image_plan.rs (plan_held, 3 sites)`; `crates/metal2vulkan-runtime/src/render.rs (viewing)`; `crates/metal2vulkan-runtime/src/render_pass.rs (attachment_format)`; `crates/metal2vulkan-runtime/src/render_pass.rs (check_target)`; `crates/metal2vulkan-runtime/src/render_pass.rs (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs (target)`; `crates/metal2vulkan-runtime/src/resolve.rs (unmodelled_resolve)`; `crates/metal2vulkan-runtime/src/sample_copy.rs (checked_twin)`; `crates/metal2vulkan-runtime/src/sample_copy.rs (plan)`; `crates/metal2vulkan-runtime/src/sample_interleave.rs (interleave_merge)`; `crates/metal2vulkan-runtime/src/shadow.rs (unmerged, 2 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (plan_sparse_texture)`; `crates/metal2vulkan-runtime/src/texture.rs (texture_as)`; `crates/metal2vulkan-runtime/src/texture.rs (two_planes_refused)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs (astc_texels)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs (etc_texels)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs (with_decoded_twin)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (planned_heap_texture)`; `crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs (refused)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (converted_storage)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (new_render_shadow)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (ycbcr_write_shadow)`; `crates/metal2vulkan-runtime/src/two_planes.rs (unmeasured)`; `crates/metal2vulkan-runtime/src/view_plan.rs (check_format, 5 sites)`; `crates/metal2vulkan-runtime/src/ycbcr.rs (refused)`; `crates/metal2vulkan/src/bind/extended_shadow.rs (extended_shadow_module)`; `crates/metal2vulkan/src/bind/plan/resources.rs (extended_sampler)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture, 2 sites)`; `crates/metal2vulkan/src/bind/plan/resources.rs (require_filter_features)`; `crates/metal2vulkan/src/bind/sample_interleave.rs (finish)`; `crates/metal2vulkan/src/bind/sample_interleave.rs (interleave_split_module)`; `crates/metal2vulkan/src/bind/shadow_copy_in.rs (shadow_copy_in_module)`; `crates/metal2vulkan/src/lower/access/tile.rs (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs (select_param, 3 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (extended_range_blend, 5 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (select_output, 3 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (select_read)`; `crates/metal2vulkan/src/lower/fragment/input_blend.rs (rotated)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_extended)`; `crates/metal2vulkan/src/lower/sampler/select.rs (texel_in)`; `crates/metal2vulkan/src/lower/stage_io/extended_color.rs (plan)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (zeroed_output)`; `crates/metal2vulkan/src/lower/stage_io/word_color.rs (plan)`; `crates/metal2vulkan/src/lower/texture/mod.rs (cross_class)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_image)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as, 2 sites)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slot.rs (atomic_format, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot, 3 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (sLine truncated
- `feature::Format`: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`; `crates/metal2vulkan-runtime/src/blit_fill.rs (fill)`; `crates/metal2vulkan-runtime/src/blit_plan.rs (check_formats, 3 sites)`; `crates/metal2vulkan-runtime/src/blit_plan.rs (pair_unit)`; `crates/metal2vulkan-runtime/src/blit_plan.rs (plan_levels_copy)`; `crates/metal2vulkan-runtime/src/blit_texture.rs (through_buffer)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (shape_over, 3 sites)`; `crates/metal2vulkan-runtime/src/buffer_texture.rs (texture_buffer_texel)`; `crates/metal2vulkan-runtime/src/color_resolve.rs (of_attachment)`; `crates/metal2vulkan-runtime/src/copy_plan.rs (colour_unit)`; `crates/metal2vulkan-runtime/src/copy_plan.rs (copy_unit, 2 sites)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs (usable_twin)`; `crates/metal2vulkan-runtime/src/families/features.rs (read_write_tier)`; `crates/metal2vulkan-runtime/src/families/formats.rs (answers, 3 sites)`; `crates/metal2vulkan-runtime/src/families/formats.rs (atomic_gap)`; `crates/metal2vulkan-runtime/src/families/formats.rs (lacking)`; `crates/metal2vulkan-runtime/src/families/formats.rs (none)`; `crates/metal2vulkan-runtime/src/families/formats.rs (probe, 2 sites)`; `crates/metal2vulkan-runtime/src/families/formats.rs (sparse_missing)`; `crates/metal2vulkan-runtime/src/families/formats.rs (unsupported)`; `crates/metal2vulkan-runtime/src/image_plan.rs (plan_held, 3 sites)`; `crates/metal2vulkan-runtime/src/render.rs (viewing)`; `crates/metal2vulkan-runtime/src/render_pass.rs (attachment_format)`; `crates/metal2vulkan-runtime/src/render_pass.rs (check_target)`; `crates/metal2vulkan-runtime/src/render_pass.rs (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs (target)`; `crates/metal2vulkan-runtime/src/resolve.rs (unmodelled_resolve)`; `crates/metal2vulkan-runtime/src/sample_copy.rs (checked_twin)`; `crates/metal2vulkan-runtime/src/sample_copy.rs (plan)`; `crates/metal2vulkan-runtime/src/sample_interleave.rs (interleave_merge)`; `crates/metal2vulkan-runtime/src/shadow.rs (unmerged, 2 sites)`; `crates/metal2vulkan-runtime/src/texture.rs (plan_sparse_texture)`; `crates/metal2vulkan-runtime/src/texture.rs (texture_as)`; `crates/metal2vulkan-runtime/src/texture.rs (two_planes_refused)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs (astc_texels)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs (etc_texels)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs (with_decoded_twin)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (planned_heap_texture)`; `crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs (refused)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (converted_storage)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (new_render_shadow)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (ycbcr_write_shadow)`; `crates/metal2vulkan-runtime/src/two_planes.rs (unmeasured)`; `crates/metal2vulkan-runtime/src/view_plan.rs (check_format, 5 sites)`; `crates/metal2vulkan-runtime/src/ycbcr.rs (refused)`; `crates/metal2vulkan/src/bind/extended_shadow.rs (extended_shadow_module)`; `crates/metal2vulkan/src/bind/heap.rs (array)`; `crates/metal2vulkan/src/bind/plan/resources.rs (extended_sampler)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture, 2 sites)`; `crates/metal2vulkan/src/bind/plan/resources.rs (require_filter_features)`; `crates/metal2vulkan/src/bind/sample_interleave.rs (finish)`; `crates/metal2vulkan/src/bind/sample_interleave.rs (interleave_split_module)`; `crates/metal2vulkan/src/bind/shadow_copy_in.rs (shadow_copy_in_module)`; `crates/metal2vulkan/src/lower/access/tile.rs (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs (select_param, 3 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (extended_range_blend, 5 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (select_output, 3 sites)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs (select_read)`; `crates/metal2vulkan/src/lower/fragment/input_blend.rs (rotated)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_extended)`; `crates/metal2vulkan/src/lower/sampler/select.rs (texel_in)`; `crates/metal2vulkan/src/lower/stage_io/extended_color.rs (plan)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (zeroed_output)`; `crates/metal2vulkan/src/lower/stage_io/word_color.rs (plan)`; `crates/metal2vulkan/src/lower/texture/mod.rs (cross_class)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_image)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as, 2 sites)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slot.rs (atomic_format, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot, 3 sites)`; `Line truncated
- `feature::DivergentImplicitLod`: `crates/metal2vulkan/src/lower/sampler/select.rs (tangled)`
- `feature::ImplicitLodOutsideFragment`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs (query_min_level)`; `crates/metal2vulkan/src/lower/sampler/select.rs (query_level_measured)`; `crates/metal2vulkan/src/lower/sampler/select.rs (query_min_level)`
- `feature::MinLodClamp`: `crates/metal2vulkan/src/lower/sampler/select.rs (min_lod)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`