Author SHA1 Message Date
千川白浪 8fd7fb5d9c Merge pull request #3 from liuyaxuan123457-ctrl/fix/host-batch-queue-recording
Allow host-owned copy batches to record before FIFO submission
2026-12-05 13:43:28 +08:00
Xiaochi You b8f9629ba8 Merge pull request #5 from yxc0915/steelbrain/batch-fixed-offset-draws
Batch fixed-offset draws with direct Vulkan commands
2026-12-04 18:13:58 +08:00
YXC0915 1dd4e970c0 🐎 Batch fixed-offset draws with direct Vulkan commands
Reuse the ordinary draw state across a fixed binding without submitting indirect commands. RX 6500M timing showed the indirect command path still took 0.909 ms against 0.351 ms for the same direct workload, even with the ordinary shader.
2026-12-04 18:02:14 +08:00
YXC0915 acb2f3756b 🐎 Keep fixed-offset multi-draw on the ordinary pipeline
Combine repeated vertex bindings without uploading a draw table or switching the shader. Preserve the table path for changing offsets, and exclude modules that can observe DrawIndex. Add a pixel parity and pipeline reuse regression test.
2026-12-04 17:48:08 +08:00
Xiaochi You 8edd5cd27a Merge pull request #4 from yxc0915/steelbrain/sync-metal2vulkan-865592b
Merge the upstream Vulkan runtime into development
2026-12-04 16:10:31 +08:00
YXC0915 7b3aedb5fa Sync upstream metal2vulkan for the Reims runtime
Preserve GPU suspend and replay, Places allocation isolation, and multi-draw indirect. Use the upstream render-offset deltas, static attachment feedback, and 64-bit device-address arithmetic.
2026-12-04 16:07:39 +08:00
liuyaxuan123457-ctrl 0776937c90 Document host batch ownership and keep queue tests after implementation 2026-12-03 17:23:26 +08:00
Codex 728b4701d0 Separate host batch recording from Metal queue admission 2026-12-03 16:50:43 +08:00
YXC0915 19090d5f2e 🐛 Isolate Places allocations from buffer address replay
Keep image placement slabs separate when buffer capture and replay is enabled. Leave buffer replay enabled for captured buffer allocations.
2026-12-03 02:52:31 +08:00
YXC0915 3337b4d868 🐛 Use static flags for eligible attachment feedback draws
Keep the dynamic feedback capability check for path selection. Declare color feedback on the pipeline instead of toggling it for each draw.
2026-12-03 02:52:02 +08:00
YXC0915 94ff838bb8 🆕 Support GPU state capture and replay for VM suspend
Expose buffer address capture, replay and device idle operations for suspend and resume. Preserve the existing dynamic attachment-feedback device capability.
2026-12-03 02:51:52 +08:00
Xiaochi You a97670348c Merge pull request #2 from reiasu2/reims-go/multi-draw-indirect
runtime, spirv: add opt-in multi-draw indirect batching for vertex-offset draws
2026-12-03 01:43:49 +08:00
Xiaochi You 2245ae27b0 Merge PR #1: Optimize render buffer offsets and push constants
runtime: update render buffer offsets locally and submit minimal push-constant deltas
2026-12-03 00:01:41 +08:00
棠渚听潮 6c22641a9c Batch vertex-offset draws with draw-table SPIR-V variants and multi-draw indirect 2026-12-02 19:33:16 +08:00
棠渚听潮 d92aa60353 Submit aligned render push constant deltas
Track the last push length and record only the changed words for a draw. Keep Managed index and slot reaches on the full draw path, and leave device-wide alias and unslotted reads to the existing post-update checks.

Verified with cargo fmt and runtime Clippy, 207 runtime unit tests with the existing CRLF-sensitive stage test skipped, and the draw-offset regression on Intel Arc B390 including a Managed copy back.
2026-12-02 19:33:15 +08:00
棠渚听潮 3c6be6a1ed Update render buffer offsets without rebuilding push data
Reuse retained buffers for offset-only binds and track changed slots by stage. Patch indexed push fields and fixed-function bindings for eligible direct draws, and use full validation and filling when the draw cannot reuse them.

Verified with runtime clippy, the 207 lib tests in a temporary copy with LF in stage.rs, and the offset regression on Intel Arc B390.
2026-12-02 19:33:15 +08:00
YXC0915 ea695f9456 Require dynamic state for native attachment feedback
Enable color feedback around draws using the feedback layout instead of marking every graphics pipeline. Use the attachment shadow when the device lacks the dynamic feature, so drivers with only the static layout can still run workloads that sample their render targets.
2026-12-02 17:50:47 +08:00
YXC0915 729d91d23b Restore device addresses with an explicit carry
The biased slot word let a driver lower a zero-extended 32-bit
displacement as a signed physical storage buffer offset. On AMD Windows
the first draw then read exactly 4 GiB below the intended device address.

Reconstruct the slot address with two words and a carry before adding
the signed byte displacement. Keep the binding layout and invalidate
cached shaders. The existing identity-buffer test checks the carry and
the interpreted values at addresses above 4 GiB.
2026-12-02 16:59:13 +08:00
346 changed files with 11550 additions and 33714 deletions

No files matched your search

+1 -2
View File
@@ -67,8 +67,7 @@ order, and a lower one never overrides a higher one.
elsewhere; and a Shared heap's image texture in its heap on an integrated or CPU device, and elsewhere; and a Shared heap's image texture in its heap on an integrated or CPU device, and
elsewhere an optimal image of its own in device memory, its heap range left unused, whose elsewhere an optimal image of its own in device memory, its heap range left unused, whose
device memory beside the heap's block is recorded as a known gap), the attachment feedback device memory beside the heap's block is recorded as a known gap), the attachment feedback
loop (a device without it, and on every device a Direct3D 11 plane, whose image takes only its loop (a device without it reads a render target through a counted copy of that target,
texture's bind-flag usage, reads a render target through a counted copy of that target,
recorded as a known gap), run-time texel recorded as a known gap), run-time texel
offsets (a device with the maintenance8 feature takes a run-time texel offset as the sampling offsets (a device with the maintenance8 feature takes a run-time texel offset as the sampling
or read instruction's own operand; a device without it branches over the offset's values, and or read instruction's own operand; a device without it branches over the offset's values, and
-16
View File
@@ -292,22 +292,6 @@ pub struct EntryPoint {
/// as the function's `MTLFunctionReflection.userAnnotation`; it changes nothing the function /// as the function's `MTLFunctionReflection.userAnnotation`; it changes nothing the function
/// computes. /// computes.
pub user_annotation: Option<DiagName>, pub user_annotation: Option<DiagName>,
/// A vertex function (post-tessellation ones included) or a mesh function, the stages that
/// write varyings, of a module whose `llvm.module.flags` states
/// `agx.allow_mismatched_component_counts` as 1; false for every other function. The flag is
/// the module's, so it holds for each producing function the module defines. What it changes is
/// measured, not read from its name (Apple M3 Max, macOS 27.0.1): Metal makes a render pipeline
/// whose fragment function reads a user varying at another component count than its vertex
/// function writes (1 to 4 lanes of `float`, `uint` or `int`, either way) when the vertex
/// function's module states the flag as 1, and refuses the same pipeline when the vertex
/// function's module states 0 or no such flag, whether or not the fragment function's states 1
/// ("Fragment input(s) `user(locn0)` mismatching vertex shader output type(s) or not written by
/// vertex shader"); `irc.version_*` changed nothing there. In such a pipeline a narrower input
/// reads the output's first lanes, under perspective, `center_no_perspective` and flat
/// interpolation, and a wider input reads the output's lanes and, past them, values that are no
/// constant (150 such lanes read 147 distinct values, none written by the function): Metal
/// defines none. A mesh function's has not been measured.
pub mismatched_component_counts: bool,
} }
impl EntryPoint { impl EntryPoint {
+10 -51
View File
@@ -120,9 +120,6 @@ pub(super) fn decode(
pointees, pointees,
layouts, layouts,
}; };
// `agx.allow_mismatched_component_counts` stated as 1: the module's, so its producing
// functions' (`EntryPoint::mismatched_component_counts`).
let mut mismatched = false;
for &(kind, ops) in &lists { for &(kind, ops) in &lists {
let site = Site::module(); let site = Site::module();
match kind { match kind {
@@ -140,9 +137,7 @@ pub(super) fn decode(
n.finish()?; n.finish()?;
} }
Named::CompileOptions => abi.compile = compile_options(m, ops, &site, cx.meter)?, Named::CompileOptions => abi.compile = compile_options(m, ops, &site, cx.meter)?,
Named::ModuleFlags => { Named::ModuleFlags => abi.limits = module_flags(m, ops, &site, cx.meter)?,
(abi.limits, mismatched) = module_flags(m, ops, &site, cx.meter)?;
}
Named::Ident => { Named::Ident => {
// Only the first producer is kept, so only it is allocated and charged. // Only the first producer is kept, so only it is allocated and charged.
for &id in ops { for &id in ops {
@@ -276,7 +271,7 @@ pub(super) fn decode(
} }
cx.meter.reserve(&mut abi.entries, ops.len())?; cx.meter.reserve(&mut abi.entries, ops.len())?;
for &id in ops { for &id in ops {
abi.entries.push(entry(&mut cx, stage, id, mismatched)?); abi.entries.push(entry(&mut cx, stage, id)?);
} }
} }
} }
@@ -392,50 +387,23 @@ fn plain_signature(n: &mut Ops<'_>, site: &Site) -> Result<LinkageSignature, Err
} }
/// `!llvm.module.flags`: `!{i32 <behavior>, !"<key>", <value>}`. The `air.max_*` limits are /// `!llvm.module.flags`: `!{i32 <behavior>, !"<key>", <value>}`. The `air.max_*` limits are
/// decoded, and returned with whether `agx.allow_mismatched_component_counts` (an integer, 0 or /// decoded; `wchar_size`, `frame-pointer`, `SDK Version`, and debug info's `Dwarf Version` and
/// 1, stated at most once) is 1, which the module's vertex and mesh functions carry /// `Debug Info Version` are LLVM's and carry nothing the translation reads; `air.workaround.sampler_state_variable_length_encoding` (an `i1`) names the
/// (`EntryPoint::mismatched_component_counts`, which says what it changes). `wchar_size`, /// form of the module's constexpr sampler words, which each `air.sampler_state` global's own type
/// `frame-pointer`, `SDK Version`, and debug info's `Dwarf Version` and `Debug Info Version` are /// states; any other flag is unknown.
/// LLVM's and carry nothing the translation reads, and neither do `irc.version_major`,
/// `irc.version_minor` and `irc.version_patch` (integers), each stated once: their shapes are
/// checked and nothing is kept (a measured render pipeline linked the same whatever they state).
/// `air.workaround.sampler_state_variable_length_encoding` (an `i1`) names the form of the
/// module's constexpr sampler words, which each `air.sampler_state` global's own type states. Any
/// other flag is unknown.
fn module_flags( fn module_flags(
m: &Module, m: &Module,
ops: &[MdId], ops: &[MdId],
site: &Site, site: &Site,
meter: &mut Meter, meter: &mut Meter,
) -> Result<(ModuleLimits, bool), Error> { ) -> Result<ModuleLimits, Error> {
let key = Some("llvm.module.flags"); let key = Some("llvm.module.flags");
let mut l = ModuleLimits::default(); let mut l = ModuleLimits::default();
let (mut mismatch, mut major, mut minor, mut patch) = (false, false, false, false);
let mut mismatched = false;
for &id in ops { for &id in ops {
meter.tick(1)?; meter.tick(1)?;
let mut n = Ops::node(m, id, site.clone())?; let mut n = Ops::node(m, id, site.clone())?;
n.u32(key)?; n.u32(key)?;
let flag = n.string(key)?; let flag = n.string(key)?;
// The converter's flags: an integer each, stated once; the agx flag 0 or 1.
let agx = flag == b"agx.allow_mismatched_component_counts";
let shape = match flag {
_ if agx => Some((&mut mismatch, 1)),
b"irc.version_major" => Some((&mut major, u32::MAX)),
b"irc.version_minor" => Some((&mut minor, u32::MAX)),
b"irc.version_patch" => Some((&mut patch, u32::MAX)),
_ => None,
};
if let Some((seen, limit)) = shape {
let repeated = std::mem::replace(seen, true);
let value = n.u32(key)?;
if value > limit || repeated {
return Err(site.err(AbiError::BadValue, key));
}
mismatched |= agx && value == 1;
n.finish()?;
continue;
}
let slot = match flag { let slot = match flag {
b"air.max_device_buffers" => &mut l.max_device_buffers, b"air.max_device_buffers" => &mut l.max_device_buffers,
b"air.max_constant_buffers" => &mut l.max_constant_buffers, b"air.max_constant_buffers" => &mut l.max_constant_buffers,
@@ -467,7 +435,7 @@ fn module_flags(
} }
n.finish()?; n.finish()?;
} }
Ok((l, mismatched)) Ok(l)
} }
/// `!{ptr @init, !"<type>", !"<name>", i32 <index>[, i1 <flag>]}`. /// `!{ptr @init, !"<type>", !"<name>", i32 <index>[, i1 <flag>]}`.
@@ -533,15 +501,8 @@ fn global_binding(cx: &mut Cx<'_, '_>, id: MdId, site: &Site) -> Result<GlobalBi
cx.global_binding(node, global) cx.global_binding(node, global)
} }
/// An entry node: `!{ptr @fn, !outputs, !inputs, <stage attribute>...}`, of a module whose /// An entry node: `!{ptr @fn, !outputs, !inputs, <stage attribute>...}`.
/// `agx.allow_mismatched_component_counts` is 1 where `mismatched`, which a vertex or mesh fn entry(cx: &mut Cx<'_, '_>, stage: Named, id: MdId) -> Result<EntryPoint, Error> {
/// function carries.
fn entry(
cx: &mut Cx<'_, '_>,
stage: Named,
id: MdId,
mismatched: bool,
) -> Result<EntryPoint, Error> {
cx.meter.tick(1)?; cx.meter.tick(1)?;
let m = cx.m; let m = cx.m;
let module_site = Site::module(); let module_site = Site::module();
@@ -635,8 +596,6 @@ fn entry(
outputs, outputs,
name, name,
user_annotation, user_annotation,
mismatched_component_counts: mismatched
&& matches!(stage, Stage::Vertex { .. } | Stage::Mesh { .. }),
}) })
} }
-90
View File
@@ -3436,95 +3436,6 @@ fn static_samplers_decode_from_their_globals() {
); );
} }
/// The converter's module flags (`agx.allow_mismatched_component_counts`, `irc.version_*`) are
/// checked for their shapes, and a module with no entry decodes as without them: `irc.version_*`
/// is kept nowhere, and the agx flag only on producing entries (the next test).
#[test]
fn converter_module_flags_are_checked_and_dropped() {
let flags = |nodes: &[(u64, &'static str, u64)]| {
let nodes = nodes.to_vec();
module_with(move |b| {
let ids: Vec<MdId> = nodes
.iter()
.map(|&(behavior, key, value)| node(b, &[I(behavior), S(key), I(value)]))
.collect();
b.named_md("llvm.module.flags", &ids);
})
};
let plain = flags(&[(7, "air.max_textures", 128)]).unwrap();
let with = flags(&[
(7, "air.max_textures", 128),
(7, "agx.allow_mismatched_component_counts", 1),
(1, "irc.version_major", 3),
(1, "irc.version_minor", 1),
(1, "irc.version_patch", 4),
])
.unwrap();
assert_eq!(with.limits, plain.limits);
assert_eq!(with.compile, plain.compile);
flags(&[(7, "agx.allow_mismatched_component_counts", 0)]).unwrap();
flags(&[(1, "irc.version_major", 3)]).unwrap();
for refused in [
&[(1, "irc.version_major", 3), (1, "irc.version_major", 3)][..],
&[
(7, "agx.allow_mismatched_component_counts", 1),
(7, "agx.allow_mismatched_component_counts", 1),
][..],
&[(7, "agx.allow_mismatched_component_counts", 2)][..],
] {
expect_abi(flags(refused), AbiError::BadValue);
}
expect_abi(flags(&[(7, "agx.something_else", 1)]), AbiError::UnknownKey);
}
/// `agx.allow_mismatched_component_counts` stated as 1 is the module's, kept on each vertex and
/// mesh function it defines (`EntryPoint::mismatched_component_counts`); its fragment, kernel and
/// object functions never carry it, and a module stating 0 or nothing keeps it off everywhere.
#[test]
fn the_agx_flag_is_kept_on_the_module_s_producing_functions() {
let lists: [(&str, &[&str]); 5] = [
("air.vertex", &["v", "v2"]),
("air.fragment", &["f"]),
("air.kernel", &["k"]),
("air.object", &["o"]),
("air.mesh", &["m"]),
];
let decoded = |flag: Option<u64>| {
module_with(move |b| {
if let Some(v) = flag {
let n = node(b, &[I(7), S("agx.allow_mismatched_component_counts"), I(v)]);
b.named_md("llvm.module.flags", &[n]);
}
let void = b.void();
for (list, names) in lists {
let entries: Vec<MdId> = (names.iter())
.map(|name| {
let f = entry_fn(b, name, void, &[]);
let (outputs, inputs) = (node(b, &[]), node(b, &[]));
node(b, &[F(f), N(outputs), N(inputs)])
})
.collect();
b.named_md(list, &entries);
}
})
.unwrap()
};
let flagged = |abi: &AirAbi| {
let mut on: Vec<String> = (abi.entries.iter())
.filter(|e| e.mismatched_component_counts)
.map(|e| e.name.to_string())
.collect();
on.sort_unstable();
on
};
let abi = decoded(Some(1));
assert_eq!(abi.entries.len(), 6);
assert_eq!(flagged(&abi), ["m", "v", "v2"]);
for off in [Some(0), None] {
assert!(flagged(&decoded(off)).is_empty(), "{off:?}");
}
}
#[test] #[test]
fn visible_function_references_and_signatures() { fn visible_function_references_and_signatures() {
let abi = module_with(|b| { let abi = module_with(|b| {
@@ -5429,7 +5340,6 @@ fn reach_entry(roles: Vec<ParamRole>) -> EntryPoint {
outputs: Vec::new(), outputs: Vec::new(),
name: DiagName::new("k"), name: DiagName::new("k"),
user_annotation: None, user_annotation: None,
mismatched_component_counts: false,
} }
} }
@@ -77,12 +77,12 @@ use super::ModuleValue;
use crate::budget::Meter; use crate::budget::Meter;
use crate::error::{BitcodeError, DiagName, InputError, InputErrorKind, IntrinsicError, Location}; use crate::error::{BitcodeError, DiagName, InputError, InputErrorKind, IntrinsicError, Location};
use crate::error::{Error, Feature, Limit}; use crate::error::{Error, Feature, Limit};
use crate::intrinsics::{self, Bound, DeclClass, LegacyAlignmentError}; use crate::intrinsics::{self, Bound, DeclClass};
use crate::ir::{ use crate::ir::{
AddrSpace, Align, Arena, Atomic, AtomicRmwOp, Block, BlockId, Body, Call, CallAttrs, Callee, AddrSpace, Align, Arena, Atomic, AtomicRmwOp, Block, BlockId, Body, Call, CallAttrs, Callee,
CastOp, Const, ConstId, ConstTable, FastMath, FloatPredicate, FuncId, Function, Inst, InstId, CastOp, Const, ConstId, ConstTable, FastMath, FloatPredicate, FuncId, Function, Inst, InstId,
InstKind, IntFlags, IntPredicate, LoopHints, Md, MdId, Ordering, ParamAttrs, RangeMd, Sym, InstKind, IntFlags, IntPredicate, LoopHints, Md, MdId, Ordering, RangeMd, Sym, Symbols,
Symbols, SyncScope, TailKind, Type, TypeId, TypeTable, Unroll, Value, SyncScope, TailKind, Type, TypeId, TypeTable, Unroll, Value,
}; };
const B: u32 = FUNCTION_BLOCK; const B: u32 = FUNCTION_BLOCK;
@@ -1180,7 +1180,6 @@ impl FnDecoder {
volatile, volatile,
atomic, atomic,
range: None, range: None,
speculative: false,
}; };
self.push(s, cx, code, (ty, tid), kind, m) self.push(s, cx, code, (ty, tid), kind, m)
} }
@@ -1536,7 +1535,7 @@ impl FnDecoder {
return self.drop_call(s, cx, m); return self.drop_call(s, cx, m);
} }
let mut enums = SiteEnums::default(); let mut enums = SiteEnums::default();
let mut attrs = match list { let attrs = match list {
None => None, None => None,
Some(list) => { Some(list) => {
let bc_params = cx.bc_types.params(fn_bc).unwrap_or(&[]); let bc_params = cx.bc_types.params(fn_bc).unwrap_or(&[]);
@@ -1559,22 +1558,6 @@ impl FnDecoder {
})) }))
} }
}; };
if let Target::Intrinsic(_, class) = &target {
// An older LLVM's memory intrinsic takes its alignment as an operand; the current
// form states it as the pointers' `align` attribute, which lowering reads. A constant
// alignment that is not a power of two is a malformed record, as an `align`
// attribute of that value is.
let upgraded = intrinsics::upgrade_legacy_memory(*class, &mut args, cx.consts)
.map_err(|e| match e {
LegacyAlignmentError::Intrinsic(e) => {
Error::from(InputError::new(InputErrorKind::Intrinsic(e), s.location()))
}
LegacyAlignmentError::Malformed => bad(),
})?;
if let Some(legacy) = upgraded {
attrs = upgrade_legacy_attrs(attrs, &mut enums, legacy, m)?;
}
}
let callee = match target { let callee = match target {
Target::Callee(c) => c, Target::Callee(c) => c,
Target::Intrinsic(f, class) => match intrinsics::bind(class, &args, cx.consts) { Target::Intrinsic(f, class) => match intrinsics::bind(class, &args, cx.consts) {
@@ -1756,46 +1739,6 @@ impl FnDecoder {
} }
} }
/// `attrs` and `enums` of a legacy memory intrinsic's call, upgraded as LLVM's reader does: the
/// removed alignment operand's attributes go with it, the later positions move down, and the
/// leading pointer operands' `align` is the alignment the operand stated (replacing their own,
/// none for an alignment of 0).
pub(super) fn upgrade_legacy_attrs(
attrs: Option<Box<CallAttrs>>,
enums: &mut SiteEnums,
legacy: intrinsics::LegacyAlignment,
m: &mut Meter,
) -> Result<Option<Box<CallAttrs>>, Error> {
if enums.params.len() > legacy.removed {
enums.params.remove(legacy.removed);
}
let CallAttrs { func, ret, params } = match attrs {
Some(a) => *a,
None if legacy.align.is_none() => return Ok(None),
None => {
m.charge(std::mem::size_of::<CallAttrs>())?;
CallAttrs::default()
}
};
let mut params = params.into_vec();
if params.len() > legacy.removed {
params.remove(legacy.removed);
}
if legacy.align.is_some() {
let missing = legacy.pointers.saturating_sub(params.len());
m.reserve(&mut params, missing)?;
params.resize(params.len().max(legacy.pointers), ParamAttrs::default());
}
for p in params.iter_mut().take(legacy.pointers) {
p.align = legacy.align;
}
Ok(Some(Box::new(CallAttrs {
func,
ret,
params: params.into_boxed_slice(),
})))
}
/// What a call's callee operand names, before its arguments are read. /// What a call's callee operand names, before its arguments are read.
enum Target { enum Target {
/// A direct or indirect call. /// A direct or indirect call.
@@ -12,11 +12,10 @@ use super::ModuleTables;
use crate::bitstream::writer::Writer; use crate::bitstream::writer::Writer;
use crate::error::BitcodeError; use crate::error::BitcodeError;
use crate::error::{Error, Feature}; use crate::error::{Error, Feature};
use crate::intrinsics::{LlvmIntrinsic, Template};
use crate::ir::print::print; use crate::ir::print::print;
use crate::ir::{ use crate::ir::{
Align, BlockId, Callee, Const, FuncId, InstId, InstKind, IntFlags, IntPredicate, Md, MdId, BlockId, Callee, Const, FuncId, InstId, InstKind, IntFlags, IntPredicate, Md, MdId, Type,
Type, Unroll, Value, Unroll, Value,
}; };
const STRTAB: &[u8] = b"kair.x"; const STRTAB: &[u8] = b"kair.x";
@@ -1306,270 +1305,3 @@ fn legacy_metadata_records_read_as_their_modern_twins() {
refused(decode_err(legacy_module(&[(8, vec![6, 0])], 5)), 8); refused(decode_err(legacy_module(&[(8, vec![6, 0])], 5)), 8);
refused(decode_err(module_with(&[(9, vec![0, 2])], &[])), 9); refused(decode_err(module_with(&[(9, vec![0, 2])], &[])), 9);
} }
/// How a legacy memory intrinsic's alignment operand is written in [`legacy_copy_module`], and
/// its volatile flag where that is not `false`.
#[derive(Clone, Copy)]
enum LegacyAlign {
/// An `i32` constant.
Constant(u64),
/// The kernel's second parameter.
Parameter,
/// An `i32` constant, the volatile flag being the kernel's second parameter.
VolatileParameter(u64),
}
/// `@k(ptr addrspace(1) %p [, i32 %a | i1 %v])` calling `llvm.memcpy.p1i8.p1i8.i64` as an LLVM
/// before the alignment moved to the pointers' attributes declared it, `void (ptr, ptr, i64, i32,
/// i1)`: `memcpy(%p, %p, 400, <align>, <volatile>)`, the volatile flag `false` where it is not
/// `%v`. Types: 0 `i64`, 1 `i32`, 2 `i1`, 3 `void`, 4 `ptr addrspace(1)`, 5 the declaration's, 6
/// the kernel's. Values: `@k` 0, the declaration 1, `%p` 2, `%a` or `%v` 3 where there is one,
/// then the local constants.
fn legacy_copy_module(align: LegacyAlign) -> Vec<u8> {
const NAMES: &[u8] = b"kllvm.memcpy.p1i8.p1i8.i64";
// The kernel's second parameter's type, where it has one: `i32` for `%a`, `i1` for `%v`.
let parameter = match align {
LegacyAlign::Constant(_) => None,
LegacyAlign::Parameter => Some(1),
LegacyAlign::VolatileParameter(_) => Some(2),
};
let first_const = if parameter.is_some() { 4 } else { 3 };
stream(2, 0, NAMES, |w| {
block(
w,
codes::TYPE_BLOCK,
&[
(1, vec![7]),
(7, vec![64]),
(7, vec![32]),
(7, vec![1]),
(2, vec![]),
(25, vec![1]),
(21, vec![0, 3, 4, 4, 0, 1, 2]),
(
21,
match parameter {
Some(ty) => vec![0, 3, 4, ty],
None => vec![0, 3, 4],
},
),
],
);
w.unabbrev(8, &[0, 1, 6, 0, 0, 0, 0, 0, 0]);
w.unabbrev(8, &[1, 25, 5, 0, 1, 0, 0, 0, 0]);
// Local constants: `i64 400`, then the alignment where it is one, then `i1 false` where
// the volatile flag is.
let mut consts = vec![(1, vec![0]), (4, vec![800])];
let mut at = first_const;
let align_at = match align {
LegacyAlign::Constant(bytes) | LegacyAlign::VolatileParameter(bytes) => {
consts.extend([(1, vec![1]), (4, vec![bytes * 2])]);
at += 1;
at
}
LegacyAlign::Parameter => 3,
};
let volatile = match align {
LegacyAlign::VolatileParameter(_) => 3,
LegacyAlign::Constant(_) | LegacyAlign::Parameter => {
consts.extend([(1, vec![2]), (4, vec![0])]);
at += 1;
at
}
};
let (len, next) = (first_const, at + 1);
w.enter(u64::from(codes::FUNCTION_BLOCK), 4);
w.unabbrev(1, &[1]);
block(w, codes::CONSTANTS_BLOCK, &consts);
w.unabbrev(
34,
&[
0,
1 << 15,
5,
rel(next, 1),
rel(next, 2),
rel(next, 2),
rel(next, len),
rel(next, align_at),
rel(next, volatile),
],
);
w.unabbrev(10, &[]);
w.end();
})
}
/// A memory intrinsic declared with an alignment operand decodes to the current form: the
/// operand is gone, and its value is the `align` of the destination and the source, as LLVM's
/// reader upgrades it. Metal's compilers before the move wrote this form, and lowering reads
/// the alignment from the attribute only.
#[test]
fn a_legacy_memory_intrinsic_states_its_alignment_on_its_pointers() {
let t = decode(&legacy_copy_module(LegacyAlign::Constant(16))).unwrap();
// The upgraded call verifies against the legacy declaration.
verify_module_level(&t).unwrap();
let body = body_of_named(&t, b"k");
let call = body
.insts
.values()
.find_map(|i| match &i.kind {
InstKind::Call(c) => Some(c),
_ => None,
})
.unwrap();
assert!(matches!(
call.callee,
Callee::Llvm {
op: LlvmIntrinsic::Memcpy {
volatile: false,
..
},
..
}
));
assert_eq!(call.args.len(), 4);
let sixteen = Align::from_bytes(16);
let params = &call.attrs.as_ref().unwrap().params;
assert_eq!(
params.iter().map(|p| p.align).collect::<Vec<_>>(),
[sixteen, sixteen]
);
// An alignment of 0 states none.
let none = decode(&legacy_copy_module(LegacyAlign::Constant(0))).unwrap();
verify_module_level(&none).unwrap();
let call = body_of_named(&none, b"k")
.insts
.values()
.find_map(|i| match &i.kind {
InstKind::Call(c) => Some(c.clone()),
_ => None,
})
.unwrap();
assert_eq!(call.args.len(), 4);
assert!(call.attrs.is_none());
}
/// An alignment that is not a constant power of two is refused, not dropped: one that is not a
/// constant as `ImmediateNotConstant`, and a constant that is not a power of two as a malformed
/// record, as an `align` attribute of that value is.
#[test]
fn a_legacy_memory_intrinsic_s_alignment_must_be_a_constant_power_of_two() {
let e = decode(&legacy_copy_module(LegacyAlign::Parameter))
.map(|_| ())
.unwrap_err();
assert!(format!("{e:?}").contains("ImmediateNotConstant"), "{e:?}");
let e = decode(&legacy_copy_module(LegacyAlign::Constant(24)))
.map(|_| ())
.unwrap_err();
assert_eq!(
bitcode_kind(&e),
Some(&BitcodeError::MalformedRecord {
block: codes::FUNCTION_BLOCK,
code: codes::FUNC_CALL,
}),
"{e}"
);
}
/// A legacy call whose volatile flag is not a constant where it is made is upgraded as any
/// other, and keeps its template (`Callee::Unbound`) as a current-form call does, for
/// specialization to bind where inlining makes the flag a constant. The verifier takes it one
/// operand short of the legacy declaration, as it takes the bound call.
#[test]
fn a_legacy_memory_intrinsic_with_an_unbound_volatile_flag_verifies() {
let t = decode(&legacy_copy_module(LegacyAlign::VolatileParameter(16))).unwrap();
let call = body_of_named(&t, b"k")
.insts
.values()
.find_map(|i| match &i.kind {
InstKind::Call(c) => Some(c),
_ => None,
})
.unwrap();
assert!(matches!(
call.callee,
Callee::Unbound {
template: Template::Llvm(LlvmIntrinsic::Memcpy { .. }),
..
}
));
assert_eq!(call.args.len(), 4);
let sixteen = Align::from_bytes(16);
let params = &call.attrs.as_ref().unwrap().params;
assert_eq!(
params.iter().map(|p| p.align).collect::<Vec<_>>(),
[sixteen, sixteen]
);
verify_module_level(&t).unwrap();
}
/// An upgraded call's attributes move as LLVM's reader moves them: the removed alignment
/// operand's (position 3) go with it, the volatile flag's (position 4) become position 3's, and
/// the pointers' `align` is the operand's, replacing their own; an alignment of 0 removes it.
#[test]
fn a_legacy_memory_intrinsic_s_attributes_move_with_its_operands() {
use super::enum_attrs::{EnumAttrs, SiteEnums};
use super::function::upgrade_legacy_attrs;
use crate::intrinsics::LegacyAlignment;
use crate::ir::{CallAttrs, ParamAttrs};
let param = |align: Option<u64>, deref: Option<u64>| ParamAttrs {
align: align.and_then(Align::from_bytes),
dereferenceable: deref,
..ParamAttrs::default()
};
let kinds = |kind: u32| {
let mut e = EnumAttrs::default();
e.insert(kind);
e
};
let attrs = || {
Some(Box::new(CallAttrs {
params: vec![
param(Some(4), Some(400)),
param(Some(4), None),
param(None, None),
param(None, Some(3)),
param(None, Some(4)),
]
.into_boxed_slice(),
..CallAttrs::default()
}))
};
let enums = || SiteEnums {
params: vec![kinds(1), kinds(2), kinds(3), kinds(4), kinds(5)],
..SiteEnums::default()
};
let mut m = super::tests::meter();
let legacy = |bytes: u64| LegacyAlignment {
align: Align::from_bytes(bytes),
removed: 3,
pointers: 2,
};
let mut e = enums();
let got = upgrade_legacy_attrs(attrs(), &mut e, legacy(16), &mut m)
.unwrap()
.unwrap();
assert_eq!(
got.params.to_vec(),
[
param(Some(16), Some(400)),
param(Some(16), None),
param(None, None),
param(None, Some(4)),
]
);
assert_eq!(e.params, [kinds(1), kinds(2), kinds(3), kinds(5)]);
// An alignment of 0 removes the pointers' own.
let mut e = enums();
let got = upgrade_legacy_attrs(attrs(), &mut e, legacy(0), &mut m)
.unwrap()
.unwrap();
assert_eq!(got.params[0], param(None, Some(400)));
assert_eq!(got.params[1], param(None, None));
// No attributes and no alignment: none.
let mut e = SiteEnums::default();
assert!(upgrade_legacy_attrs(None, &mut e, legacy(0), &mut m)
.unwrap()
.is_none());
}
+17 -28
View File
@@ -2,23 +2,20 @@
//! //!
//! An LLVM `load` or `store` may move a whole array or struct (`load [4 x <4 x float>], ptr //! An LLVM `load` or `store` may move a whole array or struct (`load [4 x <4 x float>], ptr
//! addrspace(2) %p`): Metal's own linker emits one where it passes a field of a buffer's struct to //! addrspace(2) %p`): Metal's own linker emits one where it passes a field of a buffer's struct to
//! a function by value, and a converter-built vertex function's return value is one stored to and //! a function by value. Lowering reads and writes buffer and threadgroup memory a scalar or vector
//! loaded from a stack allocation. Lowering reads and writes buffer, threadgroup and stack memory a //! at a time. After SCCP, [`expand`] replaces each such access, in its place, by its members' (the
//! scalar or vector at a time. After SCCP, [`expand`] replaces each such access, in its place, by //! scalars and vectors the type holds, in layout order): a `getelementptr i8` at the member's
//! its members' (the scalars and vectors the type holds, in layout order): a `getelementptr i8` at //! constant byte distance from the access's pointer (none at distance 0), and a load chained into
//! the member's constant byte distance from the access's pointer (none at distance 0), and a load //! the aggregate by `insertvalue`, starting from `undef`; a store's members are each an
//! chained into the aggregate by `insertvalue`, starting from `undef`; a store's members are each //! `extractvalue` and a store. A member's alignment is the access's, lowered to the largest power
//! an `extractvalue` and a store. A member's alignment is the access's, lowered to the largest //! of two dividing its distance; an access that states none leaves its members' unstated (each
//! power of two dividing its distance; an access that states none leaves its members' unstated //! member's ABI alignment, which its offset in the layout honours).
//! (each member's ABI alignment, which its offset in the layout honours).
//! //!
//! What is split: a non-volatile, non-atomic access in `device`, `constant`, `threadgroup` or //! What is split: a non-volatile, non-atomic access in `device`, `constant` or `threadgroup`
//! `thread` memory of an array or struct that holds no pointer, with at least one and at most //! memory of an array or struct that holds no pointer, with at least one and at most
//! [`MAX_MEMBERS`] members, nested at most [`MAX_DEPTH`] deep. The rest stays whole: a pointer //! [`MAX_MEMBERS`] members, nested at most [`MAX_DEPTH`] deep. The rest stays whole: `thread`
//! member (a handle or a resource) is lowering's to follow, and lowering holds no larger //! memory's allocations the memory planner takes whole, a pointer member (a handle or a resource)
//! aggregate, so it refuses the access (`Lowering(Access)` `AccessType`). A stack allocation's //! is lowering's to follow, and lowering holds no larger aggregate, so it refuses the access.
//! whole-aggregate access is split like the rest because lowering holds only scalars and vectors
//! there too.
use crate::budget::Meter; use crate::budget::Meter;
use crate::error::Error; use crate::error::Error;
@@ -62,8 +59,6 @@ struct Split {
ptr_ty: TypeId, ptr_ty: TypeId,
align: Option<Align>, align: Option<Align>,
members: (usize, usize), members: (usize, usize),
/// A speculative load's (`InstKind::Load`'s `speculative`): each member's load is too.
speculative: bool,
} }
impl Split { impl Split {
@@ -189,15 +184,14 @@ fn split_of(
members: &mut Vec<Member>, members: &mut Vec<Member>,
m: &mut Meter, m: &mut Meter,
) -> Result<Option<Split>, Error> { ) -> Result<Option<Split>, Error> {
let (ptr, val, ty, align, speculative) = match &inst.kind { let (ptr, val, ty, align) = match &inst.kind {
InstKind::Load { InstKind::Load {
ptr, ptr,
align, align,
volatile: false, volatile: false,
atomic: None, atomic: None,
speculative,
.. ..
} => (*ptr, None, inst.ty, *align, *speculative), } => (*ptr, None, inst.ty, *align),
InstKind::Store { InstKind::Store {
val, val,
ptr, ptr,
@@ -205,7 +199,7 @@ fn split_of(
volatile: false, volatile: false,
atomic: None, atomic: None,
} => match ty_of(*val) { } => match ty_of(*val) {
Some(ty) => (*ptr, Some(*val), ty, *align, false), Some(ty) => (*ptr, Some(*val), ty, *align),
None => return Ok(None), None => return Ok(None),
}, },
_ => return Ok(None), _ => return Ok(None),
@@ -216,10 +210,7 @@ fn split_of(
let split = matches!( let split = matches!(
tl.0.get(ptr_ty), tl.0.get(ptr_ty),
Some(Type::Ptr { Some(Type::Ptr {
space: AddrSpace::Device space: AddrSpace::Device | AddrSpace::Constant | AddrSpace::Threadgroup,
| AddrSpace::Constant
| AddrSpace::Threadgroup
| AddrSpace::Thread,
}) })
); );
if !split { if !split {
@@ -232,7 +223,6 @@ fn split_of(
ptr_ty, ptr_ty,
align, align,
members, members,
speculative,
})) }))
} }
@@ -341,7 +331,6 @@ fn emit(
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: s.speculative,
}, },
}, },
m, m,
@@ -1,496 +0,0 @@
//! A kernel's plain loads of its constant references, made in its entry block.
//!
//! A kernel often reads a `constant T&` parameter only behind its bounds branch (`if (gid >= n)
//! return; out[gid] = in[gid] * scale;`): the load of `scale` lies in a block the threads past the
//! end skip. [`expand`] moves each such load into the entry block, ahead of every branch, its value
//! reaching each use by dominance, where all of the following hold. Each is read from the body's
//! structure and the entry's ABI, never from a name.
//!
//! - **A plain load of a scalar or vector.** Neither volatile nor atomic, of an integer, a float or
//! a vector of them. The load of a pointer or an aggregate stays.
//! - **The reference's own bytes, at an offset fixed at translation time.** Its address is a
//! parameter the ABI binds as a buffer of the constant address space with a stated
//! `air.buffer_size` (a `constant T&`; no function constant gates it), or that parameter plus
//! `getelementptr`s at constant, non-negative indices and bitcasts, which move with the load. The
//! bytes read lie inside the referenced object, `[0, air.buffer_size)`, one address for every
//! thread of the dispatch. A pointer parameter (`constant T*`, no size), an offset outside the
//! object, and an offset the run computes stay.
//! - **A pointer no other root shares.** Neither the parameter nor an address step from it (a
//! `getelementptr`, a bitcast or address-space cast, a `freeze`) is an operand of a phi, a
//! `select`, or a vector or aggregate insert, the value of a store, or the function's result.
//! Such a pointer may meet one loaded from memory, which lowering then reaches by the address it
//! holds (a wide pointer); its loads stay.
//! - **No write before it.** No instruction on any path from the function's start to the load may
//! write device memory or order another thread's writes before it: a store or memory intrinsic
//! whose destination is not thread or threadgroup memory, an atomic or atomic load of any space,
//! a fence or barrier, a texture write, or a call of any kind but arithmetic, conversions, group
//! operations, built-in reads and texture reads and queries. A device buffer may cover the
//! constant buffer's bytes, so such a write could change what the load reads.
//!
//! Anything else stays where it is. The moved load reads the bytes it read where it stood, and a
//! thread that skipped its block reads them too and uses nothing of them. That thread runs a load
//! the program did not run, so the moved load is marked speculative
//! ([`InstKind::Load`]'s `speculative`): Metal requires the reference's binding only where the
//! program reads it, and an app may leave it unbound, or bound shorter than the object, where the
//! branch is not taken. Lowering contains a speculative load whatever its offset: a bound storage
//! view's robust buffer access reads zero outside its range, and a slot reached by its device
//! address checks the load against its bounds and reads zero outside, as it checks an access at
//! an offset the run computes.
use std::collections::{BTreeMap, BTreeSet};
use crate::abi::{ParamBinding, ParamRole};
use crate::budget::Meter;
use crate::error::Error;
use crate::intrinsics::{AirIntrinsic, LlvmIntrinsic, TexOp};
use crate::ir::{AddrSpace, BlockId, Body, Callee, CastOp, FuncId, Idx, InstId, InstKind};
use crate::ir::{Layout, ModuleParts, Type, TypeId, TypeLayouts, TypeTable, Value};
use super::pieces::gep_offset;
use super::rewrite::{apply, filled, invariant, scoped, BodyEdit};
/// The address steps a load's address is followed through to its parameter.
const STEPS: usize = 64;
/// Make in the entry block each load of `func`'s body that reads a constant reference the
/// entry's `bindings` bind, where nothing before it may write device memory, each marked
/// speculative (the module docs).
pub(super) fn expand(
body: Body,
parts: &ModuleParts,
func: FuncId,
bindings: &[ParamBinding],
m: &mut Meter,
) -> Result<Body, Error> {
let f = parts
.funcs
.get(func)
.ok_or_else(|| invariant("entry out of range"))?;
let Some(Type::Function { params: tys, .. }) = parts.types.get(f.ty) else {
return Err(invariant("the entry's type is not a function"));
};
let objects: BTreeMap<u32, u64> = bindings
.iter()
.filter_map(|b| reference(b, tys, &parts.types))
.collect();
if objects.is_empty() {
return Ok(body);
}
m.charge(objects.len() * std::mem::size_of::<(u32, u64)>() * 2)?;
let next = scoped(m, |m, held| {
let cx = Cx {
body: &body,
parts,
tys,
objects: &objects,
};
let shared = cx.shared(m, held)?;
let own: BTreeMap<u32, u64> = (objects.iter())
.filter(|(p, _)| !shared.contains(p))
.map(|(&p, &size)| (p, size))
.collect();
let bytes = own.len() * std::mem::size_of::<(u32, u64)>() * 2;
m.charge(bytes)?;
*held = held.saturating_add(bytes);
let cx = Cx {
objects: &own,
..cx
};
let moved = cx.moves(m, held)?;
if moved.is_empty() {
return Ok(None);
}
let mut edit = BodyEdit::keep_all(&body, m, held)?;
// Each moved load runs where the program did not run it.
for &id in moved.keys() {
let Some(inst) = body.insts.get(id) else {
continue;
};
let mut kind = inst.kind.clone();
if let InstKind::Load { speculative, .. } = &mut kind {
*speculative = true;
let bytes = std::mem::size_of::<(InstId, InstKind)>() * 2;
m.charge(bytes)?;
*held = held.saturating_add(bytes);
edit.rewrite.insert(id, kind);
}
}
edit.moved = moved;
apply(&body, &edit, &|c| c, m).map(Some)
});
m.release(objects.len() * std::mem::size_of::<(u32, u64)>() * 2);
match next? {
Some(next) => {
body.release(m);
Ok(next)
}
None => Ok(body),
}
}
/// The parameter `b` binds and the bytes of the object it references, where it is a constant
/// reference: a buffer of the constant address space with a stated `air.buffer_size`, which no
/// function constant gates, of a constant-space pointer type in `tys`.
fn reference(b: &ParamBinding, tys: &[TypeId], types: &TypeTable) -> Option<(u32, u64)> {
let ParamRole::Buffer(arg) = &b.role else {
return None;
};
if b.unused || b.predicate.is_some() || arg.space != AddrSpace::Constant {
return None;
}
let ty = types.get(*tys.get(usize::try_from(b.param).ok()?)?)?;
let pointer = matches!(
ty,
Type::Ptr {
space: AddrSpace::Constant
}
);
pointer.then_some((b.param, u64::from(arg.buffer_size?)))
}
/// What the walk reads.
struct Cx<'a> {
body: &'a Body,
parts: &'a ModuleParts,
/// The entry's parameter types.
tys: &'a [TypeId],
/// The constant references: parameter, and the bytes of the object it references.
objects: &'a BTreeMap<u32, u64>,
}
impl Cx<'_> {
/// The constant references whose pointer another root may share: the parameter, or an address
/// step from it (a `getelementptr`, a bitcast or address-space cast, a `freeze`), is an
/// operand of a phi, a `select`, or a vector or aggregate insert, the value of a store, or the
/// function's result (the module docs). Its table is charged to `held`.
fn shared(&self, m: &mut Meter, held: &mut usize) -> Result<BTreeSet<u32>, Error> {
let n = self.body.insts.len();
// The reference each instruction's pointer steps from.
let mut from: Vec<Option<u32>> = filled(m, held, n, None)?;
let of = |from: &[Option<u32>], v: Value| match v {
Value::Arg(a) => u32::try_from(a.index())
.ok()
.filter(|p| self.objects.contains_key(p)),
Value::Inst(i) => from.get(i.index()).copied().flatten(),
Value::Const(_) => None,
};
// To a fixed point: a step may lie before its base in the layout. Each pass that changes
// anything adds a step, so at most `n` passes run.
for _ in 0..=n {
let mut changed = false;
for (id, inst) in self.body.insts.iter() {
m.tick(1)?;
let base = match &inst.kind {
InstKind::Gep { base, .. } => *base,
InstKind::Cast {
op: CastOp::Bitcast | CastOp::AddrSpaceCast,
v,
}
| InstKind::Freeze(v) => *v,
_ => continue,
};
let Some(p) = of(&from, base) else {
continue;
};
if let Some(slot) = from.get_mut(id.index()).filter(|s| s.is_none()) {
*slot = Some(p);
changed = true;
}
}
if !changed {
break;
}
}
let mut shared = BTreeSet::new();
for (_, inst) in self.body.insts.iter() {
m.tick(1)?;
let mut share = |v: Value| {
if let Some(p) = of(&from, v) {
shared.insert(p);
}
};
match &inst.kind {
InstKind::Store { val, .. } => share(*val),
InstKind::Select { t, f, .. } => {
share(*t);
share(*f);
}
InstKind::Phi { .. }
| InstKind::InsertElement { .. }
| InstKind::InsertValue { .. }
| InstKind::Ret(_) => inst.kind.for_each_value(share),
_ => {}
}
}
Ok(shared)
}
/// The loads to make in the entry block, each with the address steps it moves with, mapped to
/// the entry block. Its tables are charged to `held`.
fn moves(&self, m: &mut Meter, held: &mut usize) -> Result<BTreeMap<InstId, BlockId>, Error> {
let mut moved = BTreeMap::new();
let n = self.body.blocks.len();
let entry = BlockId::new(0);
if n < 2 {
return Ok(moved);
}
// The blocks the entry reaches, and those a write may precede: every block a block that
// writes leads to.
let mut reached = filled(m, held, n, false)?;
let mut written = filled(m, held, n, false)?;
let mut stack: Vec<BlockId> = filled(m, held, n, entry)?;
stack.clear();
if let Some(r) = reached.get_mut(entry.index()) {
*r = true;
}
stack.push(entry);
while let Some(b) = stack.pop() {
m.tick(1)?;
for s in self.body.successors(b) {
// A branch back to the entry block: it is no place every path starts from.
if s == entry {
return Ok(moved);
}
if let Some(r) = reached.get_mut(s.index()).filter(|r| !**r) {
*r = true;
stack.push(s);
}
}
}
for (b, _) in self.body.blocks.iter() {
m.tick(1)?;
if !self.body.block_insts(b).any(|(_, i)| self.writes(&i.kind)) {
continue;
}
stack.push(b);
while let Some(b) = stack.pop() {
m.tick(1)?;
for s in self.body.successors(b) {
if let Some(w) = written.get_mut(s.index()).filter(|w| !**w) {
*w = true;
stack.push(s);
}
}
}
}
let mut layouts = None;
for (b, _) in self.body.blocks.iter().skip(1) {
let mut clean = reached.get(b.index()).copied().unwrap_or(false)
&& !written.get(b.index()).copied().unwrap_or(true);
for (id, inst) in self.body.block_insts(b) {
m.tick(1)?;
if !clean {
break;
}
if self.writes(&inst.kind) {
clean = false;
continue;
}
let InstKind::Load {
ptr,
volatile: false,
atomic: None,
..
} = inst.kind
else {
continue;
};
if !self.plain_value(inst.ty) {
continue;
}
if layouts.is_none() {
let l = TypeLayouts::new(&self.parts.data_layout, &self.parts.types, m)?;
*held = held.saturating_add(
self.parts.types.len() * std::mem::size_of::<Option<Layout>>(),
);
layouts = Some(l);
}
let Some(tl) = layouts.as_ref() else {
continue;
};
let Some(steps) = self.steps(tl, ptr, inst.ty, m)? else {
continue;
};
// Each step is made before what uses it: the moved instructions arrive in the
// entry block in their old order.
let mut after = id;
if steps.iter().any(|&s| {
let before = s < after;
after = s;
!before
}) {
continue;
}
for s in steps.into_iter().chain([id]) {
if moved.insert(s, entry).is_none() {
let bytes = std::mem::size_of::<(InstId, BlockId)>() * 2;
m.charge(bytes)?;
*held = held.saturating_add(bytes);
}
}
}
}
Ok(moved)
}
/// Whether a load of type `ty` reads a plain value: an integer, a float, or a vector of them.
fn plain_value(&self, ty: TypeId) -> bool {
let scalar = |t: &Type| {
matches!(
t,
Type::Int(_) | Type::Half | Type::BFloat | Type::Float | Type::Double
)
};
match self.parts.types.get(ty) {
Some(Type::Vector { elem, .. }) => self.parts.types.get(*elem).is_some_and(scalar),
Some(t) => scalar(t),
None => false,
}
}
/// The address steps of a load of `ty` at `ptr`, the nearest first, where `ptr` is a constant
/// reference plus a translation-time offset and the bytes read lie inside its object.
fn steps(
&self,
layouts: &TypeLayouts,
ptr: Value,
ty: TypeId,
m: &mut Meter,
) -> Result<Option<Vec<InstId>>, Error> {
let mut steps = Vec::new();
let mut at = 0u64;
let mut v = ptr;
for _ in 0..STEPS {
m.tick(1)?;
let i = match v {
Value::Arg(a) => {
let Some(&size) = u32::try_from(a.index())
.ok()
.and_then(|p| self.objects.get(&p))
else {
return Ok(None);
};
let inside = layouts
.store_size(ty)
.and_then(|n| at.checked_add(n))
.is_some_and(|end| end <= size);
return Ok(inside.then_some(steps));
}
Value::Inst(i) => i,
Value::Const(_) => return Ok(None),
};
let Some(inst) = self.body.insts.get(i) else {
return Ok(None);
};
match &inst.kind {
InstKind::Gep {
src_ty,
base,
indices,
..
} => {
let Some(next) = gep_offset(self.parts, layouts, *src_ty, indices)
.and_then(|o| at.checked_add(o))
else {
return Ok(None);
};
at = next;
v = *base;
}
InstKind::Cast {
op: CastOp::Bitcast,
v: inner,
} => v = *inner,
_ => return Ok(None),
}
steps.push(i);
}
Ok(None)
}
/// The type of value `v`.
fn value_ty(&self, v: Value) -> Option<TypeId> {
match v {
Value::Inst(i) => self.body.insts.get(i).map(|n| n.ty),
Value::Arg(a) => self.tys.get(a.index()).copied(),
Value::Const(k) => self.parts.consts.ty(k),
}
}
/// Whether pointer `v` points into memory of one thread or threadgroup, which no device
/// buffer covers.
fn local(&self, v: Value) -> bool {
match self.value_ty(v).and_then(|t| self.parts.types.get(t)) {
Some(Type::Ptr { space }) => local_space(*space),
_ => false,
}
}
/// Whether `kind` may write device memory, or order another thread's writes before what
/// follows it (the module docs).
fn writes(&self, kind: &InstKind) -> bool {
match kind {
InstKind::Store {
ptr, atomic: None, ..
} => !self.local(*ptr),
InstKind::Store { .. }
| InstKind::AtomicRmw { .. }
| InstKind::CmpXchg { .. }
| InstKind::Fence(_)
| InstKind::Load {
atomic: Some(_), ..
} => true,
InstKind::Call(c) => match &c.callee {
Callee::Air { op, .. } => !reads_only(op),
Callee::Llvm { op, .. } => match op {
LlvmIntrinsic::Float { .. }
| LlvmIntrinsic::Int { .. }
| LlvmIntrinsic::NarrowInt { .. }
| LlvmIntrinsic::Abs { .. }
| LlvmIntrinsic::Cttz { .. }
| LlvmIntrinsic::Ctlz { .. } => false,
LlvmIntrinsic::Memset { dst, .. }
| LlvmIntrinsic::Memcpy { dst, .. }
| LlvmIntrinsic::Memmove { dst, .. } => !local_space(*dst),
LlvmIntrinsic::Agx(_) => true,
},
_ => true,
},
_ => false,
}
}
}
/// Whether `space` is memory of one thread or threadgroup.
fn local_space(space: AddrSpace) -> bool {
matches!(
space,
AddrSpace::Thread | AddrSpace::Threadgroup | AddrSpace::ThreadgroupImageblock
)
}
/// Whether AIR intrinsic `op` neither writes memory nor orders another thread's writes:
/// arithmetic, conversions, group operations, built-in reads, and texture reads and queries.
fn reads_only(op: &AirIntrinsic) -> bool {
match op {
AirIntrinsic::Math(_)
| AirIntrinsic::Convert(_)
| AirIntrinsic::Pack(_)
| AirIntrinsic::BoolReduce(_)
| AirIntrinsic::Group(_)
| AirIntrinsic::IsUniform(_)
| AirIntrinsic::SimdgroupSize(_)
| AirIntrinsic::GlobalBuiltin(_)
| AirIntrinsic::WorkItem(_)
| AirIntrinsic::Sampler(_) => true,
AirIntrinsic::Texture(t) => matches!(
t.op,
TexOp::Read
| TexOp::Sample { .. }
| TexOp::SampleGrad { .. }
| TexOp::Gather { .. }
| TexOp::Query(_)
),
_ => false,
}
}
@@ -2246,7 +2246,6 @@ fn emit(
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}; };
for &decl in a.escapes.markers.get(&i).into_iter().flatten() { for &decl in a.escapes.markers.get(&i).into_iter().flatten() {
let marker = Call { let marker = Call {
@@ -2323,7 +2322,6 @@ fn emit(
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}; };
e.push(e.words.i64t, kind, m)?; e.push(e.words.i64t, kind, m)?;
} }
@@ -2345,7 +2343,6 @@ fn emit(
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}; };
let wide = e.push(e.words.i64t, kind, m)?; let wide = e.push(e.words.i64t, kind, m)?;
let cast = InstKind::Cast { let cast = InstKind::Cast {
@@ -96,7 +96,6 @@ fn kernel(func: FuncId, params: Vec<ParamBinding>) -> EntryPoint {
outputs: Vec::new(), outputs: Vec::new(),
name: DiagName::new("k"), name: DiagName::new("k"),
user_annotation: None, user_annotation: None,
mismatched_component_counts: false,
} }
} }
@@ -132,6 +131,7 @@ fn request() -> SpecRequest {
SpecRequest { SpecRequest {
call_stack_depth: 1, call_stack_depth: 1,
open_cl_mode: false, open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(), entry: "k".into(),
constants: BTreeMap::new(), constants: BTreeMap::new(),
} }
@@ -621,7 +621,6 @@ fn phi_kernel(dead: bool) -> (Module, AirAbi) {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
); );
k.br(join); k.br(join);
@@ -1083,7 +1082,6 @@ fn a_function_pointer_kept_in_a_thread_s_memory_is_its_word() {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
); );
call_through(k, fp, arg(1)) call_through(k, fp, arg(1))
@@ -1210,7 +1208,6 @@ fn a_loaded_pointer_no_function_can_answer_is_a_dynamic_call() {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
); );
call_through(k, fp, arg(1)) call_through(k, fp, arg(1))
@@ -1244,7 +1241,6 @@ fn constant_chosen_kernel() -> (Module, AirAbi, GlobalId) {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
); );
let is = k.push( let is = k.push(
@@ -1505,7 +1501,6 @@ fn argument_buffer_kernel(how: TableUse) -> (Module, AirAbi) {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
) )
}; };
@@ -4,7 +4,7 @@
//! the search order, a library's own calls binding to its own definitions, a variable shared by //! the search order, a library's own calls binding to its own definitions, a variable shared by
//! every reference, the refusals of what is missing or not loaded. //! every reference, the refusals of what is missing or not loaded.
use std::collections::BTreeMap; use std::collections::{BTreeMap, BTreeSet};
use super::*; use super::*;
use crate::abi::{ use crate::abi::{
@@ -152,7 +152,6 @@ fn compute(f: &mut FunctionBuilder<'_>, names: &mut Names, x: Value, d: &Def<'_>
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
); );
v = f.bin(BinOp::Add, v, word); v = f.bin(BinOp::Add, v, word);
@@ -297,7 +296,6 @@ fn client(kernel: Def<'_>, defs: &[Def<'_>], dead: bool) -> (Module, AirAbi) {
outputs: Vec::new(), outputs: Vec::new(),
name: DiagName::new("k"), name: DiagName::new("k"),
user_annotation: None, user_annotation: None,
mismatched_component_counts: false,
}]; }];
(module, abi) (module, abi)
} }
@@ -316,6 +314,7 @@ fn request() -> SpecRequest {
SpecRequest { SpecRequest {
call_stack_depth: 1, call_stack_depth: 1,
open_cl_mode: false, open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(), entry: "k".into(),
constants: BTreeMap::new(), constants: BTreeMap::new(),
} }
@@ -1,7 +1,7 @@
//! Linking tests over IR built with the typed test builder: a kernel calls visible functions //! Linking tests over IR built with the typed test builder: a kernel calls visible functions
//! through reference stubs, and linked modules define them. //! through reference stubs, and linked modules define them.
use std::collections::BTreeMap; use std::collections::{BTreeMap, BTreeSet};
use super::*; use super::*;
use crate::abi::{ use crate::abi::{
@@ -144,7 +144,6 @@ fn caller(dead: bool) -> (Module, AirAbi) {
outputs: Vec::new(), outputs: Vec::new(),
name: DiagName::new("k"), name: DiagName::new("k"),
user_annotation: None, user_annotation: None,
mismatched_component_counts: false,
}]; }];
abi.visible_function_refs = vec![reference(stub, "f")]; abi.visible_function_refs = vec![reference(stub, "f")];
(module, abi) (module, abi)
@@ -217,7 +216,6 @@ fn callee(name: &str, calls: &[&str]) -> LinkedModule {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
); );
let mut v = f.bin(BinOp::Add, x3, word); let mut v = f.bin(BinOp::Add, x3, word);
@@ -257,6 +255,7 @@ fn request() -> SpecRequest {
SpecRequest { SpecRequest {
call_stack_depth: 1, call_stack_depth: 1,
open_cl_mode: false, open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(), entry: "k".into(),
constants: BTreeMap::new(), constants: BTreeMap::new(),
} }
@@ -551,7 +550,6 @@ fn constant_callee() -> LinkedCode {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
) )
}; };
@@ -1313,7 +1311,6 @@ fn a_difference_no_adapter_passes_is_not_implemented() {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
)) ))
}, },
+19 -19
View File
@@ -84,13 +84,9 @@
//! through the call's map pointer and Apple's arithmetic. **AIR 2.7 simdgroup-matrix block loads and //! through the call's map pointer and Apple's arithmetic. **AIR 2.7 simdgroup-matrix block loads and
//! stores** take their AIR 2.8 form, their extent, stride and origin built from the elements per //! stores** take their AIR 2.8 form, their extent, stride and origin built from the elements per
//! row, the origin and the constant transpose flag (`legacy_matrix`). **Aggregate accesses**: a //! row, the origin and the constant transpose flag (`legacy_matrix`). **Aggregate accesses**: a
//! load or store of a whole array or struct in buffer, threadgroup or stack memory becomes its //! load or store of a whole array or struct in buffer or threadgroup memory becomes its scalar
//! scalar and vector members' accesses, joined by `insertvalue` or split by `extractvalue` //! and vector members' accesses, joined by `insertvalue` or split by `extractvalue`
//! (`aggregates`). **Constant references**: in a kernel, each plain load of a scalar or vector //! (`aggregates`). **Program-scope buffer bindings**: each load of the pointer a bound buffer's
//! from a `constant T&` parameter's object, at an offset fixed at translation time, is made in
//! the entry block where nothing on any path before it may write device memory and no other
//! root shares the parameter's pointer, marked speculative, as a speculated arm's load is
//! (`const_hoist`). **Program-scope buffer bindings**: each load of the pointer a bound buffer's
//! global holds becomes a read of the entry's parameter of that buffer, its own or one appended //! global holds becomes a read of the entry's parameter of that buffer, its own or one appended
//! (`global_binding`). **Global built-in //! (`global_binding`). **Global built-in
//! variables**: each `air.get_*` read of a program-scope built-in becomes a read of a built-in //! variables**: each `air.get_*` read of a program-scope built-in becomes a read of a built-in
@@ -113,7 +109,6 @@ mod async_copy;
mod block_read; mod block_read;
mod byval; mod byval;
mod command_writes; mod command_writes;
mod const_hoist;
mod const_loads; mod const_loads;
mod const_tables; mod const_tables;
mod devirt; mod devirt;
@@ -212,6 +207,12 @@ pub struct SpecRequest {
/// sits 3 past its index, and OpenCL C's work-item functions read the dispatch's values /// sits 3 past its index, and OpenCL C's work-item functions read the dispatch's values
/// ([`opencl`]). Any other entry than a kernel specializes as without it. /// ([`opencl`]). Any other entry than a kernel specializes as without it.
pub open_cl_mode: bool, pub open_cl_mode: bool,
/// With [`open_cl_mode`](Self::open_cl_mode), the texture indices of the kernel's 1D images
/// (`texture1d` and `texture1d_array` arguments) that a 1D texture is bound for, where Apple's
/// OpenCL binds a 2D texture of height 1: each keeps its 1D type and its 1D operations, which
/// read the 1D texture. Every other 1D image of the kernel is read as the 2D texture
/// ([`Entry::open_cl_1d_images`]).
pub open_cl_lines: BTreeSet<u32>,
} }
/// The constexpr samplers of one linked function that a pipeline state numbers /// The constexpr samplers of one linked function that a pipeline state numbers
@@ -303,6 +304,11 @@ pub struct Entry {
/// no measurement says whether it speculates them (an arm of an instruction, size or shape no /// no measurement says whether it speculates them (an arm of an instruction, size or shape no
/// probe covers). Such a branch keeps the AIR's lanes; Metal's may be the block's. /// probe covers). Such a branch keeps the AIR's lanes; Metal's may be the block's.
pub unmeasured_speculation: bool, pub unmeasured_speculation: bool,
/// In a kernel of OpenCL mode ([`SpecRequest::open_cl_mode`]), the texture indices of its 1D
/// images (`texture1d` and `texture1d_array` arguments): each is read as the 2D texture of
/// height 1 Apple's OpenCL binds for it, or as a 1D texture where
/// [`SpecRequest::open_cl_lines`] names it. Empty elsewhere.
pub open_cl_1d_images: BTreeSet<u32>,
} }
/// An entry's explicit call stack: what its recursion through visible functions runs on. Its stacks /// An entry's explicit call stack: what its recursion through visible functions runs on. Its stacks
@@ -628,7 +634,7 @@ pub fn specialize_dynamic(
// OpenCL mode: a 1D image's operations are the 2D texture's that Apple's OpenCL binds for it, // OpenCL mode: a 1D image's operations are the 2D texture's that Apple's OpenCL binds for it,
// but those of an image a 1D texture is bound for. // but those of an image a 1D texture is bound for.
let body = if req.open_cl_mode && matches!(ep.stage, Stage::Kernel { .. }) { let body = if req.open_cl_mode && matches!(ep.stage, Stage::Kernel { .. }) {
opencl_1d::expand(body, &mut parts, ep, m)? opencl_1d::expand(body, &mut parts, (ep, &req.open_cl_lines), m)?
} else { } else {
body body
}; };
@@ -764,16 +770,8 @@ pub fn specialize_dynamic(
// in plain AIR, each OpenCL C `mad` call its multiply and addition, and each `mul24` and // in plain AIR, each OpenCL C `mad` call its multiply and addition, and each `mul24` and
// `mad24` call the 32-bit product of its operands' low 24 bits (and the addition). // `mad24` call the 32-bit product of its operands' low 24 bits (and the addition).
let body = routine::expand(body, &mut parts, m)?; let body = routine::expand(body, &mut parts, m)?;
// Aggregate loads and stores of buffer, threadgroup and stack memory as their members' // Aggregate loads and stores of buffer and threadgroup memory as their members' accesses.
// accesses.
let body = aggregates::expand(body, &mut parts, func, m)?; let body = aggregates::expand(body, &mut parts, func, m)?;
// A kernel's plain loads of its constant references, made in its entry block where nothing
// before them may write device memory.
let body = if matches!(ep.stage, Stage::Kernel { .. }) {
const_hoist::expand(body, &parts, func, &ep.params, m)?
} else {
body
};
// A simdgroup reduction before a discard that Metal's compiler moves past it is placed after // A simdgroup reduction before a discard that Metal's compiler moves past it is placed after
// the discard, where the fragment lowering gives Metal's lanes. // the discard, where the fragment lowering gives Metal's lanes.
let body = if matches!(ep.stage, Stage::Fragment { .. }) { let body = if matches!(ep.stage, Stage::Fragment { .. }) {
@@ -821,8 +819,9 @@ pub fn specialize_dynamic(
ep.params.extend(lanes.bindings()); ep.params.extend(lanes.bindings());
} }
// OpenCL mode's indices and hidden buffers. // OpenCL mode's indices and hidden buffers.
let mut open_cl_1d_images = BTreeSet::new();
if let Some(first) = hidden { if let Some(first) = hidden {
ep = opencl::entry(ep, first)?; (ep, open_cl_1d_images) = opencl::entry(ep, first, &req.open_cl_lines)?;
} }
// The buffer parameters the program-scope bindings' reads became, each at a slot no other // The buffer parameters the program-scope bindings' reads became, each at a slot no other
// parameter binds. // parameter binds.
@@ -926,6 +925,7 @@ pub fn specialize_dynamic(
lockstep: Lockstep::default(), lockstep: Lockstep::default(),
call_stack, call_stack,
unmeasured_speculation, unmeasured_speculation,
open_cl_1d_images,
module, module,
}) })
} }
+23 -7
View File
@@ -68,6 +68,8 @@
//! left, and lowering refuses it. [`entry`] then moves the entry's buffer-indexed arguments 3 on //! left, and lowering refuses it. [`entry`] then moves the entry's buffer-indexed arguments 3 on
//! and adds the three buffers' bindings. //! and adds the three buffers' bindings.
use std::collections::BTreeSet;
use crate::abi::{ use crate::abi::{
AbiInt, Access, ArgTypeInfo, BufferArg, EntryPoint, ParamBinding, ParamRole, Slot, AbiInt, Access, ArgTypeInfo, BufferArg, EntryPoint, ParamBinding, ParamRole, Slot,
}; };
@@ -334,7 +336,6 @@ impl Sink<'_> {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
m, m,
)?; )?;
@@ -671,14 +672,29 @@ pub(super) fn barriers(mut body: Body, parts: &ModuleParts, m: &mut Meter) -> Re
/// `first` to `first + 2`: each argument bound at a buffer index 3 past its own (an argument /// `first` to `first + 2`: each argument bound at a buffer index 3 past its own (an argument
/// buffer, a function table and an acceleration structure as a buffer), threadgroup memory, /// buffer, a function table and an acceleration structure as a buffer), threadgroup memory,
/// textures and samplers at theirs, a 1D image's texture of the 2D type Metal's OpenCL binds for /// textures and samplers at theirs, a 1D image's texture of the 2D type Metal's OpenCL binds for
/// it (`texture1d` as `texture2d`, `texture1d_array` as `texture2d_array`), and the buffers' /// it (`texture1d` as `texture2d`, `texture1d_array` as `texture2d_array`) but at a texture index
/// bindings after the entry's own. /// of `lines`, a 1D texture's, which keeps its type, and the buffers' bindings after the entry's
pub fn entry(mut ep: EntryPoint, first: u32) -> Result<EntryPoint, Error> { /// own. With it, the texture indices of the entry's 1D images (`Entry::open_cl_1d_images`).
pub fn entry(
mut ep: EntryPoint,
first: u32,
lines: &BTreeSet<u32>,
) -> Result<(EntryPoint, BTreeSet<u32>), Error> {
let mut images = BTreeSet::new();
for p in &mut ep.params { for p in &mut ep.params {
if let ParamRole::Texture(_) = &p.role { if let ParamRole::Texture(t) = &p.role {
let bound = (p.ty.name.as_ref()).and_then(|name| bound_texture(&name.to_string())); let bound = (p.ty.name.as_ref()).and_then(|name| bound_texture(&name.to_string()));
if let Some(bound) = bound { if let Some(bound) = bound {
p.ty.name = Some(DiagName::new(bound)); let index = match t.location.index {
AbiInt::Const(index) => Some(index),
_ => None,
};
if let Some(index) = index {
images.insert(index);
}
if !index.is_some_and(|index| lines.contains(&index)) {
p.ty.name = Some(DiagName::new(bound));
}
} }
continue; continue;
} }
@@ -721,7 +737,7 @@ pub fn entry(mut ep: EntryPoint, first: u32) -> Result<EntryPoint, Error> {
name: Some(DiagName::new(name)), name: Some(DiagName::new(name)),
}); });
} }
Ok(ep) Ok((ep, images))
} }
/// The MSL type of the texture Metal's OpenCL binds for an image argument whose type AIR names /// The MSL type of the texture Metal's OpenCL binds for an image argument whose type AIR names
+43 -10
View File
@@ -18,17 +18,20 @@
//! array, its coordinate `(x, 0)`, a sampled coordinate `(x, 0.5)` (the row's centre in //! array, its coordinate `(x, 0)`, a sampled coordinate `(x, 0.5)` (the row's centre in
//! normalized and unnormalized coordinates alike), its offset `(o, 0)` or, where the 1D form has //! normalized and unnormalized coordinates alike), its offset `(o, 0)` or, where the 1D form has
//! none, `(0, 0)`. Lowering then declares the slot, and the binder binds it, as the 2D texture //! none, `(0, 0)`. Lowering then declares the slot, and the binder binds it, as the 2D texture
//! Metal's OpenCL binds; a 1D texture bound there, which Apple's OpenCL never binds, is the //! Metal's OpenCL binds. An image a 1D texture is bound for (`SpecRequest::open_cl_lines`, the
//! consumer's to refuse. Not rewritten: `get_num_mip_levels`, whose 1D answer (0) a 2D texture's is //! binder's variant) keeps its 1D operations, which read the 1D texture: the 5300M's answer.
//! Not rewritten: `get_num_mip_levels`, whose 1D answer (0) a 2D texture's is
//! not, and the image format queries, which read a hidden buffer whatever the shape //! not, and the image format queries, which read a hidden buffer whatever the shape
//! (`canon::opencl`); neither is OpenCL C's. //! (`canon::opencl`); neither is OpenCL C's.
use crate::abi::EntryPoint; use std::collections::BTreeSet;
use crate::abi::{AbiInt, EntryPoint, ParamRole};
use crate::budget::Meter; use crate::budget::Meter;
use crate::error::Error; use crate::error::Error;
use crate::intrinsics::{AirIntrinsic, ImageDim, ImageShape, Query, TexOp, TexRole, Texture}; use crate::intrinsics::{AirIntrinsic, ImageDim, ImageShape, Query, TexOp, TexRole, Texture};
use crate::ir::{ use crate::ir::{
ArgIdx, Body, Call, CallConv, Callee, Const, FnAttrs, FuncId, Function, InstId, InstKind, ArgIdx, Body, Call, CallConv, Callee, Const, FnAttrs, FuncId, Function, Idx, InstId, InstKind,
Linkage, ModuleParts, Param, ParamAttrs, Type, TypeId, UnnamedAddr, Value, Visibility, Linkage, ModuleParts, Param, ParamAttrs, Type, TypeId, UnnamedAddr, Value, Visibility,
}; };
@@ -57,8 +60,9 @@ fn widened(t: Texture) -> Option<Texture> {
} }
} }
/// The 1D texture operation `kind` calls that [`expand`] rewrites, with its declaration and call. /// The 1D texture operation `kind` calls that [`expand`] rewrites, with its declaration and call:
fn site(kind: &InstKind) -> Option<(Texture, FuncId, &Call)> { /// not one of a texture parameter of `kept`, a 1D texture's.
fn site<'a>(kind: &'a InstKind, kept: &[u32]) -> Option<(Texture, FuncId, &'a Call)> {
let InstKind::Call(call) = kind else { let InstKind::Call(call) = kind else {
return None; return None;
}; };
@@ -66,11 +70,36 @@ fn site(kind: &InstKind) -> Option<(Texture, FuncId, &Call)> {
Callee::Air { Callee::Air {
decl, decl,
op: AirIntrinsic::Texture(t), op: AirIntrinsic::Texture(t),
} if widened(t).is_some() => Some((t, decl, call)), } if widened(t).is_some() && !of_params(t, call, kept) => Some((t, decl, call)),
_ => None, _ => None,
} }
} }
/// Whether operation `t`'s `call` names a texture that is one of the entry's parameters `kept`.
fn of_params(t: Texture, call: &Call, kept: &[u32]) -> bool {
let texture = t.layout().index(TexRole::Texture);
match texture.and_then(|i| call.args.get(i)) {
Some(Value::Arg(a)) => u32::try_from(a.index()).is_ok_and(|p| kept.contains(&p)),
_ => false,
}
}
/// The parameters of `ep` that bind a texture at an index of `lines`: the 1D images a 1D texture
/// is bound for, whose operations stay 1D.
fn kept_params(ep: &EntryPoint, lines: &BTreeSet<u32>, m: &mut Meter) -> Result<Vec<u32>, Error> {
let mut kept = Vec::new();
for p in &ep.params {
m.tick(1)?;
if let ParamRole::Texture(t) = &p.role {
if matches!(t.location.index, AbiInt::Const(index) if lines.contains(&index)) {
m.reserve(&mut kept, 1)?;
kept.push(p.param);
}
}
}
Ok(kept)
}
/// Whether `parts` declares a 1D texture operation [`expand`] rewrites. Every site calls one, so /// Whether `parts` declares a 1D texture operation [`expand`] rewrites. Every site calls one, so
/// a module that declares none has none, and [`expand`] need not read its instructions. /// a module that declares none has none, and [`expand`] need not read its instructions.
fn declares_sites(parts: &ModuleParts, m: &mut Meter) -> Result<bool, Error> { fn declares_sites(parts: &ModuleParts, m: &mut Meter) -> Result<bool, Error> {
@@ -92,23 +121,25 @@ fn declares_sites(parts: &ModuleParts, m: &mut Meter) -> Result<bool, Error> {
} }
/// Make each 1D texture operation of the entry `ep`'s inlined `body` that the module doc lists a /// Make each 1D texture operation of the entry `ep`'s inlined `body` that the module doc lists a
/// call of a function built for it, and inline the result. /// call of a function built for it, and inline the result: each but those of an image at a
/// texture index of `lines`, which a 1D texture is bound for.
pub(super) fn expand( pub(super) fn expand(
body: Body, body: Body,
parts: &mut ModuleParts, parts: &mut ModuleParts,
ep: &EntryPoint, (ep, lines): (&EntryPoint, &BTreeSet<u32>),
m: &mut Meter, m: &mut Meter,
) -> Result<Body, Error> { ) -> Result<Body, Error> {
if !declares_sites(parts, m)? { if !declares_sites(parts, m)? {
return Ok(body); return Ok(body);
} }
let func = ep.func; let func = ep.func;
let kept = kept_params(ep, lines, m)?;
// One function per operation and declaration, and each call's. // One function per operation and declaration, and each call's.
let mut made: Vec<((Texture, FuncId), FuncId)> = Vec::new(); let mut made: Vec<((Texture, FuncId), FuncId)> = Vec::new();
let mut calls: Vec<(InstId, FuncId)> = Vec::new(); let mut calls: Vec<(InstId, FuncId)> = Vec::new();
for (id, inst) in body.insts.iter() { for (id, inst) in body.insts.iter() {
m.tick(1)?; m.tick(1)?;
let Some((t, decl, call)) = site(&inst.kind) else { let Some((t, decl, call)) = site(&inst.kind, &kept) else {
continue; continue;
}; };
let f = match made.iter().find(|(k, _)| *k == (t, decl)) { let f = match made.iter().find(|(k, _)| *k == (t, decl)) {
@@ -125,6 +156,8 @@ pub(super) fn expand(
} }
m.release(made.capacity() * std::mem::size_of::<((Texture, FuncId), FuncId)>()); m.release(made.capacity() * std::mem::size_of::<((Texture, FuncId), FuncId)>());
drop(made); drop(made);
m.release(kept.capacity() * std::mem::size_of::<u32>());
drop(kept);
if calls.is_empty() { if calls.is_empty() {
m.release(calls.capacity() * std::mem::size_of::<(InstId, FuncId)>()); m.release(calls.capacity() * std::mem::size_of::<(InstId, FuncId)>());
return Ok(body); return Ok(body);
-1
View File
@@ -258,7 +258,6 @@ impl<'p> Out<'p> {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}; };
self.push(ty, kind, m) self.push(ty, kind, m)
} }
@@ -195,7 +195,6 @@ fn emit(
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
}, },
m, m,
@@ -292,7 +292,6 @@ impl Sink<'_> {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}; };
self.push(ty, load, m) self.push(ty, load, m)
} }
@@ -3153,7 +3153,6 @@ fn load(ptr: Value) -> InstKind {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
} }
} }
@@ -298,7 +298,6 @@ fn load(ty: TypeId, ptr: Value) -> Inst {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
} }
} }
+1 -20
View File
@@ -39,11 +39,7 @@
//! [`expand`] speculates each outermost branch Metal speculates whose arms hold a group operation //! [`expand`] speculates each outermost branch Metal speculates whose arms hold a group operation
//! that answers differently there (the operations above): the branch becomes a jump into its arm //! that answers differently there (the operations above): the branch becomes a jump into its arm
//! (a diamond's arms run one after the other), each value the arms join with becomes a `select` //! (a diamond's arms run one after the other), each value the arms join with becomes a `select`
//! on the condition, and a sunk store stores the chosen value where the arms join. Each load of //! on the condition, and a sunk store stores the chosen value where the arms join. A branch whose
//! the arms, a `constant` reference's, then runs in lanes the program did not run it in, and is
//! marked speculative ([`InstKind::Load`]'s `speculative`): lowering contains it where the
//! reference is unbound or bound shorter than the load, as the constant-reference hoist's loads
//! (`const_hoist`). A branch whose
//! arms hold no such operation is left as it is, as is one whose arms hold an instruction no //! arms hold no such operation is left as it is, as is one whose arms hold an instruction no
//! measurement covers (a vector or aggregate operation, an address computation, a math function //! measurement covers (a vector or aggregate operation, an address computation, a math function
//! other than `sqrt`, a call outside the families above, a load other than a `constant` //! other than `sqrt`, a call outside the families above, a load other than a `constant`
@@ -685,21 +681,6 @@ fn flatten(
let Some(head_term) = term(fold.head) else { let Some(head_term) = term(fold.head) else {
return; return;
}; };
// Each load of the arms runs in every lane of the branch's block.
for a in &fold.arms {
for &b in &a.blocks {
for (id, i) in body.block_insts(b) {
if !matches!(i.kind, InstKind::Load { .. }) {
continue;
}
let mut kind = i.kind.clone();
if let InstKind::Load { speculative, .. } = &mut kind {
*speculative = true;
}
edit.rewrite.insert(id, kind);
}
}
}
match &fold.arms[..] { match &fold.arms[..] {
[a] => { [a] => {
edit.rewrite.insert( edit.rewrite.insert(
@@ -22,8 +22,8 @@ struct Types {
i32t: TypeId, i32t: TypeId,
} }
/// A body of `fn(i32 t, ptr addrspace(1) out, ptr addrspace(2) k)` that `build` writes, `k` a /// A body of `fn(i32 t, ptr addrspace(1) out)` that `build` writes, with its type table and
/// `constant` reference of 4 bytes, with its type table and parameter types. /// parameter types.
struct Built { struct Built {
body: Body, body: Body,
types: TypeTable, types: TypeTable,
@@ -32,18 +32,9 @@ struct Built {
} }
impl Built { impl Built {
/// The parameters' attributes: `k` dereferenceable for its 4 bytes.
fn params(&self) -> Vec<Param> {
let mut params = vec![Param::default(); self.param_tys.len()];
if let Some(k) = params.get_mut(2) {
k.attrs.dereferenceable = Some(4);
}
params
}
fn decisions(&self) -> Vec<Decision> { fn decisions(&self) -> Vec<Decision> {
let mut m = meter(); let mut m = meter();
let params = self.params(); let params = vec![Param::default(); self.param_tys.len()];
decisions( decisions(
&self.body, &self.body,
(&self.types, &self.consts), (&self.types, &self.consts),
@@ -63,7 +54,7 @@ impl Built {
/// measurement decides. /// measurement decides.
fn expanded_noting(self) -> (Body, bool) { fn expanded_noting(self) -> (Body, bool) {
let mut m = meter(); let mut m = meter();
let params = self.params(); let params = vec![Param::default(); self.param_tys.len()];
expand( expand(
self.body, self.body,
(&self.types, &self.consts), (&self.types, &self.consts),
@@ -82,8 +73,7 @@ fn built(build: impl FnOnce(&mut FunctionBuilder<'_>, &Types)) -> Built {
i32t: m.int(32), i32t: m.int(32),
}; };
let dev = m.ptr(AddrSpace::Device); let dev = m.ptr(AddrSpace::Device);
let cst = m.ptr(AddrSpace::Constant); let fty = m.fn_ty(types.void, &[types.i32t, dev]);
let fty = m.fn_ty(types.void, &[types.i32t, dev, cst]);
let mut f = m.define("f", fty); let mut f = m.define("f", fty);
build(&mut f, &types); build(&mut f, &types);
let id = f.finish(); let id = f.finish();
@@ -351,57 +341,6 @@ fn a_quad_reduction_keeps_its_arm() {
assert_eq!(phis_and_selects(&body), (1, 0)); assert_eq!(phis_and_selects(&body), (1, 0));
} }
/// The load of `k`, a `constant` reference, then `+ t`.
fn read_k(f: &mut FunctionBuilder<'_>, t: &Types) -> Value {
let x = f.push(
t.i32t,
InstKind::Load {
ptr: f.arg(2),
align: None,
volatile: false,
atomic: None,
range: None,
speculative: false,
},
);
f.bin(BinOp::Add, x, f.arg(0))
}
/// Whether each load of `body` is speculative, in layout order.
fn speculative_loads(body: &Body) -> Vec<bool> {
body.insts
.iter()
.filter_map(|(_, i)| match i.kind {
InstKind::Load { speculative, .. } => Some(speculative),
_ => None,
})
.collect()
}
/// A `constant` reference's load in a speculated arm runs in every lane of the branch's block,
/// where the program ran it in the arm's lanes alone: it is marked speculative, so lowering
/// contains it where the reference is bound shorter than the load or not at all. An arm that keeps
/// its lanes keeps its load as it is.
#[test]
fn a_constant_reference_load_of_a_speculated_arm_is_speculative() {
let b = triangle(|f, t| {
let x = read_k(f, t);
first(f, t, x)
});
assert_eq!(b.decisions(), [Decision::Speculated]);
let body = b.expanded();
assert_eq!(conditional_branches(&body), 0);
assert_eq!(speculative_loads(&body), [true]);
let b = triangle(|f, t| {
let x = read_k(f, t);
let y = first(f, t, x);
let s = quad_sum(f, t, x);
f.bin(BinOp::Add, y, s)
});
assert_eq!(b.decisions(), [Decision::Kept]);
assert_eq!(speculative_loads(&b.expanded()), [false]);
}
/// A device read keeps its arm. /// A device read keeps its arm.
#[test] #[test]
fn a_device_read_keeps_its_arm() { fn a_device_read_keeps_its_arm() {
@@ -415,7 +354,6 @@ fn a_device_read_keeps_its_arm() {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
); );
first(f, t, x) first(f, t, x)
+3 -5
View File
@@ -1,6 +1,6 @@
//! Canonicalization tests over IR built with the typed test builder. //! Canonicalization tests over IR built with the typed test builder.
use std::collections::BTreeMap; use std::collections::{BTreeMap, BTreeSet};
use super::*; use super::*;
use crate::abi::{ use crate::abi::{
@@ -21,7 +21,6 @@ use crate::ir::{
mod aggregates; mod aggregates;
mod command_buffers; mod command_buffers;
mod constant_fields; mod constant_fields;
mod constant_hoist;
mod constant_sets; mod constant_sets;
mod conversions; mod conversions;
mod float_compares; mod float_compares;
@@ -98,7 +97,6 @@ fn kernel(func: FuncId, params: Vec<ParamBinding>) -> EntryPoint {
outputs: Vec::new(), outputs: Vec::new(),
name: DiagName::new("k"), name: DiagName::new("k"),
user_annotation: None, user_annotation: None,
mismatched_component_counts: false,
} }
} }
@@ -167,7 +165,6 @@ fn load(f: &mut FunctionBuilder<'_>, ty: TypeId, ptr: Value) -> Value {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
) )
} }
@@ -187,6 +184,7 @@ fn request(constants: &[(u32, ConstValue)]) -> SpecRequest {
SpecRequest { SpecRequest {
call_stack_depth: 1, call_stack_depth: 1,
open_cl_mode: false, open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(), entry: "k".into(),
constants: constants.iter().cloned().collect::<BTreeMap<_, _>>(), constants: constants.iter().cloned().collect::<BTreeMap<_, _>>(),
} }
@@ -2054,7 +2052,6 @@ fn a_deeply_nested_written_global_is_rebuilt_on_a_small_stack() {
volatile: true, volatile: true,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
); );
store(&mut f, v, arg(0)); store(&mut f, v, arg(0));
@@ -2867,6 +2864,7 @@ fn a_static_initializer_branch_on_an_unsupplied_constant_takes_its_false_way() {
let r = SpecRequest { let r = SpecRequest {
call_stack_depth: 1, call_stack_depth: 1,
open_cl_mode: false, open_cl_mode: false,
open_cl_lines: BTreeSet::new(),
entry: "k".into(), entry: "k".into(),
constants: [(3, boolean(1))].into_iter().collect(), constants: [(3, boolean(1))].into_iter().collect(),
}; };
@@ -1,5 +1,5 @@
//! Aggregate loads and stores of buffer, threadgroup and stack memory, split into their members' //! Aggregate loads and stores of buffer and threadgroup memory, split into their members' accesses
//! accesses (`canon::aggregates`). //! (`canon::aggregates`).
use super::*; use super::*;
@@ -31,15 +31,6 @@ enum Move {
/// `store [2 x i32] [7, 7]` into a threadgroup array, loaded back whole, element 1 stored to /// `store [2 x i32] [7, 7]` into a threadgroup array, loaded back whole, element 1 stored to
/// `out`. /// `out`.
Threadgroup, Threadgroup,
/// `store { <2 x float>, i32 } zeroinitializer` into a stack allocation, field 1 overwritten
/// from the constant buffer, the whole loaded back, its field 1 stored to `out`.
Stack,
/// [`Move::Stack`] with a volatile whole load.
StackVolatile,
/// A `{ ptr addrspace(1), i32 }` stack allocation, zero-stored and loaded whole.
StackPointer,
/// A `[300 x float]` stack allocation, zero-stored and loaded whole.
StackWide,
} }
/// `kernel k(constant void *in [[buffer(0)]], device void *out [[buffer(1)]])`, moving an aggregate /// `kernel k(constant void *in [[buffer(0)]], device void *out [[buffer(1)]])`, moving an aggregate
@@ -90,16 +81,6 @@ fn moved(how: Move) -> Entry {
let k = m.constant(i32t, Const::Int(7)); let k = m.constant(i32t, Const::Int(7));
Value::Const(m.constant(tg_ty, Const::Aggregate([k, k].into()))) Value::Const(m.constant(tg_ty, Const::Aggregate([k, k].into())))
}; };
let m_thread = m.ptr(AddrSpace::Thread);
let stack_ty = m.struct_ty(&[v2, i32t]);
let zero_of = |m: &mut ModuleBuilder, ty| Value::Const(m.constant(ty, Const::Null));
let (stack_zero, ptr_zero, wide_zero) = (
zero_of(&mut m, stack_ty),
zero_of(&mut m, with_ptr),
zero_of(&mut m, wide),
);
let zero64 = m.const_int(i64t, 0);
let one = m.const_int(i32t, 1);
let fty = m.fn_ty(void, &[cst, dev]); let fty = m.fn_ty(void, &[cst, dev]);
let mut f = m.define("k", fty); let mut f = m.define("k", fty);
let load_as = |f: &mut FunctionBuilder<'_>, ty: TypeId, ptr: Value, volatile: bool| { let load_as = |f: &mut FunctionBuilder<'_>, ty: TypeId, ptr: Value, volatile: bool| {
@@ -111,7 +92,6 @@ fn moved(how: Move) -> Entry {
volatile, volatile,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
) )
}; };
@@ -196,69 +176,6 @@ fn moved(how: Move) -> Entry {
let x = extract(&mut f, i32t, whole, 1); let x = extract(&mut f, i32t, whole, 1);
store_as(&mut f, x, 4); store_as(&mut f, x, 4);
} }
Move::Stack | Move::StackVolatile | Move::StackPointer | Move::StackWide => {
let ty = match how {
Move::StackPointer => with_ptr,
Move::StackWide => wide,
_ => stack_ty,
};
let zero = match how {
Move::StackPointer => ptr_zero,
Move::StackWide => wide_zero,
_ => stack_zero,
};
let slot = f.push(
m_thread,
InstKind::Alloca {
ty,
count: one,
align: None,
},
);
f.push_void(InstKind::Store {
val: zero,
ptr: slot,
align: Align::from_bytes(8),
volatile: false,
atomic: None,
});
{
let live = load_as(&mut f, i32t, arg(0), false);
let field1 = f.push(
m_thread,
InstKind::Gep {
src_ty: ty,
base: slot,
indices: [zero64, one].into(),
inbounds: true,
},
);
f.push_void(InstKind::Store {
val: live,
ptr: field1,
align: Align::from_bytes(4),
volatile: false,
atomic: None,
});
}
// The slot is 8-aligned (its zero store says so), and so is the whole load.
let whole = f.push(
ty,
InstKind::Load {
ptr: slot,
align: Align::from_bytes(8),
volatile: how == Move::StackVolatile,
atomic: None,
range: None,
speculative: false,
},
);
let x = match how {
Move::StackWide => extract(&mut f, f32t, whole, 7),
_ => extract(&mut f, i32t, whole, 1),
};
store_as(&mut f, x, 4);
}
Move::Wide => { Move::Wide => {
let whole = load_as(&mut f, wide, arg(0), false); let whole = load_as(&mut f, wide, arg(0), false);
let x = extract(&mut f, f32t, whole, 7); let x = extract(&mut f, f32t, whole, 7);
@@ -333,36 +250,6 @@ fn a_threadgroup_aggregate_is_split() {
assert_eq!(text.matches("store ").count(), 3, "{text}"); assert_eq!(text.matches("store ").count(), 3, "{text}");
} }
/// A whole struct stored to and loaded from a stack allocation, where the rest of the body
/// writes it in part, is its members' accesses as a buffer's is: the zero store is two member
/// stores (aligned 8 and 8, the second at byte 8), the whole load two member loads (8 and 8)
/// joined by two `insertvalue`s from `undef`, and no access of the whole struct is left.
#[test]
fn a_stack_aggregate_is_split() {
let text = body_text(&moved(Move::Stack));
let lines = |what: &str| text.lines().filter(|l| l.contains(what)).count();
assert_eq!(lines("load %t7"), 0, "{text}");
assert_eq!(lines("store %t7"), 0, "{text}");
assert_eq!(lines("alloca"), 1, "{text}");
assert_eq!(
lines("extractvalue <2 x float> %t7 zeroinitializer, 0"),
1,
"{text}"
);
assert_eq!(
lines("extractvalue i32 %t7 zeroinitializer, 1"),
1,
"{text}"
);
assert_eq!(lines("store %i1, %i0, align 8"), 1, "{text}");
assert_eq!(lines("store %i3, %i4, align 8"), 1, "{text}");
assert_eq!(lines("load <2 x float>, %i0, align 8"), 1, "{text}");
assert_eq!(lines("load i32, %i11, align 8"), 1, "{text}");
assert_eq!(lines("getelementptr inbounds i8, %i0, i64 8"), 2, "{text}");
assert_eq!(lines("insertvalue"), 2, "{text}");
assert_eq!(lines("insertvalue %t7 undef"), 1, "{text}");
}
/// A volatile access, an aggregate that holds a pointer, and one of more members than the split /// A volatile access, an aggregate that holds a pointer, and one of more members than the split
/// takes stay whole. /// takes stay whole.
#[test] #[test]
@@ -371,9 +258,6 @@ fn what_is_not_split_stays_whole() {
(Move::Volatile, "load volatile %t8"), (Move::Volatile, "load volatile %t8"),
(Move::PointerStruct, "load %t5"), (Move::PointerStruct, "load %t5"),
(Move::Wide, "load %t5"), (Move::Wide, "load %t5"),
(Move::StackVolatile, "load volatile %t7"),
(Move::StackPointer, "= load %t"),
(Move::StackWide, "= load %t"),
] { ] {
let text = body_text(&moved(how)); let text = body_text(&moved(how));
assert!(text.contains(whole), "{how:?}: {text}"); assert!(text.contains(whole), "{how:?}: {text}");
@@ -1,330 +0,0 @@
//! A kernel's plain loads of its constant references, made in its entry block ahead of its bounds
//! branch (`canon::const_hoist`), and the loads that stay where they are.
use super::*;
/// What lies between the kernel's start and its loads of `scale` and `p.bias`, or how they are
/// reached.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Shape {
/// The bounds branch alone.
Bounds,
/// A store to `out` behind the branch, before the loads.
StoreBefore,
/// An atomic add to `out` behind the branch, before the loads.
AtomicBefore,
/// `scale` read by a function called behind the branch, which stores to `out` first.
CalleeWrites,
/// `p.bias` read as `(&p.first)[gid & 1]`, its offset computed behind the branch.
PointerBehind,
/// `scale` a `constant float*`, which states no object size.
Pointer,
/// `p.bias` read at byte 8, past `p`'s 8 bytes.
PastObject,
/// `scale`'s pointer also chosen by a `select` against a pointer loaded from `out`, and read
/// through it: another root shares it.
Shared,
}
/// `kernel k(device float* out [[buffer(0)]], constant uint& n [[buffer(1)]], constant float&
/// scale [[buffer(2)]], constant P& p [[buffer(3)]], uint gid [[thread_position_in_grid]])`, with
/// `struct P { float first; float bias; }`: `if (gid >= n) return; out[gid] = float(gid) * scale +
/// p.bias;`, `shape` adding what it says. The bounds-branch shape of the kernels the hoist was
/// measured on, synthetic.
fn kernel_of(shape: Shape) -> Entry {
let mut m = ModuleBuilder::new();
let void = m.void();
let i1 = m.int(1);
let i8t = m.int(8);
let i32t = m.int(32);
let i64t = m.int(64);
let f32t = m.float();
let dev = m.ptr(AddrSpace::Device);
let cst = m.ptr(AddrSpace::Constant);
let zero_f = m.constant(f32t, Const::Float(0f32.to_bits().into()));
let zero_f = Value::Const(zero_f);
let (zero, one, two) = (
m.const_int(i32t, 0),
m.const_int(i32t, 1),
m.const_int(i32t, 2),
);
let no = m.const_int(i1, 0);
let bias_at = m.const_int(
i64t,
match shape {
Shape::PastObject => 8,
_ => 4,
},
);
// `float h(device float* out, constant float& s, uint gid) { out[gid] = 0; return s; }`
let h = {
let hty = m.fn_ty(f32t, &[dev, cst, i32t]);
let mut f = m.define("h", hty);
let o = f.push(
dev,
InstKind::Gep {
src_ty: f32t,
base: arg(0),
indices: [arg(2)].into(),
inbounds: true,
},
);
store(&mut f, zero_f, o);
let v = load(&mut f, f32t, arg(1));
f.ret(Some(v));
f.finish()
};
let add_ty = m.fn_ty(i32t, &[dev, i32t, i32t, i32t, i1]);
let add = m.declare("air.atomic.global.add.u.i32", add_ty);
let add_op = AirIntrinsic::parse("air.atomic.global.add.u.i32").unwrap();
let fty = m.fn_ty(void, &[dev, cst, cst, cst, i32t]);
let mut f = m.define("k", fty);
let (then, exit) = (f.block(), f.block());
let n = load(&mut f, i32t, arg(1));
let past = f.push(
i1,
InstKind::ICmp {
pred: IntPredicate::Uge,
a: arg(4),
b: n,
},
);
f.cond_br(past, exit, then);
f.switch_to(then);
let o = f.push(
dev,
InstKind::Gep {
src_ty: f32t,
base: arg(0),
indices: [arg(4)].into(),
inbounds: true,
},
);
match shape {
Shape::StoreBefore => store(&mut f, zero_f, o),
Shape::AtomicBefore => {
call(
&mut f,
i32t,
Callee::Air {
decl: add,
op: add_op,
},
&[arg(0), one, zero, two, no],
);
}
_ => {}
}
let scale = match shape {
Shape::CalleeWrites => call(&mut f, f32t, Callee::Direct(h), &[arg(0), arg(2), arg(4)]),
_ => load(&mut f, f32t, arg(2)),
};
let bias_ptr = match shape {
Shape::PointerBehind => {
let k = f.bin(BinOp::And, arg(4), one);
f.push(
cst,
InstKind::Gep {
src_ty: f32t,
base: arg(3),
indices: [k].into(),
inbounds: true,
},
)
}
_ => f.push(
cst,
InstKind::Gep {
src_ty: i8t,
base: arg(3),
indices: [bias_at].into(),
inbounds: true,
},
),
};
let bias = load(&mut f, f32t, bias_ptr);
let shared = match shape {
Shape::Shared => {
let loaded = load(&mut f, cst, arg(0));
let first = f.push(
i1,
InstKind::ICmp {
pred: IntPredicate::Eq,
a: arg(4),
b: zero,
},
);
let either = f.push(
cst,
InstKind::Select {
c: first,
t: arg(2),
f: loaded,
fmf: FastMath::NONE,
},
);
Some(load(&mut f, f32t, either))
}
_ => None,
};
let g = f.push(
f32t,
InstKind::Cast {
op: CastOp::UIToFP,
v: arg(4),
},
);
let x = f.bin(BinOp::FMul, g, scale);
let y = f.bin(BinOp::FAdd, x, bias);
let y = match shared {
Some(v) => f.bin(BinOp::FAdd, y, v),
None => y,
};
store(&mut f, y, o);
f.br(exit);
f.switch_to(exit);
f.ret(None);
let k = f.finish();
let module = m.finish().unwrap();
let reference = |param: u32, size: Option<u32>| {
let mut b = buffer(param, param);
if let ParamRole::Buffer(a) = &mut b.role {
a.access = Access::Read;
a.space = AddrSpace::Constant;
a.buffer_size = size;
}
b
};
let scale_size = match shape {
Shape::Pointer => None,
_ => Some(4),
};
let gid = ParamBinding {
param: 4,
role: ParamRole::Builtin(crate::abi::Builtin::ThreadPositionInGrid),
unused: false,
predicate: None,
ty: ArgTypeInfo::default(),
name: Some(DiagName::new("gid")),
};
let params = vec![
buffer(0, 0),
reference(1, Some(4)),
reference(2, scale_size),
reference(3, Some(8)),
gid,
];
let abi = abi(vec![kernel(k, params)], Vec::new());
specialize(module, &abi, &request(&[]), &mut meter()).unwrap()
}
/// The loads of the specialized kernel in its entry block and in its other blocks, and whether a
/// store lies in its entry block.
fn placed(e: &Entry) -> (usize, usize, bool) {
let body = e.module.func(e.func).unwrap().body.as_ref().unwrap();
let (mut entry, mut elsewhere, mut stored) = (0, 0, false);
for (b, _) in body.blocks.iter() {
for (_, i) in body.block_insts(b) {
match (&i.kind, b.index() == 0) {
(InstKind::Load { .. }, true) => entry += 1,
(InstKind::Load { .. }, false) => elsewhere += 1,
(InstKind::Store { .. }, at_entry) => stored |= at_entry,
_ => {}
}
}
}
(entry, elsewhere, stored)
}
/// The speculative loads of the specialized kernel, each in its entry block: the loads the hoist
/// made there, where the program ran them behind the branch.
fn speculative(e: &Entry) -> usize {
let body = e.module.func(e.func).unwrap().body.as_ref().unwrap();
let mut n = 0;
for (b, _) in body.blocks.iter() {
for (_, i) in body.block_insts(b) {
if let InstKind::Load {
speculative: true, ..
} = i.kind
{
assert_eq!(b.index(), 0, "a speculative load outside the entry block");
n += 1;
}
}
}
n
}
/// Behind the bounds branch alone, the loads of `scale` and of `p.bias` (with its address) are made
/// in the entry block beside `n`'s; the store stays behind the branch.
#[test]
fn a_constant_reference_read_behind_the_bounds_branch_is_read_in_the_entry_block() {
let e = kernel_of(Shape::Bounds);
assert_eq!(placed(&e), (3, 0, false), "{}", body_text(&e));
// `scale`'s and `p.bias`'s, which the program read behind the branch; `n`'s it read there.
assert_eq!(speculative(&e), 2, "{}", body_text(&e));
}
/// A store to device memory before the loads keeps them behind the branch: `out` may cover the
/// constant buffer's bytes.
#[test]
fn a_store_before_the_load_keeps_it_where_it_is() {
let e = kernel_of(Shape::StoreBefore);
assert_eq!(placed(&e), (1, 2, false), "{}", body_text(&e));
assert_eq!(speculative(&e), 0, "{}", body_text(&e));
}
/// An atomic before the loads keeps them behind the branch.
#[test]
fn an_atomic_before_the_load_keeps_it_where_it_is() {
let e = kernel_of(Shape::AtomicBefore);
assert_eq!(placed(&e), (1, 2, false), "{}", body_text(&e));
assert_eq!(speculative(&e), 0, "{}", body_text(&e));
}
/// A load in a callee that writes `out` first keeps it, and the load after the call, behind the
/// branch once the callee is inlined.
#[test]
fn a_load_in_a_callee_that_writes_keeps_it_where_it_is() {
let e = kernel_of(Shape::CalleeWrites);
assert_eq!(placed(&e), (1, 2, false), "{}", body_text(&e));
assert_eq!(speculative(&e), 0, "{}", body_text(&e));
}
/// A load whose address the branch's block computes stays; `scale`'s, at the parameter itself, is
/// made in the entry block.
#[test]
fn a_pointer_computed_behind_the_branch_keeps_its_load_where_it_is() {
let e = kernel_of(Shape::PointerBehind);
assert_eq!(placed(&e), (2, 1, false), "{}", body_text(&e));
assert_eq!(speculative(&e), 1, "{}", body_text(&e));
}
/// A load through a `constant float*`, which states no object size, stays; `p.bias`'s is made in
/// the entry block.
#[test]
fn a_constant_pointer_without_an_object_size_keeps_its_load_where_it_is() {
let e = kernel_of(Shape::Pointer);
assert_eq!(placed(&e), (2, 1, false), "{}", body_text(&e));
assert_eq!(speculative(&e), 1, "{}", body_text(&e));
}
/// A load past the referenced object's bytes stays; `scale`'s is made in the entry block.
#[test]
fn a_load_past_the_object_keeps_it_where_it_is() {
let e = kernel_of(Shape::PastObject);
assert_eq!(placed(&e), (2, 1, false), "{}", body_text(&e));
assert_eq!(speculative(&e), 1, "{}", body_text(&e));
}
/// A reference whose pointer a `select` shares with a pointer loaded from memory keeps its loads
/// where they are: lowering may reach it through a device address no check bounds. `p.bias`'s is
/// made in the entry block.
#[test]
fn a_reference_another_root_shares_keeps_its_loads_where_they_are() {
let e = kernel_of(Shape::Shared);
// `n`'s and `p.bias`'s in the entry block; `scale`'s, the loaded pointer's and the selected
// load behind the branch.
assert_eq!(placed(&e), (2, 3, false), "{}", body_text(&e));
assert_eq!(speculative(&e), 1, "{}", body_text(&e));
}
@@ -332,6 +332,12 @@ attributes #3 = { nounwind willreturn }\n\
/// [`IMAGES`] specialized, in OpenCL mode where `open_cl_mode`; `None` without `llvm-as`. /// [`IMAGES`] specialized, in OpenCL mode where `open_cl_mode`; `None` without `llvm-as`.
fn images(test: &str, open_cl_mode: bool) -> Option<Entry> { fn images(test: &str, open_cl_mode: bool) -> Option<Entry> {
images_bound(test, open_cl_mode, BTreeSet::new())
}
/// [`IMAGES`] specialized, in OpenCL mode where `open_cl_mode`, a 1D texture bound for each 1D
/// image at a texture index of `lines`; `None` without `llvm-as`.
fn images_bound(test: &str, open_cl_mode: bool, lines: BTreeSet<u32>) -> Option<Entry> {
let bitcode = match metal2vulkan_devtools::llvm_assemble_text(&format!("{HEAD}{IMAGES}")) { let bitcode = match metal2vulkan_devtools::llvm_assemble_text(&format!("{HEAD}{IMAGES}")) {
Ok(b) => b, Ok(b) => b,
Err(e) => { Err(e) => {
@@ -343,6 +349,7 @@ fn images(test: &str, open_cl_mode: bool) -> Option<Entry> {
let req = SpecRequest { let req = SpecRequest {
entry: "img".into(), entry: "img".into(),
open_cl_mode, open_cl_mode,
open_cl_lines: lines,
..SpecRequest::default() ..SpecRequest::default()
}; };
Some(specialize(d.module, &d.abi, &req, &mut meter()).expect("specialized")) Some(specialize(d.module, &d.abi, &req, &mut meter()).expect("specialized"))
@@ -506,15 +513,52 @@ fn opencl_1d_images_are_read_written_and_queried_as_2d_textures() {
); );
} }
/// In OpenCL mode each 1D image takes the type of the 2D texture Apple's OpenCL binds for it /// A 1D image a 1D texture is bound for (`SpecRequest::open_cl_lines`), which Apple's OpenCL never
/// (`texture1d` as `texture2d`, `texture1d_array` as `texture2d_array`); without the mode each /// binds, keeps its type and its 1D operations, which read that texture; every other 1D image is
/// keeps its own. /// the 2D texture's still. The entry names its 1D images in OpenCL mode alone, whatever is bound.
#[test] #[test]
fn opencl_1d_images_take_their_2d_textures_types() { fn opencl_1d_images_bound_to_1d_textures_keep_their_1d_operations() {
let test = "opencl_1d_images_take_their_2d_textures_types"; use crate::intrinsics::{ImageDim, Query};
let (Some(plain), Some(cl)) = (images(test, false), images(test, true)) else { let test = "opencl_1d_images_bound_to_1d_textures_keep_their_1d_operations";
let (Some(plain), Some(cl), Some(lines)) = (
images(test, false),
images(test, true),
images_bound(test, true, BTreeSet::from([1, 2])),
) else {
return; return;
}; };
let ops = |e: &Entry| {
let mut v: Vec<_> = texture_ops(e)
.into_iter()
.filter(|(op, ..)| {
!matches!(
op,
TexOp::Query(Query::ChannelOrder | Query::ChannelDataType)
)
})
.collect();
v.sort();
v
};
let width = TexOp::Query(Query::Width);
let layers = TexOp::Query(Query::ArraySize);
let sample = |e: &Entry| {
texture_ops(e)
.into_iter()
.find(|(op, ..)| matches!(op, TexOp::Sample { .. }))
.expect("a sample")
.0
};
// `b` (texture 1) and `c` (texture 2) stay 1D; `d` (texture 3) writes its 2D texture.
let mut want = vec![
(layers, ImageDim::D1, true),
(TexOp::Read, ImageDim::D1, false),
(sample(&lines), ImageDim::D1, true),
(width, ImageDim::D1, false),
(TexOp::Write, ImageDim::D2, false),
];
want.sort();
assert_eq!(ops(&lines), want, "{}", print(&lines.module));
let names = |e: &Entry| -> Vec<(u32, String)> { let names = |e: &Entry| -> Vec<(u32, String)> {
e.ep.params e.ep.params
.iter() .iter()
@@ -527,6 +571,15 @@ fn opencl_1d_images_take_their_2d_textures_types() {
}) })
.collect() .collect()
}; };
assert_eq!(
names(&lines),
[
(0, "texture2d<unknown, read>".to_owned()),
(1, "texture1d<unknown, read>".to_owned()),
(2, "texture1d_array<unknown, read>".to_owned()),
(3, "texture2d<unknown, write>".to_owned()),
]
);
assert_eq!( assert_eq!(
names(&cl), names(&cl),
[ [
@@ -536,15 +589,9 @@ fn opencl_1d_images_take_their_2d_textures_types() {
(3, "texture2d<unknown, write>".to_owned()), (3, "texture2d<unknown, write>".to_owned()),
] ]
); );
assert_eq!( assert_eq!(cl.open_cl_1d_images, BTreeSet::from([1, 2, 3]));
names(&plain), assert_eq!(lines.open_cl_1d_images, BTreeSet::from([1, 2, 3]));
[ assert!(plain.open_cl_1d_images.is_empty());
(0, "texture2d<unknown, read>".to_owned()),
(1, "texture1d<unknown, read>".to_owned()),
(2, "texture1d_array<unknown, read>".to_owned()),
(3, "texture1d<unknown, write>".to_owned()),
]
);
} }
#[test] #[test]
@@ -229,8 +229,7 @@ fn an_absent_value_stored_into_private_bytes_nothing_reads_is_unobserved() {
} }
/// Every read that reaches the gated-off field's bytes observes the store: the field itself, an /// Every read that reaches the gated-off field's bytes observes the store: the field itself, an
/// aggregate load covering it (split into its members' loads, joined from an `undef` by /// aggregate load covering it, one byte of it, the field through the pointer loaded back from the
/// `insertvalue`), one byte of it, the field through the pointer loaded back from the
/// cell, a copy of the struct, and any read once the struct's address escapes. The observed value /// cell, a copy of the struct, and any read once the struct's address escapes. The observed value
/// reads zero. /// reads zero.
#[test] #[test]
@@ -249,15 +248,7 @@ fn a_read_that_reaches_an_absent_value_in_private_memory_observes_it() {
text.contains("store i32 zeroinitializer"), text.contains("store i32 zeroinitializer"),
"{reach:?}: {text}" "{reach:?}: {text}"
); );
// The one `undef` left is the start of the `insertvalue` chain that joins a split load's assert!(!text.contains("undef"), "{reach:?}: {text}");
// members: `insertvalue %tN undef %iM, 0`.
let observed_undef = text.lines().any(|l| {
l.contains("undef")
&& !(l.contains("= insertvalue %t")
&& l.contains(" undef %i")
&& l.ends_with(", 0"))
});
assert!(!observed_undef, "{reach:?}: {text}");
assert!(!text.contains("%a1"), "{reach:?}: {text}"); assert!(!text.contains("%a1"), "{reach:?}: {text}");
} }
} }
@@ -157,7 +157,6 @@ fn a_side_effect_nothing_uses_stays() {
volatile: true, volatile: true,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
); );
air_call(f, "air.wg.barrier", void, &[i32t, i32t], &[two, one]); air_call(f, "air.wg.barrier", void, &[i32t, i32t], &[two, one]);
@@ -3280,9 +3280,8 @@ fn layouts_poison_on_overflow() {
assert!(!sig.matches(&t, ty)); assert!(!sig.matches(&t, ty));
} }
/// Every name below, one or more of each known AIR family and the listed `llvm.*` name, decodes /// Every name below, one or more of each known AIR family, decodes here or its family is listed
/// here or its family is listed in [`UNDECODED`], never both; and every listed family has a name /// in [`UNDECODED`], never both; and every listed family has a name below.
/// below.
#[test] #[test]
fn known_families_decode_or_are_listed() { fn known_families_decode_or_are_listed() {
let names = [ let names = [
@@ -3424,8 +3423,6 @@ fn known_families_decode_or_are_listed() {
"air.get_imageblock_num_colors", "air.get_imageblock_num_colors",
"air.get_color_coverage_mask", "air.get_color_coverage_mask",
"air.store.implicit_imageblock.mask.v4f16", "air.store.implicit_imageblock.mask.v4f16",
// MSL's `__builtin_trap`: listed, not decoded (an `llvm.*` name never decodes as `air.*`).
"llvm.trap",
]; ];
for name in names { for name in names {
let listed = undecoded_family(name).is_some(); let listed = undecoded_family(name).is_some();
@@ -683,25 +683,6 @@ impl LlvmIntrinsic {
}) })
} }
/// The signature of the declaration an older LLVM wrote for a memory intrinsic, which has an
/// `i32` alignment before the volatile flag; `None` for any other operation.
pub(super) fn legacy_signature(&self) -> Option<Signature> {
let sig = self.signature()?;
let (ret, params) = (sig.ret, sig.params());
match self {
LlvmIntrinsic::Memset { .. }
| LlvmIntrinsic::Memcpy { .. }
| LlvmIntrinsic::Memmove { .. } => {
let (head, flag) = params.split_at(params.len().checked_sub(1)?);
let mut legacy = head.to_vec();
legacy.push(Operand::Imm(ImmKind::I32));
legacy.extend_from_slice(flag);
Some(Signature::new(ret, &legacy))
}
_ => None,
}
}
/// Read the call's immediates into the variant. /// Read the call's immediates into the variant.
pub(super) fn bind(self, imm: &Immediates<'_>) -> Result<LlvmIntrinsic, IntrinsicError> { pub(super) fn bind(self, imm: &Immediates<'_>) -> Result<LlvmIntrinsic, IntrinsicError> {
Ok(match self { Ok(match self {
+5 -84
View File
@@ -30,8 +30,7 @@
//! queries, ray intersection (`air.intersect`), tensor descriptors, indirect commands, OpenCL C's //! queries, ray intersection (`air.intersect`), tensor descriptors, indirect commands, OpenCL C's
//! vector data loads and stores, MSL 4.1's generic-pointer space queries, and the //! vector data loads and stores, MSL 4.1's generic-pointer space queries, and the
//! closed `llvm.*` set with the AGX family. Every other `air.*` name (names whose declarations have not been observed) stays //! closed `llvm.*` set with the AGX family. Every other `air.*` name (names whose declarations have not been observed) stays
//! unknown, as does every other `llvm.*` name. [`UNDECODED`] lists the known families and names //! unknown. [`UNDECODED`] lists the known families among them, and the intrinsic census of the
//! among them (`llvm.trap` the one `llvm.*` name), and the intrinsic census of the
//! `bitcode-reader` audit reports every unknown name with row counts. [`UNDECODED_FEATURES`] names //! `bitcode-reader` audit reports every unknown name with row counts. [`UNDECODED_FEATURES`] names
//! the undecoded families that belong to a typed feature not implemented yet (intersection function //! the undecoded families that belong to a typed feature not implemented yet (intersection function
//! tables), so their calls are refused as that feature. //! tables), so their calls are refused as that feature.
@@ -300,10 +299,9 @@ impl AirIntrinsic {
} }
} }
/// The `air.*` families, and the `llvm.*` names, the decoder knows of but does not decode, each /// The `air.*` families the decoder knows of but does not decode, each with the reason: their
/// with the reason: their calls stay `Callee::UnknownIntrinsic`. This is the "listed" half of the /// calls stay `Callee::UnknownIntrinsic`. This is the "listed" half of the census contract: every
/// census contract: every corpus name decodes or matches an entry here. Each entry is a name /// corpus name decodes or matches an entry here. Each entry is a name prefix.
/// prefix.
pub const UNDECODED: &[(&str, &str)] = &[ pub const UNDECODED: &[(&str, &str)] = &[
( (
"air.function_constant_predicate", "air.function_constant_predicate",
@@ -334,14 +332,8 @@ pub const UNDECODED: &[(&str, &str)] = &[
"air.store.implicit_imageblock.mask.", "air.store.implicit_imageblock.mask.",
MULTISAMPLE_IMAGEBLOCK, MULTISAMPLE_IMAGEBLOCK,
), ),
// MSL's `__builtin_trap`: a call, then `unreachable`.
("llvm.trap", TRAP),
]; ];
/// The reason `llvm.trap` is [`UNDECODED`].
const TRAP: &str = "MSL and Metal's headers do not define a reached trap; a trap that survives \
canonicalization is refused as an unknown intrinsic";
/// The reason a multisample imageblock's operations are [`UNDECODED`]. /// The reason a multisample imageblock's operations are [`UNDECODED`].
const MULTISAMPLE_IMAGEBLOCK: &str = "a multisample imageblock's sample count, colors, coverage \ const MULTISAMPLE_IMAGEBLOCK: &str = "a multisample imageblock's sample count, colors, coverage \
masks and masked stores: tile functions and fragment \ masks and masked stores: tile functions and fragment \
@@ -474,14 +466,7 @@ pub fn classify(name: &[u8], sym: Sym, fn_ty: TypeId, types: &TypeTable) -> Opti
match llvm::parse(rest, sym, types, fn_ty) { match llvm::parse(rest, sym, types, fn_ty) {
Ok(llvm::Parsed::Dropped(d)) => DeclClass::Drop(d), Ok(llvm::Parsed::Dropped(d)) => DeclClass::Drop(d),
Ok(llvm::Parsed::Kept(op)) => match op.signature() { Ok(llvm::Parsed::Kept(op)) => match op.signature() {
Some(sig) Some(sig) if !sig.matches(types, fn_ty) => DeclClass::Mismatch,
if !sig.matches(types, fn_ty)
&& !op
.legacy_signature()
.is_some_and(|legacy| legacy.matches(types, fn_ty)) =>
{
DeclClass::Mismatch
}
_ => DeclClass::Llvm(op), _ => DeclClass::Llvm(op),
}, },
Err(llvm::Fail::Unknown) => DeclClass::Unknown, Err(llvm::Fail::Unknown) => DeclClass::Unknown,
@@ -565,67 +550,3 @@ pub fn bind(
DeclClass::Drop(_) | DeclClass::Unknown => Ok(Bound::Unknown), DeclClass::Drop(_) | DeclClass::Unknown => Ok(Bound::Unknown),
} }
} }
/// What upgrading a legacy memory intrinsic's call removed: the alignment it stated, and the
/// operand position it held.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct LegacyAlignment {
/// The alignment; `None` for an alignment of 0, which states none.
pub align: Option<crate::ir::Align>,
/// The position of the removed operand (3), whose attributes go with it.
pub removed: usize,
/// The pointer operands it applies to: the destination, and the source of a copy.
pub pointers: usize,
}
/// Why a legacy memory intrinsic's call is not upgraded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum LegacyAlignmentError {
/// The alignment is not a constant ([`IntrinsicError::ImmediateNotConstant`]).
Intrinsic(IntrinsicError),
/// The alignment is a constant that is not a power of two, or is above 2^32: a malformed
/// record, as an `align` attribute of that value is.
Malformed,
}
/// Upgrade a call of a memory intrinsic declared with an `i32` alignment before the volatile flag
/// (`llvm.memcpy.p0i8.p0i8.i64(i8*, i8*, i64, i32, i1)`) to the current form, as LLVM's reader
/// upgrades it (`UpgradeIntrinsicCall`): the alignment operand is removed from `args` and returned,
/// and the caller removes that position's attributes and sets the pointer operands' `align` to it
/// (`setDestAlignment`, `setSourceAlignment`: replacing any the call states, and removing it for
/// an alignment of 0). `Ok(None)` for any other call. An alignment that is not a constant is
/// [`IntrinsicError::ImmediateNotConstant`], and a malformed one (not a power of two, or above
/// 2^32), which LLVM's verifier refuses, is [`LegacyAlignmentError::Malformed`].
pub(crate) fn upgrade_legacy_memory(
class: DeclClass,
args: &mut Vec<Value>,
consts: &ConstTable,
) -> Result<Option<LegacyAlignment>, LegacyAlignmentError> {
let DeclClass::Llvm(op) = class else {
return Ok(None);
};
let Some(legacy) = op
.legacy_signature()
.filter(|legacy| legacy.params().len() == args.len())
else {
return Ok(None);
};
let removed = args.len().saturating_sub(2);
let bytes = Immediates::new(legacy, args, consts)
.get(removed)
.map_err(LegacyAlignmentError::Intrinsic)?;
let align = match bytes {
0 => None,
bytes => Some(crate::ir::Align::from_bytes(bytes).ok_or(LegacyAlignmentError::Malformed)?),
};
args.remove(removed);
let pointers = match op {
LlvmIntrinsic::Memset { .. } => 1,
_ => 2,
};
Ok(Some(LegacyAlignment {
align,
removed,
pointers,
}))
}
@@ -898,45 +898,6 @@ fn llvm_bases_decode_against_their_declarations() {
"{name}" "{name}"
); );
} }
// The declaration an older LLVM wrote: an `i32` alignment before the volatile flag.
let align = Operand::Imm(ImmKind::I32);
assert_eq!(
llvm(
"llvm.memcpy.p0i8.p1i8.i64",
void,
&[p0, p1, i64s, align, flag]
),
DeclClass::Llvm(LlvmIntrinsic::Memcpy {
dst: AddrSpace::Thread,
src: AddrSpace::Device,
len: Elem::I64,
volatile: false,
})
);
assert!(matches!(
llvm(
"llvm.memmove.p1i8.p1i8.i32",
void,
&[p1, p1, i32s, align, flag]
),
DeclClass::Llvm(LlvmIntrinsic::Memmove { .. })
));
assert!(matches!(
llvm(
"llvm.memset.p0i8.i64",
void,
&[p0, Operand::Num(NumTy::scalar(Elem::I8)), i64s, align, flag]
),
DeclClass::Llvm(LlvmIntrinsic::Memset { .. })
));
assert_eq!(
llvm(
"llvm.memcpy.p0i8.p1i8.i64",
void,
&[p0, p1, i64s, flag, flag]
),
DeclClass::Mismatch
);
let i8s = Operand::Num(NumTy::scalar(Elem::I8)); let i8s = Operand::Num(NumTy::scalar(Elem::I8));
assert!(matches!( assert!(matches!(
llvm("llvm.memset.p1.i32", void, &[p1, i8s, i32s, flag]), llvm("llvm.memset.p1.i32", void, &[p1, i8s, i32s, flag]),
@@ -1153,15 +1114,6 @@ fn markers_are_dropped() {
assert_eq!(bases.len(), 32); assert_eq!(bases.len(), 32);
} }
/// `llvm.trap` (MSL's `__builtin_trap`, a call followed by `unreachable`) is outside the closed
/// set and listed as not decoded: its calls stay `Callee::UnknownIntrinsic`, so a trap that
/// survives canonicalization is refused as an unknown intrinsic, and the census counts it listed.
#[test]
fn trap_is_listed_not_decoded() {
assert_eq!(llvm("llvm.trap", Operand::Void, &[]), DeclClass::Unknown);
assert!(undecoded_family("llvm.trap").is_some());
}
#[test] #[test]
fn handle_positions_are_typed_seeds() { fn handle_positions_are_typed_seeds() {
let texture = HandleKind::Texture(ImageShape { let texture = HandleKind::Texture(ImageShape {
-6
View File
@@ -163,12 +163,6 @@ pub enum InstKind {
atomic: Option<Atomic>, atomic: Option<Atomic>,
/// A `!range` attachment on the loaded value. /// A `!range` attachment on the loaded value.
range: Option<RangeMd>, range: Option<RangeMd>,
/// The load runs where the program does not run it: canonicalization made it out of the
/// branch's arm it stood in (a constant reference's load made in a kernel's entry block,
/// or a load of a branch's arm that Metal's backend speculates). A thread may then read
/// bytes the program never read, which its binding need not hold, so lowering contains
/// the access whatever its offset. A decoded load is never speculative.
speculative: bool,
}, },
/// `store` of `val` to `ptr`. /// `store` of `val` to `ptr`.
Store { Store {
-4
View File
@@ -319,7 +319,6 @@ impl Printer<'_> {
volatile, volatile,
atomic, atomic,
range, range,
speculative,
} => { } => {
self.out.push_str("load"); self.out.push_str("load");
self.atomic_prefix(*atomic, *volatile); self.atomic_prefix(*atomic, *volatile);
@@ -331,9 +330,6 @@ impl Printer<'_> {
if let Some(r) = range { if let Some(r) = range {
w!(self, ", !range {:?}", r.ranges); w!(self, ", !range {:?}", r.ranges);
} }
if *speculative {
self.out.push_str(", speculative");
}
} }
InstKind::Store { InstKind::Store {
val, val,
@@ -232,7 +232,6 @@ fn every_opcode_prints() {
volatile: true, volatile: true,
atomic, atomic,
range, range,
speculative: false,
}; };
let x = k.push(i32t, load); let x = k.push(i32t, load);
k.push_void(InstKind::Store { k.push_void(InstKind::Store {
-40
View File
@@ -38,7 +38,6 @@ use crate::budget::Meter;
use crate::error::Error; use crate::error::Error;
use crate::error::{DiagName, InputError, InputErrorKind, Location, VerifyError}; use crate::error::{DiagName, InputError, InputErrorKind, Location, VerifyError};
use crate::graph::{Cfg, DomTree}; use crate::graph::{Cfg, DomTree};
use crate::intrinsics::{LlvmIntrinsic, Template};
/// A verified AIR module. Immutable: passes consume it with [`Module::into_parts`] and build a /// A verified AIR module. Immutable: passes consume it with [`Module::into_parts`] and build a
/// new one through [`Module::new`]. /// new one through [`Module::new`].
@@ -917,45 +916,6 @@ impl<'a> Verifier<'a> {
let Some((ret, params, vararg)) = fn_sig(types, fn_ty) else { let Some((ret, params, vararg)) = fn_sig(types, fn_ty) else {
return operand(false); return operand(false);
}; };
// A memory intrinsic declared with an alignment operand (an older LLVM's form,
// its `i32` alignment before the `i1` volatile flag) is called without it: decode
// moved its value to the pointers' `align`. So is one whose volatile flag is not
// yet a constant (`Callee::Unbound`), which specialization binds as it binds the
// current form's.
let upgraded: Vec<TypeId>;
let legacy = |params: &[TypeId]| match params {
[.., align, flag] if params.len() == 5 => {
self.ty(*align) == Some(&Type::Int(32)) && self.is_i1(*flag)
}
_ => false,
};
let params = match call.callee {
Callee::Llvm {
op:
LlvmIntrinsic::Memset { .. }
| LlvmIntrinsic::Memcpy { .. }
| LlvmIntrinsic::Memmove { .. },
..
}
| Callee::Unbound {
template:
Template::Llvm(
LlvmIntrinsic::Memset { .. }
| LlvmIntrinsic::Memcpy { .. }
| LlvmIntrinsic::Memmove { .. },
),
..
} if !vararg && call.args.len() + 1 == params.len() && legacy(params) => {
upgraded = params
.iter()
.enumerate()
.filter(|&(i, _)| i + 2 != params.len())
.map(|(_, &p)| p)
.collect();
&upgraded[..]
}
_ => params,
};
let arity_ok = if vararg { let arity_ok = if vararg {
call.args.len() >= params.len() call.args.len() >= params.len()
} else { } else {
@@ -56,7 +56,6 @@ fn load(f: &mut FunctionBuilder<'_>, ty: TypeId, ptr: Value) -> Value {
volatile: false, volatile: false,
atomic: None, atomic: None,
range: None, range: None,
speculative: false,
}, },
) )
} }
@@ -506,7 +505,6 @@ fn instruction_typing_is_enforced() {
scope: SyncScope::System, scope: SyncScope::System,
}), }),
range: None, range: None,
speculative: false,
}, },
); );
}, },
@@ -1052,60 +1050,3 @@ fn dominance_is_charged_to_the_ledger_and_returned() {
Err(Error::LimitExceeded(crate::error::Limit::LedgerBytes)) Err(Error::LimitExceeded(crate::error::Limit::LedgerBytes))
); );
} }
/// A memory intrinsic's call is one operand short of its declaration only where the declaration is
/// the older LLVM's form, an `i32` alignment before the `i1` volatile flag (decode removed the
/// call's alignment operand): a call one short of the current four-parameter form, or of a
/// five-parameter declaration whose fourth parameter is not `i32`, is refused.
#[test]
fn a_memory_intrinsic_call_one_short_only_of_the_legacy_declaration() {
let call = |legacy: bool, align_ty_i32: bool, args: usize| {
let mut m = ModuleBuilder::new();
let t = tys(&mut m);
let i64t = m.int(64);
let mut params = vec![t.dev, t.dev, i64t];
if legacy {
params.push(if align_ty_i32 { t.i32 } else { i64t });
}
params.push(t.i1);
let decl_ty = m.fn_ty(t.void, &params);
let decl = m.declare("llvm.memcpy.p1i8.p1i8.i64", decl_ty);
let len = m.const_int(i64t, 16);
let no = m.const_int(t.i1, 0);
let fty = m.fn_ty(t.void, &[t.dev, t.i32]);
let mut f = m.define("k", fty);
let all = [f.arg(0), f.arg(0), len, no];
let args: Box<[Value]> = match args {
4 => all.into(),
_ => [all[0], all[1], all[3]].into(),
};
f.push(
t.void,
InstKind::Call(Box::new(Call {
callee: Callee::Llvm {
decl,
op: crate::intrinsics::LlvmIntrinsic::Memcpy {
dst: AddrSpace::Device,
src: AddrSpace::Device,
len: crate::intrinsics::Elem::I64,
volatile: false,
},
},
args,
fmf: FastMath::NONE,
tail: TailKind::None,
attrs: None,
range: None,
})),
);
f.ret(None);
f.finish();
m.finish()
};
// Four operands of the current declaration, and of the legacy one.
assert!(call(false, true, 4).is_ok());
assert!(call(true, true, 4).is_ok());
// One short of the current declaration, and of a five-parameter one without the `i32`.
assert_eq!(verify_kind(call(false, true, 3)), VerifyError::OperandType);
assert_eq!(verify_kind(call(true, false, 4)), VerifyError::OperandType);
}
File diff suppressed because it is too large. Load diff
@@ -24,8 +24,7 @@
// salt never used before): // salt never used before):
// - Made, answering (object threads, mesh threads, object width, mesh width, mesh grid): // - Made, answering (object threads, mesh threads, object width, mesh width, mesh grid):
// `plain` 1024, 1024, 32, 32, 1048576, and `maxTotalThreadsPerThreadgroup` 0 in every case; // `plain` 1024, 1024, 32, 32, 1048576, and `maxTotalThreadsPerThreadgroup` 0 in every case;
// `no-object` 3, 1024, 32, 32, 1048576; `max-64-32` 64 and 32; `max-1024-1024` as `plain` // `no-object` 3, 1024, 32, 32, 1048576; `max-64-32` 64 and 32; `attribute-64` and
// (plain only, a first compile, the same salt again and unsalted alike); `attribute-64` and
// `attribute-64-max-64` 64 for the object stage, `mesh-attribute-64` and // `attribute-64-max-64` 64 for the object stage, `mesh-attribute-64` and
// `mesh-attribute-64-max-64` 64 for the mesh stage; `grid-8` 8, `grid-2097152` 2097152, // `mesh-attribute-64-max-64` 64 for the mesh stage; `grid-8` 8, `grid-2097152` 2097152,
// `grid-8-no-object` 8; `grid-attribute-4` 1048576 (an object function's // `grid-8-no-object` 8; `grid-attribute-4` 1048576 (an object function's
@@ -118,7 +117,6 @@ static const Case CASES[] = {
{"plain", "obj", "msh", 0, 0, 0, 0, 1, Z, Z}, {"plain", "obj", "msh", 0, 0, 0, 0, 1, Z, Z},
{"no-object", NULL, "alone", 0, 0, 0, 0, 1, Z, Z}, {"no-object", NULL, "alone", 0, 0, 0, 0, 1, Z, Z},
{"max-64-32", "obj", "msh", 64, 32, 0, 0, 1, Z, Z}, {"max-64-32", "obj", "msh", 64, 32, 0, 0, 1, Z, Z},
{"max-1024-1024", "obj", "msh", 1024, 1024, 0, 0, 1, Z, Z},
{"max-object-2048", "obj", "msh", 2048, 0, 0, 0, 1, Z, Z}, {"max-object-2048", "obj", "msh", 2048, 0, 0, 0, 1, Z, Z},
{"max-mesh-2048", "obj", "msh", 0, 2048, 0, 0, 1, Z, Z}, {"max-mesh-2048", "obj", "msh", 0, 2048, 0, 0, 1, Z, Z},
{"max-mesh-2048-no-object", NULL, "alone", 0, 2048, 0, 0, 1, Z, Z}, {"max-mesh-2048-no-object", NULL, "alone", 0, 2048, 0, 0, 1, Z, Z},
@@ -14,8 +14,7 @@
// Cases: `set0` and `set1` (`newFunctionWithName:constantValues:` with constant 17, `b_set`, // Cases: `set0` and `set1` (`newFunctionWithName:constantValues:` with constant 17, `b_set`,
// false or true, every other constant undefined), `none` (`newFunctionWithName:`). Each prints // false or true, every other constant undefined), `none` (`newFunctionWithName:`). Each prints
// every constant's `required`, the pipeline's creation, and the 20 words the kernel stores // every constant's `required`, the pipeline's creation, and the 20 words the kernel stores
// (the buffer is filled with 0xAB first). A function Metal does not make prints the error's domain, // (the buffer is filled with 0xAB first). Case `gate` makes kernel `kg`, whose buffer 1 is gated
// code and text. Case `gate` makes kernel `kg`, whose buffer 1 is gated
// on `!g_flag` and on `g_flag` (buffers 1 and 2) with `g_flag` undefined, and prints the buffers // on `!g_flag` and on `g_flag` (buffers 1 and 2) with `g_flag` undefined, and prints the buffers
// its pipeline's reflection binds and the words it stores. // its pipeline's reflection binds and the words it stores.
// //
@@ -53,15 +52,6 @@
// - `empty` and `descriptor`, every shape: every function answers count 0, and the state is made; // - `empty` and `descriptor`, every shape: every function answers count 0, and the state is made;
// `ko` stores 7 (`o_opt` undefined), `kn` 9, `k` 0, and `kg` leaves word 0 as filled // `ko` stores 7 (`o_opt` undefined), `kn` 9, `k` 0, and `kg` leaves word 0 as filled
// (0xabababab). // (0xabababab).
// - `set0`: `k`'s constants but `u_opt` answer `required` 1; made with constant 17 alone, the
// function and the state are made and the command buffer completes: Metal refuses no required
// constant left without a value (macOS 27.0.1 build 26A434).
// - `ib/kib/empty`: the constant answers `required` 1; the function and the state are made, the
// imageblock length is 0, the buffer way runs (word 0 is 5) and the texture keeps -1, as for
// `zero`. `ib/kib2/empty`: made, the imageblock length is 1024, and the imageblock way runs
// (texel (0, 0) is (0, 0, 7, 9), (7, 7) is (7, 7, 7, 9)), as for `max`. On both, Metal takes
// the way the AIR's branch on `derived bool == 0` takes when that test is true, and keeps the
// imageblock where that way uses it. The constant's own read (word 1) stores nothing.
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <Metal/Metal.h> #import <Metal/Metal.h>
#include <stdio.h> #include <stdio.h>
@@ -149,7 +139,7 @@ static id<MTLFunction> made_as(id<MTLLibrary> L, const char *how, NSString *name
d.name = name; d.name = name;
f = [L newFunctionWithDescriptor:d error:&e]; f = [L newFunctionWithDescriptor:d error:&e];
} }
if (!f) { printf("RESULT function %s error domain=%s code=%ld %s\n", name.UTF8String, e.domain.UTF8String, (long)e.code, e.localizedDescription.UTF8String); exit(0); } if (!f) { printf("RESULT function %s error %s\n", name.UTF8String, e.localizedDescription.UTF8String); exit(0); }
printf("RESULT function %s %s constants=%lu\n", name.UTF8String, how, (unsigned long)f.functionConstantsDictionary.count); printf("RESULT function %s %s constants=%lu\n", name.UTF8String, how, (unsigned long)f.functionConstantsDictionary.count);
fflush(stdout); fflush(stdout);
return f; return f;
@@ -210,114 +200,13 @@ static int stage_case(id<MTLDevice> D, id<MTLCommandQueue> Q, id<MTLLibrary> L,
return 0; return 0;
} }
// Cases `ib/<kernel>/<how>`: an explicit imageblock argument gated on a program-scope bool
// derived from a required `uint` constant (`ib_mode`, index 40: the argument is there only for
// 0xffffffff), whose body writes a cell (`imageblock::data`) and the slice of the threadgroup's
// cells to a texture where that bool is true, and word 0 of a buffer otherwise. `kib` branches
// on the bool, `kib2` on its negation (the buffer write first). `how`: `empty` (made with no
// constant value), `zero` (`ib_mode` 0) or `max` (0xffffffff). Each prints the constant's
// `required` (of the function made by name, no pipeline made of it), the function's making, the
// compute state's making and its imageblock length for 8 by 8, then one 8 by 8 dispatch of an
// 8 by 8 threadgroup with an 8 by 8 imageblock: the command buffer's status, words 0 and 1 (5
// where the buffer way ran; the constant's read), and texel (0, 0) and (7, 7) of an
// RGBA32Float texture set to -1 first (the slice way writes (x, y, 7, 9)). Case `ib-source`
// prints that library's source, for `xcrun metal`.
static const char *SRC_IB =
"#include <metal_stdlib>\nusing namespace metal;\n"
"struct Cell { float4 colour; };\n"
"constant uint ib_mode [[function_constant(40)]];\n"
"constant bool ib_on = ib_mode == 0xffffffffu;\n"
"constant bool ib_off = ib_mode != 0xffffffffu;\n"
"constant bool ib_on2 = !ib_off;\n"
"kernel void kib(imageblock<Cell, imageblock_layout_explicit> block [[function_constant(ib_on)]],\n"
" texture2d<float, access::write> out [[texture(0)]], device uint *words [[buffer(0)]],\n"
" ushort2 lid [[thread_position_in_threadgroup]], ushort2 gid [[thread_position_in_grid]]) {\n"
" if (ib_on) {\n"
" threadgroup_imageblock Cell *cell = block.data(lid);\n"
" cell->colour = float4(float(gid.x), float(gid.y), 7.0, 9.0);\n"
" threadgroup_barrier(mem_flags::mem_threadgroup_imageblock);\n"
" if (lid.x == 0 && lid.y == 0) out.write(block.slice(block.data(ushort2(0))->colour), ushort2(0));\n"
" } else if (gid.x == 0 && gid.y == 0) {\n"
" words[0] = 5;\n"
" }\n"
" if (gid.x == 0 && gid.y == 0) words[1] = ib_mode;\n"
"}\n"
"kernel void kib2(imageblock<Cell, imageblock_layout_explicit> block [[function_constant(ib_on2)]],\n"
" texture2d<float, access::write> out [[texture(0)]], device uint *words [[buffer(0)]],\n"
" ushort2 lid [[thread_position_in_threadgroup]], ushort2 gid [[thread_position_in_grid]]) {\n"
" if (ib_off) {\n"
" if (gid.x == 0 && gid.y == 0) words[0] = 5;\n"
" } else {\n"
" threadgroup_imageblock Cell *cell = block.data(lid);\n"
" cell->colour = float4(float(gid.x), float(gid.y), 7.0, 9.0);\n"
" threadgroup_barrier(mem_flags::mem_threadgroup_imageblock);\n"
" if (lid.x == 0 && lid.y == 0) out.write(block.slice(block.data(ushort2(0))->colour), ushort2(0));\n"
" }\n"
" if (gid.x == 0 && gid.y == 0) words[1] = ib_mode;\n"
"}\n";
static int ib_case(id<MTLDevice> D, id<MTLCommandQueue> Q, const char *kernel, const char *how) {
NSError *e = nil;
id<MTLLibrary> L = [D newLibraryWithSource:[NSString stringWithUTF8String:SRC_IB] options:nil error:&e];
if (!L) { printf("RESULT library error domain=%s code=%ld %s\n", e.domain.UTF8String, (long)e.code, e.localizedDescription.UTF8String); return 1; }
NSString *name = [NSString stringWithUTF8String:kernel];
id<MTLFunction> plain = [L newFunctionWithName:name];
for (NSString *k in plain.functionConstantsDictionary) {
MTLFunctionConstant *fc = plain.functionConstantsDictionary[k];
printf("RESULT constant %lu type=%ld required=%d\n", (unsigned long)fc.index, (long)fc.type, fc.required);
}
MTLFunctionConstantValues *v = [MTLFunctionConstantValues new];
uint32_t mode = strcmp(how, "max") == 0 ? 0xffffffffu : 0;
if (strcmp(how, "empty") != 0) [v setConstantValue:&mode type:MTLDataTypeUInt atIndex:40];
id<MTLFunction> f = [L newFunctionWithName:name constantValues:v error:&e];
if (!f) { printf("RESULT function error domain=%s code=%ld %s\n", e.domain.UTF8String, (long)e.code, e.localizedDescription.UTF8String); return 0; }
printf("RESULT function made constants=%lu\n", (unsigned long)f.functionConstantsDictionary.count);
fflush(stdout);
id<MTLComputePipelineState> ps = [D newComputePipelineStateWithFunction:f error:&e];
if (!ps) { printf("RESULT pipeline error domain=%s code=%ld %s\n", e.domain.UTF8String, (long)e.code, e.localizedDescription.UTF8String); return 0; }
printf("RESULT pipeline made imageblock_length_8x8=%lu\n", (unsigned long)[ps imageblockMemoryLengthForDimensions:MTLSizeMake(8, 8, 1)]);
fflush(stdout);
MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:8 height:8 mipmapped:NO];
td.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead;
td.storageMode = MTLStorageModeShared;
id<MTLTexture> tex = [D newTextureWithDescriptor:td];
static float texels[8][8][4];
for (int i = 0; i < 8 * 8 * 4; i++) ((float *)texels)[i] = -1.0f;
[tex replaceRegion:MTLRegionMake2D(0, 0, 8, 8) mipmapLevel:0 withBytes:texels bytesPerRow:8 * 16];
id<MTLBuffer> words = [D newBufferWithLength:64 options:MTLResourceStorageModeShared];
memset(words.contents, 0xAB, 64);
id<MTLCommandBuffer> cb = [Q commandBuffer];
id<MTLComputeCommandEncoder> ce = [cb computeCommandEncoder];
[ce setComputePipelineState:ps];
[ce setTexture:tex atIndex:0];
[ce setBuffer:words offset:0 atIndex:0];
[ce setImageblockWidth:8 height:8];
[ce dispatchThreads:MTLSizeMake(8, 8, 1) threadsPerThreadgroup:MTLSizeMake(8, 8, 1)];
[ce endEncoding]; [cb commit]; [cb waitUntilCompleted];
[tex getBytes:texels bytesPerRow:8 * 16 fromRegion:MTLRegionMake2D(0, 0, 8, 8) mipmapLevel:0];
const uint32_t *w = words.contents;
printf("RESULT status=%ld%s%s words %08x %08x texel00 %g %g %g %g texel77 %g %g %g %g\n", (long)cb.status,
cb.error ? " error " : "", cb.error ? cb.error.localizedDescription.UTF8String : "", w[0], w[1],
texels[0][0][0], texels[0][0][1], texels[0][0][2], texels[0][0][3],
texels[7][7][0], texels[7][7][1], texels[7][7][2], texels[7][7][3]);
return 0;
}
int main(int argc, char **argv) { int main(int argc, char **argv) {
if (argc < 2) return 2; if (argc < 2) return 2;
const char *c = argv[1]; const char *c = argv[1];
if (strcmp(c, "ib-source") == 0) { fputs(SRC_IB, stdout); return 0; }
@autoreleasepool { @autoreleasepool {
printf("RESULT case=%s debug_layer=%s\n", c, getenv("MTL_DEBUG_LAYER") ? getenv("MTL_DEBUG_LAYER") : "unset"); printf("RESULT case=%s debug_layer=%s\n", c, getenv("MTL_DEBUG_LAYER") ? getenv("MTL_DEBUG_LAYER") : "unset");
id<MTLDevice> D = MTLCreateSystemDefaultDevice(); id<MTLDevice> D = MTLCreateSystemDefaultDevice();
id<MTLCommandQueue> Q = [D newCommandQueue]; id<MTLCommandQueue> Q = [D newCommandQueue];
if (strncmp(c, "ib/", 3) == 0) {
char kernel[16] = {0};
const char *slash = strchr(c + 3, '/');
if (!slash || (size_t)(slash - c - 3) >= sizeof kernel) return 2;
memcpy(kernel, c + 3, (size_t)(slash - c - 3));
return ib_case(D, Q, kernel, slash + 1);
}
NSError *e = nil; NSError *e = nil;
id<MTLLibrary> L = [D newLibraryWithSource:[NSString stringWithUTF8String:SRC] options:nil error:&e]; id<MTLLibrary> L = [D newLibraryWithSource:[NSString stringWithUTF8String:SRC] options:nil error:&e];
if (!L) { printf("RESULT library error %s\n", e.localizedDescription.UTF8String); return 1; } if (!L) { printf("RESULT library error %s\n", e.localizedDescription.UTF8String); return 1; }
@@ -361,7 +250,7 @@ int main(int argc, char **argv) {
BOOL b = strcmp(c, "set1") == 0; BOOL b = strcmp(c, "set1") == 0;
[v setConstantValue:&b type:MTLDataTypeBool atIndex:17]; [v setConstantValue:&b type:MTLDataTypeBool atIndex:17];
f = [L newFunctionWithName:@"k" constantValues:v error:&e]; f = [L newFunctionWithName:@"k" constantValues:v error:&e];
if (!f) { printf("RESULT function error domain=%s code=%ld %s\n", e.domain.UTF8String, (long)e.code, e.localizedDescription.UTF8String); return 0; } if (!f) { printf("RESULT function error %s\n", e.localizedDescription.UTF8String); return 0; }
} }
id<MTLComputePipelineState> ps = [D newComputePipelineStateWithFunction:f error:&e]; id<MTLComputePipelineState> ps = [D newComputePipelineStateWithFunction:f error:&e];
if (!ps) { printf("RESULT pipeline error %s\n", e.localizedDescription.UTF8String); return 0; } if (!ps) { printf("RESULT pipeline error %s\n", e.localizedDescription.UTF8String); return 0; }
@@ -1,699 +0,0 @@
{
"format": 1,
"case": "chroma-pair-texel-gathers-bgrg422",
"suite_version": 1,
"shaders": [
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_gather_x",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_gather_x",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
},
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_gather_y",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_gather_y",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
},
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_gather_z",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_gather_z",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
},
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_gather_w",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_gather_w",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
}
}
},
{
"name": "entry",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "ec15cf47f4671624c66cfd2215ddd6b49f606a9836b21bf5d6efe51120a17250"
}
}
},
{
"name": "format",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "946e5fffd5aeab455618b623ec6cbc5ec6f26e67320db4f4ea7f2c62bef85bcc"
}
}
},
{
"name": "texture:bytes",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "97d94990adf22069b968c7e737659f3deec9487277219fd99998f04df0bbcce5"
}
}
},
{
"name": "positions",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1bdb601fe30639f55df17904745a273ecbdd7cfaaf2375fdc7c7168ef085b46b"
}
}
},
{
"name": "buffer:blank",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "087d80f7f182dd44f184aa86ca34488853ebcc04f0c60d5294919a466b463831"
}
}
},
{
"name": "sampler",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "640e494dd31edb66b0748239aa90547d77e8ab37843b5bc8352a5f39e5296f06"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "positions",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "sampler",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/bgrg422/gathers/x",
"observed": {
"value": {
"bytes": "gYAAPPX0dD6npiY/lpUVP/X0dD61tDQ/yslJP6emJj+1tDQ/4uFhP9LRUT/KyUk/4uFhP8XERD+/vj4/0tFRP8XERD+joiI/mZgYP7++Pj+joiI/9/b2PsPCwj6ZmBg/9/b2Pru6uj6lpKQ+w8LCPru6uj6RkJA+19bWPqWkpD6RkJA+0dBQPo6NDT/X1tY+0dBQPomICD65uDg/jo0NP4mICD6Lioo+pqUlP7m4OD+Lioo+nZwcP6uqqj6mpSU/nZwcP7a1NT+1tLQ+q6qqPra1NT+SkRE/tLMzP7W0tD6SkRE///7+PuHgYD+0szM///7+Pv/+/j7h4GA/4eBgP+/u7j7DwsI+9fR0PoGAADzDwsI+1dRUPrW0ND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oyLCz/b2to+nZwcP83MTD6bmpo+nZwcP7u6Oj/x8HA+zcxMPru6Oj+fnh4/paSkPvHwcD6fnh4/j46OPu/u7j6lpKQ+j46OPuHg4D2KiQk/7+7uPuHg4D3h4OA9iokJP4qJCT+8uzs/zMtLP728PD/My0s/zMtLP+3sbD+enR0/vbw8P+3sbD/X1lY/pqUlP56dHT/X1lY/iokJP9PSUj+mpSU/iokJP+fm5j65uDg/09JSP+fm5j6UkxM/q6qqPrm4OD+UkxM/n54eP+no6D2rqqo+n54eP5STEz+RkJA96ejoPZSTEz+Miws/sbAwPpGLine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4096
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 256,
"image_pitch": 4096,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "f409b83161097b2fce88593d4e2f93e646f261614d168936d8c80b6dbedbdd32"
}
}
},
{
"name": "y/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "y/output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "y/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "y/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "y/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/bgrg422/gathers/y",
"observed": {
"value": {
"bytes": "gYCAPf/+/j7x8HA/wcBAPP/+/j6gnx8/n56ePvHwcD+gnx8/3dzcPouKCj+fnp4+3dzcPpGQkD3BwEA9i4oKP5GQkD2opyc/kZCQPcHAQD2opyc/8fBwPbe2Nj+RkJA98fBwPZ6dHT/l5GQ/t7Y2P56dHT+opyc/wcDAPuXkZD+opyc/sbCwPYmICD7BwMA+sbCwPdnYWD/5+Hg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7h4GA/tbQ0P728vD7j4uI+tbQ0P8XExD6WlRU/vby8PsXExD6bmpo+0tFRP5aVFT+bmpo+kZCQPZ2cnD7S0VE/kZCQPcrJST+VlJQ+nZycPsrJST+ZmJg9p6YmP5WUlD6ZmJg9s7IyP9HQ0D6npiY/s7IyP6moKD7e3V0/0dDQPqmoKD6trCw/+fh4P97dXT+trCw/np0dP6inJz/5+Hg/np0dP9va2j7BwEA9qKcnP9va2j6pqKg+395eP8HAQD2pqKg+hIMDP8PCQj/f3l4/hIMDP+3sbD/BwEA9w8JCP+3sbD/t7Gw/wcBAPcHAQD3V1NQ+//7+PuHgYD/V1FQ+//7+PomICD+1tDQ/4eBgP4mICD/g318/xcTEPrW0ND/g318/19bWPpuamj7FxMQ+19bWPuXkZD+RkJA9m5qaPuXkZD+dnBw+yslJP5GQkD2dnBw+19bWPpmYmD3KyUk/19bWPvn4+D6zsjI/mZiYPfn4+D6UkxM/qagoPrOLine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4096
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 256,
"image_pitch": 4096,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "e41ba95149730a32a1dfdba6e7ed1b8e46bb5923b57634d10b5e2d45a93c7b3c"
}
}
},
{
"name": "z/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "z/output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "z/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "z/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "z/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/bgrg422/gathers/z",
"observed": {
"value": {
"bytes": "pqUlP4mICD/p6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rqio/vr09P8XERD+JiAg/mJcXP8XERD+rqio/+/r6PomICD+rqio/gYAAP7u6uj77+vo+gYAAP4uKij6ZmBg+u7q6PouKij65uLg+nZwcPpmYGD65uLg+xsVFP7++vj6dnBw+xsVFP9XUVD+VlBQ/v76+PtXUVD+KiQk/xsVFP5WUFD+KiQk/x8bGPt/eXj/GxUU/x8bGPsfGxj7f3l4/395eP93cXD6DgoI+0M9PP+fmZj+DgoI+raysPqGgID/Qz08/raysPtXU1D6HhgY/oaAgP9XU1D77+vo+hIMDP4eGBj/7+vo+19bWPpaVFT+EgwM/19bWPtHQUD6+vT0/lpUVP9HQUD6RkBA+xcREP769PT+RkBA+9fR0PquqKj/FxEQ/9fR0PoOCgj6BgAA/q6oqP4OCgj7BwEA+i4qKPoGAAD/BwEA+l5aWPrm4uD6Lioo+l5aWPpOSEj/GxUU/ubi4PpOSEj+Pjg4/1dRUP8bFRT+Pjg4/g4KCPoqJCT/V1FQ/g4KCPtHQ0D3HxsY+iokJP9HQ0D3R0NA9x8bGPsfGxj6hoCA+5eRkPoOCgj7d3Fw+5eRkPrW0tD6trKw+g4KCPrW0tD6EgwM/1dTUPq2srD6EgwM/trU1P/v6+j7V1NQ+trU1P6inJz/X1tY++/r6PqinJz+1tLQ+0dBQPtfW1j61tLQ+i4qKPpGQED7R0FA+i4qKPtHQ0D719HQ+kZAQPtHQ0D75+Pg+g4KCPvXLine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4096
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 256,
"image_pitch": 4096,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "ca65053fde743aa72334c80638b1308061912e47c4c81ac8be2a49559ff574b9"
}
}
},
{
"name": "w/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "w/output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "w/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "w/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "w/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/bgrg422/gathers/w",
"observed": {
"value": {
"bytes": "AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/A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A/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwALine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4096
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 256,
"image_pitch": 4096,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "e9bac255f4adc7cb4ada9298e193a5ff66b434d15afabd458505325f29c398c7"
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 4.11",
"instrument": 400,
"times": {
"case": "chroma-pair-texel-gathers-bgrg422",
"calls": 24,
"in_calls": 32775419,
"on_cpu": 1615544,
"blocked": 31193794,
"elsewhere": 3438167,
"spend": 36183586,
"spend_least": 34915125,
"spend_most": 37207584,
"per_call": [
{
"call": "buffer",
"least_calls": 5,
"most_calls": 5,
"wall": 14584,
"on_cpu": 14791,
"blocked": 0,
"wall_least": 12792,
"wall_most": 16042,
"wall_total": 71541,
"on_cpu_total": 72542,
"blocked_total": 0
},
{
"call": "compute_pipeline",
"least_calls": 4,
"most_calls": 4,
"wall": 59417,
"on_cpu": 59667,
"blocked": 0,
"wall_least": 55125,
"wall_most": 63500,
"wall_total": 319541,
"on_cpu_total": 320834,
"blocked_total": 0
},
{
"call": "dispatch_threads",
"least_calls": 4,
"most_calls": 4,
"wall": 36916,
"on_cpu": 37041,
"blocked": 0,
"wall_least": 36250,
"wall_most": 39042,
"wall_total": 286832,
"on_cpu_total": 287543,
"blocked_total": 0
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 26701250,
"on_cpu": 737041,
"blocked": 25917584,
"wall_least": 26187791,
"wall_most": 27419875,
"wall_total": 26701250,
"on_cpu_total": 737041,
"blocked_total": 25917584
},
{
"call": "read_buffer",
"least_calls": 4,
"most_calls": 4,
"wall": 4417,
"on_cpu": 4667,
"blocked": 0,
"wall_least": 3625,
"wall_most": 4958,
"wall_total": 19876,
"on_cpu_total": 20708,
"blocked_total": 0
},
{
"call": "sampler",
"least_calls": 1,
"most_calls": 1,
"wall": 41250,
"on_cpu": 41375,
"blocked": 0,
"wall_least": 40875,
"wall_most": 43583,
"wall_total": 41250,
"on_cpu_total": 41375,
"blocked_total": 0
},
{
"call": "texture_2d_in_role",
"least_calls": 1,
"most_calls": 1,
"wall": 68542,
"on_cpu": 68958,
"blocked": 0,
"wall_least": 64000,
"wall_most": 80334,
"wall_total": 68542,
"on_cpu_total": 68958,
"blocked_total": 0
},
{
"call": "wait",
"least_calls": 4,
"most_calls": 4,
"wall": 480250,
"on_cpu": 10583,
"blocked": 470125,
"wall_least": 149333,
"wall_most": 510917,
"wall_total": 5264168,
"on_cpu_total": 51917,
"blocked_total": 5213251
}
]
}
}
]
}
@@ -1,699 +0,0 @@
{
"format": 1,
"case": "chroma-pair-texel-gathers-gbgr422",
"suite_version": 1,
"shaders": [
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_gather_x",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_gather_x",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
},
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_gather_y",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_gather_y",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
},
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_gather_z",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_gather_z",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
},
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_gather_w",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_gather_w",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
}
}
},
{
"name": "entry",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "ec15cf47f4671624c66cfd2215ddd6b49f606a9836b21bf5d6efe51120a17250"
}
}
},
{
"name": "format",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "e6bfd42cb3ef4c11ccd2eb76227f9fa93916250b47c03f644c3171b9be8d9c02"
}
}
},
{
"name": "texture:bytes",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "97d94990adf22069b968c7e737659f3deec9487277219fd99998f04df0bbcce5"
}
}
},
{
"name": "positions",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1bdb601fe30639f55df17904745a273ecbdd7cfaaf2375fdc7c7168ef085b46b"
}
}
},
{
"name": "buffer:blank",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "087d80f7f182dd44f184aa86ca34488853ebcc04f0c60d5294919a466b463831"
}
}
},
{
"name": "sampler",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "640e494dd31edb66b0748239aa90547d77e8ab37843b5bc8352a5f39e5296f06"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "positions",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "sampler",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "x/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/gbgr422/gathers/x",
"observed": {
"value": {
"bytes": "//7+Pvf29j7Y11c/8fBwP/f29j7l5OQ+paQkP9jXVz/l5OQ++fj4PtnY2D6lpCQ/+fj4PpqZGT/BwEA+2djYPpqZGT+mpSU/j46OPsHAQD6mpSU/oaAgP7GwMD+Pjo4+oaAgP/f29j61tDQ/sbAwP/f29j7h4GA+p6amPrW0ND/h4GA+xcREPvX0dD6npqY+xcREPtHQ0D7p6Og+9fR0PtHQ0D79/Pw+4+LiPuno6D79/Pw+5+bmPtHQUD7j4uI+5+bmPv38/D7JyEg+0dBQPv38/D6hoCA/19bWPsnISD6hoCA/srExP4iHBz/X1tY+srExP7KxMT+Ihwc/iIcHP4WEBD/Z2Ng+9/b2Pv/+/j7Z2Ng+8fBwPuXk5D739vY+8fBwPqmoqD75+Pg+5eTkPqmoqD61tDQ/mpkZP/n4+D61tDQ/6ulpP6alJT+amRk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tTU/jIsLP83MzD7R0FA/trU1P83MzD719PQ+q6oqP9HQUD/19PQ+x8ZGP4OCgj6rqio/x8ZGP+3sbD/BwEA9g4KCPu3sbD/t7Gw/wcBAPcHAQD3//v4+mJcXP8LBQT/h4GA/mJcXP8jHRz+DggI/wsFBP8jHRz/h4GA/nZycPoOCAj/h4GA/5ONjP5mYGD6dnJw+5ONjP8fGRj+RkJA9mZgYPsfGRj+KiQk/mZiYPZGQkD2KiQk/6+rqPsnIyD2ZmJg96+rqPoqJCT+RkBA+ycjIPYqJCT/v7u4+j46OPpGLine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4096
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 256,
"image_pitch": 4096,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "e38f51f518a826e01bfa96e8e428b5dc11cf794a972af12b34a763f1728a8068"
}
}
},
{
"name": "y/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "y/output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "y/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "y/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "y/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/gbgr422/gathers/y",
"observed": {
"value": {
"bytes": "pqUlP4GAADyWlRU/5ONjP4GAADzBwEA+9/Z2P5aVFT/BwEA+8O9vP9vaWj/39nY/8O9vP8XERD+UkxM/29paP8XERD+3tjY/tbQ0P5STEz+3tjY/tbQ0Prm4OD61tDQ/tbQ0Ps/Ozj6Lioo+ubg4Ps/Ozj6BgIA97u1tP4uKij6BgIA99fR0PvHw8D7u7W0/9fR0Prm4uD2lpKQ+8fDwPr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My0s/hYQEPufmZj/My0s/wcDAPomICD+FhAQ+wcDAPo+ODj+enR0/iYgIP4+ODj+HhgY/goEBP56dHT+HhgY/6ulpP/HwcD6CgQE/6ulpP8HAwD3S0VE/8fBwPsHAwD2NjAw+lZQUP9LRUT+NjAw+k5KSPp6dHT+VlBQ/k5KSPsHAQD2rqio/np0dP8HAQD2hoCA+nZwcPquqKj+hoCA+jo0NP7m4OD6dnBw+jo0NP7a1NT/6+Xk/ubg4Pra1NT/KyUk/gYCAPvr5eT/KyUk/0dDQPcfGxj6BgIA+0dDQPeHg4D2KiQk/x8bGPuHg4D3h4OA9iokJP4qJCT+hoCA+vLs7P8zLSz/d3Fw+vLs7P9XU1D7BwMA+zMtLP9XU1D79/Hw/j44OP8HAwD79/Hw/z85OP4eGBj+Pjg4/z85OP8fGxj7q6Wk/h4YGP8fGxj7NzEw+wcDAPerpaT/NzEw+pKMjP42MDD7BwMA9pKMjP/Py8j6TkpI+jYwMPvPy8j6OjQ0/wcBAPZOLine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4096
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 256,
"image_pitch": 4096,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "c5f059013ef60218f92719bac0505648ed32530e4ed8be7a29b75d2b14f62156"
}
}
},
{
"name": "z/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "z/output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "z/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "z/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "z/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/gbgr422/gathers/z",
"observed": {
"value":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u7q6PrW0ND+wry8/3dxcP7GwMD+wry8/2djYPuHgYD/d3Fw/2djYPqWkpD7GxUU/4eBgP6WkpD7DwsI+i4oKP8bFRT/DwsI+jYwMP7GwsD6Ligo/jYwMP9XUVD+9vDw+sbCwPtXUVD++vT0/ubi4Pb28PD6+vT0/j46OPoGAgD25uLg9j46OPunoaD6pqCg+gYCAPenoaD6WlRU/zczMPqmoKD6WlRU/w8JCP4WEBD/NzMw+w8JCP8PCQj+FhAQ/hYQEP9XUVD6rqqo+2dhYPqGgID6rqqo+lZQUP6Oioj7Z2Fg+lZQUP5uaGj/39vY+o6KiPpuaGj/Pzs4+tbQ0P/f29j7Pzs4+2djYPrCvLz+1tDQ/2djYPquqKj/Z2Ng+sK8vP6uqKj/Ew0M/paSkPtnY2D7Ew0M/ubg4P8PCwj6lpKQ+ubg4P7KxMT+NjAw/w8LCPrKxMT+vri4/1dRUP42MDD+vri4/nZwcP769PT/V1FQ/nZwcP/v6+j6Pjo4+vr09P/v6+j7n5uY+6ehoPo+Ojj7n5uY+/fz8PpaVFT/p6Gg+/fz8PoSDAz/DwkI/lpUVP4SDAz+EgwM/w8JCP8PCQj/V1NQ+5eTkPquqqj7V1FQ+5eTkPoKBAT+VlBQ/q6qqPoKBAT+CgQE/m5oaP5WUFD+CgQE/5eTkPs/Ozj6bmho/5eTkPrW0tD7Z2Ng+z87OPrW0tD7h4GA+q6oqP9nY2D7h4GA+8fBwPsTDQz+rqio/8fBwPs/Ozj65uDg/xMNDP8/Ozj7Lyso+srExP7mLine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4096
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 256,
"image_pitch": 4096,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "e98b5be8828fc9b9f92bcddf6f95ed602aea42dc46490caa10eb4f281c46249b"
}
}
},
{
"name": "w/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "w/output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "w/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "w/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "w/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/gbgr422/gathers/w",
"observed": {
"value": {
"bytes": "AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwA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PwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwALine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4096
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 256,
"image_pitch": 4096,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "e9bac255f4adc7cb4ada9298e193a5ff66b434d15afabd458505325f29c398c7"
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 4.11",
"instrument": 400,
"times": {
"case": "chroma-pair-texel-gathers-gbgr422",
"calls": 24,
"in_calls": 31868417,
"on_cpu": 1588208,
"blocked": 30291457,
"elsewhere": 3411542,
"spend": 35234375,
"spend_least": 34697376,
"spend_most": 351309000,
"per_call": [
{
"call": "buffer",
"least_calls": 5,
"most_calls": 5,
"wall": 13834,
"on_cpu": 14000,
"blocked": 0,
"wall_least": 13208,
"wall_most": 24791,
"wall_total": 75418,
"on_cpu_total": 76292,
"blocked_total": 0
},
{
"call": "compute_pipeline",
"least_calls": 4,
"most_calls": 4,
"wall": 60209,
"on_cpu": 59292,
"blocked": 0,
"wall_least": 36125,
"wall_most": 186500,
"wall_total": 292209,
"on_cpu_total": 293126,
"blocked_total": 0
},
{
"call": "dispatch_threads",
"least_calls": 4,
"most_calls": 4,
"wall": 35250,
"on_cpu": 35459,
"blocked": 0,
"wall_least": 31333,
"wall_most": 41875,
"wall_total": 287042,
"on_cpu_total": 287875,
"blocked_total": 0
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 26379584,
"on_cpu": 768042,
"blocked": 25611542,
"wall_least": 25852333,
"wall_most": 339770125,
"wall_total": 26379584,
"on_cpu_total": 768042,
"blocked_total": 25611542
},
{
"call": "read_buffer",
"least_calls": 4,
"most_calls": 4,
"wall": 3583,
"on_cpu": 3708,
"blocked": 0,
"wall_least": 3083,
"wall_most": 4500,
"wall_total": 18959,
"on_cpu_total": 19625,
"blocked_total": 0
},
{
"call": "sampler",
"least_calls": 1,
"most_calls": 1,
"wall": 41334,
"on_cpu": 41625,
"blocked": 0,
"wall_least": 40916,
"wall_most": 60958,
"wall_total": 41334,
"on_cpu_total": 41625,
"blocked_total": 0
},
{
"call": "texture_2d_in_role",
"least_calls": 1,
"most_calls": 1,
"wall": 69750,
"on_cpu": 70041,
"blocked": 0,
"wall_least": 58625,
"wall_most": 191125,
"wall_total": 69750,
"on_cpu_total": 70041,
"blocked_total": 0
},
{
"call": "wait",
"least_calls": 4,
"most_calls": 4,
"wall": 180792,
"on_cpu": 8459,
"blocked": 173292,
"wall_least": 147667,
"wall_most": 500417,
"wall_total": 4347667,
"on_cpu_total": 51750,
"blocked_total": 4299708
}
]
}
}
]
}
@@ -1,414 +0,0 @@
{
"format": 1,
"case": "chroma-pair-texel-linear-samples-bgrg422",
"suite_version": 1,
"shaders": [
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_sample",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_sample",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
}
}
},
{
"name": "entry",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "5fdee9d06c2b3202fa13b90735e2cc6d2c6add2fc764d1b8f257eca5025e3d26"
}
}
},
{
"name": "format",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "946e5fffd5aeab455618b623ec6cbc5ec6f26e67320db4f4ea7f2c62bef85bcc"
}
}
},
{
"name": "texture:bytes",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "97d94990adf22069b968c7e737659f3deec9487277219fd99998f04df0bbcce5"
}
}
},
{
"name": "positions",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "8a907c4a84a8e3b7e86797979bacc6573d250baee78fd718ed3975bd8d4ad1de"
}
}
},
{
"name": "buffer:blank",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "087d80f7f182dd44f184aa86ca34488853ebcc04f0c60d5294919a466b463831"
}
}
},
{
"name": "sampler",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "c7af40fff57e04ab850c5f1f77e7233bfc1d5038e05b4178c5c31ebe61f0000c"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "positions",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "sampler",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/bgrg422/linear-samples",
"observed": {
"value": {
"bytes": "2tkZP/r5eT4lJWU/AACAP29vLz+JiEg/KytrPwAAgD/My0s/PDy8Pu3sbD8AAIA/DQ1NP9bV1T6SkVE/AACAPzU1NT/Z2Fg9ICAgPwAAgD/Lygo/7exsPltb2z4AAIA/Ozu7PkJCQj8aGpo+AACAPzExsT7Ew0M/bGzsPgAAgD/o5+c+oqGhPgAAQD8AAIA/WFgYP7Cvrz5zczM/AACAP/TzMz+fnl4/397ePgAAgD+SkRE/EBAQPyEhoT4AAIA/LS2tPmVl5T4gIKA+AACAP2Fh4T6gnx8+MzOzPgAAgD///j4/0M/PPlFR0T4AAIA/4eBgP4iHBz/f3t4+AACAP4eGhj2wry8+Xl4ePwAAgD82NrY+iIcHP3Nz8z4AAIA/AABAP1NTEz+fnp4+AACAP5uaWj+vrq4+0M/PPgAAgD88PDw/3t1dPl9fHz8AAIA/2dgYP4KBAT/Myws/AACAP+jn5z7Lyko+EBCQPgAAgD8wMLA+ICAgP4qJCT4AAIA/h4aGPkNDAz+vrq49AACAP7++Pj6OjY0+l5aWPQAAgD+sqys+hINDP4+ODj4AAIA/Nja2PllZ2T5XV9c+AACAP+PiIj/m5WU+wcBAPwAAgD+trCw/+vn5PmRkJD8AAIA/DQ0NPy0tLT8CAoI+AACAP//+/j6ysTE/sbCwPQAAgD/k4+M+WlpaPxwcXD8AAIA/raysPoWEBD/m5SU/AACAP7u6Oj7Z2Ng+Pj6+PgAAgD/HxsY9w8JCPjU1tT4AAIA/n56ePfTz8z739vY+AACAP/f29j1WVlY/VVXVPgAAgD/u7W0+fn4+P+TjYz4AAIA/XFzcPuvqaj/n5uY9AACAP56dHT/R0BA/ubi4PQAAgD97e/s+5ONjPry7Oz4AAIA/3t1dPldXFz85Obk+AACAP4yLiz6VlBQ+REQEPwAAgD8LCws/WlraPqCfHz8AAIA/7OsrP//+/j7c2xs/AACAP3Bw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dPiEhYT8AAIA/oqEhPvDvLz+ioWE/AACAP6alJT7t7Cw///4+PwAAgD8WFpY+JiamPublJT8AAIA/cXHxPvTzMz/U0xM/AACAP2Fh4T7i4WE+xsUFPwAAgD8NDY0+fHz8Puvq6j4AAIA/wsFBPk1NDT8fH58+AACAP8HAQD4PD48+mpkZPgAAgD8XF5c+394eP9XUVD4AAIA/aGjoPpWUlD1ZWdk+AACAP3V19T739nY+4eAgPwAAgD/U09M+w8ICPwwMTD8AAIA/xcTEPvv6+j7f3l4/AACAP6SjIz7q6Wk+ISFhPwAAgD+gn58+WVnZPgQERD8AAIA/QEAAP1hY2D4aGho/AACAP3Jy8j6lpCQ/xsUFPwAAgD+op6c+8fAwPwgICD8AAIA/u7q6Ppuamj6gnx8/AACAP4aFBT/DwsI+f38/PwAAgD9dXR0/FxcXPz4+Pj8AAIA/Hx8fP8bFBT8gICA/AACAP/j39z6lpGQ/Y2PjPgAAgD+OjY0+paRkPxYWlj4AAIA/1tVVPsHAAD9tbe0+AACAP4SDgz6CgYE+iolJPwAAgD83N7c+2NdXPwICQj8AAIA/+Pf3PhUVFT8AAAA/AACAP4qJCT/BwEA9x8bGPgAAgD8ICEg/QEDAPufmZj4AAIA/9fQ0P9bVVT8NDY0+AACAP6CfHz8gICA/t7a2PgAAgD/x8DA/Ojq6Pl5e3j4AAIA/TExMP/r5eT7y8fE+AACAP+DfHz8AAIA+Ozu7PgAAgD+Pjo4+HBwcP8HAQD4AAIA/09LSPezraz6qqSk+AACAP8XExD2RkBA/+fh4PgALine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 8832
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 552,
"image_pitch": 8832,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "4344444504a5cb6d726c882f8c770907cd0bec0f4be52f9dbd8c526407226d38"
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 4.11",
"instrument": 400,
"times": {
"case": "chroma-pair-texel-linear-samples-bgrg422",
"calls": 9,
"in_calls": 30467583,
"on_cpu": 1146917,
"blocked": 29290749,
"elsewhere": 3237458,
"spend": 33839041,
"spend_least": 32921541,
"spend_most": 35884499,
"per_call": [
{
"call": "buffer",
"least_calls": 2,
"most_calls": 2,
"wall": 7291,
"on_cpu": 7458,
"blocked": 0,
"wall_least": 7125,
"wall_most": 10875,
"wall_total": 20792,
"on_cpu_total": 21792,
"blocked_total": 0
},
{
"call": "compute_pipeline",
"least_calls": 1,
"most_calls": 1,
"wall": 108292,
"on_cpu": 108667,
"blocked": 0,
"wall_least": 103000,
"wall_most": 136458,
"wall_total": 108292,
"on_cpu_total": 108667,
"blocked_total": 0
},
{
"call": "dispatch_threads",
"least_calls": 1,
"most_calls": 1,
"wall": 160833,
"on_cpu": 161042,
"blocked": 0,
"wall_least": 154667,
"wall_most": 187667,
"wall_total": 160833,
"on_cpu_total": 161042,
"blocked_total": 0
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 26181292,
"on_cpu": 737334,
"blocked": 25432292,
"wall_least": 25689541,
"wall_most": 28161792,
"wall_total": 26181292,
"on_cpu_total": 737334,
"blocked_total": 25432292
},
{
"call": "read_buffer",
"least_calls": 1,
"most_calls": 1,
"wall": 6666,
"on_cpu": 6916,
"blocked": 0,
"wall_least": 6167,
"wall_most": 7916,
"wall_total": 6666,
"on_cpu_total": 6916,
"blocked_total": 0
},
{
"call": "sampler",
"least_calls": 1,
"most_calls": 1,
"wall": 40667,
"on_cpu": 40791,
"blocked": 0,
"wall_least": 39084,
"wall_most": 47084,
"wall_total": 40667,
"on_cpu_total": 40791,
"blocked_total": 0
},
{
"call": "texture_2d_in_role",
"least_calls": 1,
"most_calls": 1,
"wall": 58166,
"on_cpu": 58417,
"blocked": 0,
"wall_least": 56792,
"wall_most": 69708,
"wall_total": 58166,
"on_cpu_total": 58417,
"blocked_total": 0
},
{
"call": "wait",
"least_calls": 1,
"most_calls": 1,
"wall": 3752500,
"on_cpu": 17541,
"blocked": 3737083,
"wall_least": 3688667,
"wall_most": 3937458,
"wall_total": 3752500,
"on_cpu_total": 17541,
"blocked_total": 3737083
}
]
}
}
]
}
@@ -1,414 +0,0 @@
{
"format": 1,
"case": "chroma-pair-texel-linear-samples-gbgr422",
"suite_version": 1,
"shaders": [
{
"fixture": "fpv_swizzled_reads.ll",
"entry": "fpv_swz_sample",
"source_sha256": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
},
{
"fixture": "fpv_swizzled_reads.air.ll",
"entry": "fpv_swz_sample",
"source_sha256": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "b91fae6759b1cb6496c80a57c5628aef675497891efefe9f6cdd5a8a38a6703e"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "18992f6252c2fcdc827256266349a4efc8b5d5428dbb37a6f22218db7a9c8a54"
}
}
},
{
"name": "entry",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "5fdee9d06c2b3202fa13b90735e2cc6d2c6add2fc764d1b8f257eca5025e3d26"
}
}
},
{
"name": "format",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "e6bfd42cb3ef4c11ccd2eb76227f9fa93916250b47c03f644c3171b9be8d9c02"
}
}
},
{
"name": "texture:bytes",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "97d94990adf22069b968c7e737659f3deec9487277219fd99998f04df0bbcce5"
}
}
},
{
"name": "positions",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "8a907c4a84a8e3b7e86797979bacc6573d250baee78fd718ed3975bd8d4ad1de"
}
}
},
{
"name": "buffer:blank",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "087d80f7f182dd44f184aa86ca34488853ebcc04f0c60d5294919a466b463831"
}
}
},
{
"name": "sampler",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "c7af40fff57e04ab850c5f1f77e7233bfc1d5038e05b4178c5c31ebe61f0000c"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "positions",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "output",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "sampler",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels/gb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Ls7PwAAgD+TkhI+6+pqPt7dXT8AAIA/vbw8Pk9PDz8aGlo/AACAP7i3tz6OjQ0/9/Y2PwAAgD8bGxs/T0/PPvz7+z4AAIA/Pj4+P6uqKj4cHJw+AACAPwAAQD+RkJA9paQkPgAAgD9QUBA/8fBwPquqqj0AAIA/l5aWPn19/T61tLQ9AACAPw4Ojj4eHh4/5eRkPgAAgD/a2dk+wL8/P9zb2z4AAIA/+/r6PsXExD6FhAQ/AACAP2dn5z51dTU/r64uPgAAgD/+/f0+7OtrPvTzcz4AAIA/SkoKP87NDT+4t7c+AACAP3V19T6XlhY/yskJPwAAgD/DwsI+YGDgPnNzMz8AAIA/397ePkNDwz7f3h4/AACAP5qZGT+DgkI/zMvLPgAAgD97ezs/19YWPywsrD4AAIA/EBBQP+HgID9YWNg+AACAPwoKSj/KyQk/n54ePwAAgD+2tTU/pKMjPg8PTz8AAIA/fHw8P0JCwj4gICA/AACAP0dHRz+Mi0s/CAiIPgAAgD9QUBA/EhKSPiIioj4AAIA/0M9PPtrZ2T7h4CA/AACAP8HAQD2KiQk/w8JCPwAAgD8ZGVk/ubi4PvX0dD4AAIA/8vExP/HwMD9KSso+AACAP+vq6j7Y19c+FhYWPwAAgD+JiIg+jYwMP87NDT8AAIA/hYQEPl9fHz9RUdE+AACAP5OSkj11dTU/+Pf3PgAAgD+lpKQ919bWPfHwMD8AAIA/397ePbOyMj4BAUE/AACAP7SzMz7o52c+9/Y2PwALine truncated
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 8832
}
},
"element": "f32",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 16,
"rows": 552,
"image_pitch": 8832,
"images": 1,
"gaps": "ignored"
}
},
"digest": {
"kind": "sha256",
"hex": "40f4e78dff7b2fdfe314c960cf7522a1d057d224d2dcd8fe492bb6ed18d1a7d9"
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 4.11",
"instrument": 400,
"times": {
"case": "chroma-pair-texel-linear-samples-gbgr422",
"calls": 9,
"in_calls": 30671833,
"on_cpu": 1152417,
"blocked": 29475791,
"elsewhere": 3257666,
"spend": 33955499,
"spend_least": 33421792,
"spend_most": 36077874,
"per_call": [
{
"call": "buffer",
"least_calls": 2,
"most_calls": 2,
"wall": 7208,
"on_cpu": 7375,
"blocked": 0,
"wall_least": 6959,
"wall_most": 8834,
"wall_total": 21792,
"on_cpu_total": 22124,
"blocked_total": 0
},
{
"call": "compute_pipeline",
"least_calls": 1,
"most_calls": 1,
"wall": 110250,
"on_cpu": 110542,
"blocked": 0,
"wall_least": 102166,
"wall_most": 123542,
"wall_total": 110250,
"on_cpu_total": 110542,
"blocked_total": 0
},
{
"call": "dispatch_threads",
"least_calls": 1,
"most_calls": 1,
"wall": 164250,
"on_cpu": 164500,
"blocked": 0,
"wall_least": 151708,
"wall_most": 178709,
"wall_total": 164250,
"on_cpu_total": 164500,
"blocked_total": 0
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 26405875,
"on_cpu": 724833,
"blocked": 25675625,
"wall_least": 25938125,
"wall_most": 28792750,
"wall_total": 26405875,
"on_cpu_total": 724833,
"blocked_total": 25675625
},
{
"call": "read_buffer",
"least_calls": 1,
"most_calls": 1,
"wall": 6542,
"on_cpu": 7042,
"blocked": 0,
"wall_least": 6125,
"wall_most": 9750,
"wall_total": 6542,
"on_cpu_total": 7042,
"blocked_total": 0
},
{
"call": "sampler",
"least_calls": 1,
"most_calls": 1,
"wall": 40625,
"on_cpu": 40833,
"blocked": 0,
"wall_least": 40542,
"wall_most": 45000,
"wall_total": 40625,
"on_cpu_total": 40833,
"blocked_total": 0
},
{
"call": "texture_2d_in_role",
"least_calls": 1,
"most_calls": 1,
"wall": 62041,
"on_cpu": 62334,
"blocked": 0,
"wall_least": 60084,
"wall_most": 70750,
"wall_total": 62041,
"on_cpu_total": 62334,
"blocked_total": 0
},
{
"call": "wait",
"least_calls": 1,
"most_calls": 1,
"wall": 3800083,
"on_cpu": 20375,
"blocked": 3781666,
"wall_least": 3704833,
"wall_most": 3913958,
"wall_total": 3800083,
"on_cpu_total": 20375,
"blocked_total": 3781666
}
]
}
}
]
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,351 +0,0 @@
{
"format": 1,
"case": "sparse-read-through",
"suite_version": 1,
"shaders": [
{
"fixture": "a2_sparse_read_through.ll",
"entry": "a2_sparse_read_through",
"source_sha256": "503a066d24018e70b436c4d4cfb8ba2c838fed21a8a76cb9ff5a735d3d248e76"
},
{
"fixture": "a2_sparse_read_through.air.ll",
"entry": "a2_sparse_read_through",
"source_sha256": "bacef4a468f9e6b728aaddce7dec795e5f0c56144fb20f9e4c3b73a3640e3fcd"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "503a066d24018e70b436c4d4cfb8ba2c838fed21a8a76cb9ff5a735d3d248e76"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "bacef4a468f9e6b728aaddce7dec795e5f0c56144fb20f9e4c3b73a3640e3fcd"
}
}
},
{
"name": "texture",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "d32fb7e3ab4f2c02a7b991d65c1ec4b2139495f2e2641fd16c04160d1a55845f"
}
}
},
{
"name": "positions",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "29b926e7376d8f1a4480c442cd37e9d4eddd80ce96d95df2dc41f536d59c8592"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer/positions",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer/out",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "stored",
"observed": {
"value": {
"bytes": "AACgPwAAIEAAABA/AACAPwAAoD8AACBAAAAQPwAAgD8AAKA/AAAgQAAAED8AAIA/AACgPwAAIEAAABA/AACAPwEAAAABAAAAAQAAAAEAAAAAAFBAAABgQAAAcD8AAIA/AABQQAAAYEAAAHA/AACAPwAAUEAAAGBAAABwPwAAgD8AAFBAAABgQAAAcD8AAIA/AQAAAAEAAAABAAAAAQAAAAAAUEAAAMA/AADgPgAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAgD8AAIA/AACAPwAAUEAAAMA/AADgPgAAgD8BAAAAAQAAAAEAAAABAAAAAACAPgAAIEAAAAA/AACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AACAPwAAgD8AAIA/AACAPgAAIEAAAAA/AACAPwEAAAABAAAAAQAAAAEAAAAAABBAAAAAPwAAAD4AAIA/AAAAAAAAAAAAAAAAAAAAAAAAgD8AAIA/AACAPwAAgD8AABBAAAAAPwAAAD4AAIA/AQAAAAEAAAABAAAAAQAAAAAAUEAAAGBAAABwPwAAgD8AAAAAAAAAAAAAAAAAAAAAAACAPwAAgD8AAIA/AACAPwAAUEAAAGBAAABwPwAAgD8BAAAAAQAAAAEAAAABAAAAAACAPgAAAD8AAAAAAACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AACAPwAAgD8AAIA/AACAPgAAAD8AAAAAAACAPwEAAAABAAAAAQAAAAEAAAAAAKA/AADAPwAAoD4AAIA/AACgPwAAwD8AAKA+AACAPwAAoD8AAMA/AACgPgAAgD8AAKA/AADAPwAAoD4AAIA/AQAAAAEAAAABAAAAAQAAAAAAUEAAAAA/AABAPgAAgD8AAFBAAAAAPwAAQD4AAIA/AABQQAAAAD8AAEA+AACAPwAAUEAAAAA/AABAPgAAgD8BAAAAAQAAAAEAAAABAAAAAABQQAAAYEAAAHA/AACAPwAAAAAAAAAAAAAAAAAAAAAAAIA/AACAPwAAgD8AAIA/AABQQAAAYEAAAHA/AACAPwEAAAABAAAAAQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAQAAAAEAAAABAAAA"
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 960
}
},
"element": "u32",
"row_offset": 0,
"row_elements": 20,
"row_pitch": 80,
"rows": 12,
"image_pitch": 960,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 12.22",
"instrument": 293,
"times": {
"case": "sparse-read-through",
"calls": 8,
"in_calls": 34154083,
"on_cpu": 1241126,
"blocked": 32942792,
"elsewhere": 4091834,
"spend": 38263001,
"spend_least": 35415335,
"spend_most": 44320168,
"per_call": [
{
"call": "buffer",
"least_calls": 2,
"most_calls": 2,
"wall": 6917,
"on_cpu": 7083,
"blocked": 0,
"wall_least": 6417,
"wall_most": 10875,
"wall_total": 21875,
"on_cpu_total": 22292,
"blocked_total": 0
},
{
"call": "compute_pipeline",
"least_calls": 1,
"most_calls": 1,
"wall": 133000,
"on_cpu": 133416,
"blocked": 0,
"wall_least": 126833,
"wall_most": 157375,
"wall_total": 133000,
"on_cpu_total": 133416,
"blocked_total": 0
},
{
"call": "dispatch_threads",
"least_calls": 1,
"most_calls": 1,
"wall": 172625,
"on_cpu": 172833,
"blocked": 0,
"wall_least": 168125,
"wall_most": 236042,
"wall_total": 172625,
"on_cpu_total": 172833,
"blocked_total": 0
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 29058875,
"on_cpu": 769375,
"blocked": 28289500,
"wall_least": 26297250,
"wall_most": 34836958,
"wall_total": 29058875,
"on_cpu_total": 769375,
"blocked_total": 28289500
},
{
"call": "read_buffer",
"least_calls": 1,
"most_calls": 1,
"wall": 9167,
"on_cpu": 9417,
"blocked": 0,
"wall_least": 7000,
"wall_most": 10125,
"wall_total": 9167,
"on_cpu_total": 9417,
"blocked_total": 0
},
{
"call": "texture",
"least_calls": 1,
"most_calls": 1,
"wall": 94334,
"on_cpu": 94667,
"blocked": 0,
"wall_least": 86917,
"wall_most": 103959,
"wall_total": 94334,
"on_cpu_total": 94667,
"blocked_total": 0
},
{
"call": "wait",
"least_calls": 1,
"most_calls": 1,
"wall": 4590125,
"on_cpu": 26417,
"blocked": 4569041,
"wall_least": 4537667,
"wall_most": 4738792,
"wall_total": 4590125,
"on_cpu_total": 26417,
"blocked_total": 4569041
}
]
}
}
]
}
@@ -132,7 +132,6 @@ pub mod mesh_pipeline_reflection;
pub mod nan_integer_conversions; pub mod nan_integer_conversions;
pub mod nearest_positions; pub mod nearest_positions;
pub mod norm_storage_writes; pub mod norm_storage_writes;
pub mod one_level_filters;
pub mod padded_blends; pub mod padded_blends;
pub mod padded_fetch; pub mod padded_fetch;
pub mod pass_attachment_pairs; pub mod pass_attachment_pairs;
@@ -187,7 +186,6 @@ pub mod simdgroup_lockstep;
pub mod snorm_tile_store; pub mod snorm_tile_store;
pub mod sparse_heaps; pub mod sparse_heaps;
pub mod sparse_mappings; pub mod sparse_mappings;
pub mod sparse_read_through;
pub mod sparse_status; pub mod sparse_status;
pub mod sparse_tiles; pub mod sparse_tiles;
pub mod srgb_fetch; pub mod srgb_fetch;
@@ -629,7 +627,6 @@ pub fn all() -> Vec<Box<dyn Case>> {
cases.push(Box::new(srgb_storage_writes::SrgbStorageWrites)); cases.push(Box::new(srgb_storage_writes::SrgbStorageWrites));
cases.push(Box::new(block_writes_only::BlockWritesOnlyWrites)); cases.push(Box::new(block_writes_only::BlockWritesOnlyWrites));
cases.push(Box::new(sparse_status::SparseStatusPlain)); cases.push(Box::new(sparse_status::SparseStatusPlain));
cases.push(Box::new(sparse_read_through::SparseReadThrough));
cases.push(Box::new( cases.push(Box::new(
srgb_storage_fragment_writes::SrgbStorageFragmentWrites, srgb_storage_fragment_writes::SrgbStorageFragmentWrites,
)); ));
@@ -645,7 +642,6 @@ pub fn all() -> Vec<Box<dyn Case>> {
} }
cases.extend(sampler_bind_clamps::all()); cases.extend(sampler_bind_clamps::all());
cases.extend(sampler_crossings::boxed()); cases.extend(sampler_crossings::boxed());
cases.extend(one_level_filters::all());
cases.extend(render_chains::boxed()); cases.extend(render_chains::boxed());
cases.extend(compute_render_chains::boxed()); cases.extend(compute_render_chains::boxed());
cases.extend(draw_state_changes::boxed()); cases.extend(draw_state_changes::boxed());
@@ -1,5 +1,5 @@
//! Metal's 4:2:2 chroma-pair textures (`GBGR422`, `BGRG422`): what a copy moves, and what a //! Metal's 4:2:2 chroma-pair textures (`GBGR422`, `BGRG422`): what a copy moves, and what a
//! kernel's `read()`, nearest and linear sample and gather of one answer. //! kernel's `read()` and nearest sample of one answer.
//! //!
//! Both of these formats are **public** Metal pixel formats, and every call the cases make of them //! Both of these formats are **public** Metal pixel formats, and every call the cases make of them
//! — `newTextureWithDescriptor:`, `replaceRegion:`, `getBytes:`, the four blit copies and a //! — `newTextureWithDescriptor:`, `replaceRegion:`, `getBytes:`, the four blit copies and a
@@ -15,13 +15,9 @@
//! //!
//! That probe covered 64 texels and is not re-runnable. These cases take Metal's answer over 256 //! That probe covered 64 texels and is not re-runnable. These cases take Metal's answer over 256
//! texels of a fixed pattern and commit it, so a new macOS is one `conformance record` from saying //! texels of a fixed pattern and commit it, so a new macOS is one `conformance record` from saying
//! whether Apple changed it. A second probe (an Apple M3 Max under macOS 27.0.1) took the model's //! whether Apple changed it.
//! rule over 64 texels of hashed bytes: a texel's green is its own luma, and its red and blue are
//! `(3c + n + 2) >> 2` of its pair's chroma `c` and the chroma `n` of the pair on its side (left
//! for an even texel, right for an odd one, the pair itself at the texture's edges); a linear
//! sample filters those texels.
//! //!
//! # The families //! # The three families
//! //!
//! [`ChromaCopies`] is a copy sweep as one declarative program ([`crate::work`]): a whole blit //! [`ChromaCopies`] is a copy sweep as one declarative program ([`crate::work`]): a whole blit
//! in and out, the host's whole `replaceRegion:`/`getBytes:`, seven blits in of regions whose x //! in and out, the host's whole `replaceRegion:`/`getBytes:`, seven blits in of regions whose x
@@ -42,15 +38,6 @@
//! recording answers rather than assumes. Comparison is exact and each case's allowances are on the //! recording answers rather than assumes. Comparison is exact and each case's allowances are on the
//! notices site alone. Every texel compares bit for bit. //! notices site alone. Every texel compares bit for bit.
//! //!
//! [`ChromaTexels`] also takes two accesses over a texture of `hashed` bytes, whose neighbouring
//! pairs' chroma differ by amounts that are not multiples of 4, so a decode's rounding shows (the
//! pattern above steps every byte by 1, so `3c + n` is a multiple of 4 at every texel): `sample()`
//! through a linear clamp-to-edge sampler at `linear_positions` (a quarter of the way between
//! each texel and its right neighbour, the corner of each 2 by 2 footprint, the texel centres of
//! two rows, and the edges and past them), and `gather()` of each component through the nearest
//! sampler at the corner of each 2 by 2 footprint. Clamp to edge is the one address mode Metal's
//! header grants these formats ("When sampling, ClampToEdge is the only usable wrap mode").
//!
//! # Why nothing here can fault a GPU //! # Why nothing here can fault a GPU
//! //!
//! Every program is a handful of 16 x 16 textures, blits of regions inside them, and one compute //! Every program is a handful of 16 x 16 textures, blits of regions inside them, and one compute
@@ -60,12 +47,10 @@
//! process. So is a render target of these formats, whose pipeline Metal's validation aborts plain //! process. So is a render target of these formats, whose pipeline Metal's validation aborts plain
//! too. //! too.
use crate::allowance::Allowance;
use crate::case::{ use crate::case::{
made, Abort, Bindings, Case, Failure, Input, MetalSource, SamplerSpec, Side, TextureRole, made, Abort, Bindings, Case, Failure, Input, MetalSource, SamplerSpec, Side, TextureRole,
TextureSpec, TextureSpec,
}; };
use crate::degradation::Degradation;
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT}; use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef; use crate::recording::ShaderRef;
use crate::transcript::{ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites, Value}; use crate::transcript::{ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites, Value};
@@ -118,14 +103,6 @@ const FORMATS: [(PixelFormat, &str); 2] = [
/// The case names, written out so each is a `&'static str` the report and `conformance replay` /// The case names, written out so each is a `&'static str` the report and `conformance replay`
/// can name. /// can name.
const LINEAR_NAMES: [&str; 2] = [
"chroma-pair-texel-linear-samples-gbgr422",
"chroma-pair-texel-linear-samples-bgrg422",
];
const GATHER_NAMES: [&str; 2] = [
"chroma-pair-texel-gathers-gbgr422",
"chroma-pair-texel-gathers-bgrg422",
];
const COPY_NAMES: [&str; 2] = ["chroma-pair-copies-gbgr422", "chroma-pair-copies-bgrg422"]; const COPY_NAMES: [&str; 2] = ["chroma-pair-copies-gbgr422", "chroma-pair-copies-bgrg422"];
const READ_NAMES: [&str; 2] = [ const READ_NAMES: [&str; 2] = [
"chroma-pair-texel-reads-gbgr422", "chroma-pair-texel-reads-gbgr422",
@@ -136,8 +113,8 @@ const SAMPLE_NAMES: [&str; 2] = [
"chroma-pair-texel-samples-bgrg422", "chroma-pair-texel-samples-bgrg422",
]; ];
/// Every case of the family: the copy sweep, the texel reads, the nearest and linear texel /// Every case of the family: the copy sweep, the texel reads and the texel samples, of each
/// samples and the gathers, of each format. /// format.
pub fn all() -> Vec<Box<dyn Case>> { pub fn all() -> Vec<Box<dyn Case>> {
let mut cases: Vec<Box<dyn Case>> = Vec::new(); let mut cases: Vec<Box<dyn Case>> = Vec::new();
for (at, (format, word)) in FORMATS.into_iter().enumerate() { for (at, (format, word)) in FORMATS.into_iter().enumerate() {
@@ -151,8 +128,6 @@ pub fn all() -> Vec<Box<dyn Case>> {
for (name, access) in [ for (name, access) in [
(READ_NAMES[at], Access::Read), (READ_NAMES[at], Access::Read),
(SAMPLE_NAMES[at], Access::NearestSample), (SAMPLE_NAMES[at], Access::NearestSample),
(LINEAR_NAMES[at], Access::LinearSample),
(GATHER_NAMES[at], Access::Gather),
] { ] {
cases.push(Box::new(ChromaTexels { cases.push(Box::new(ChromaTexels {
name, name,
@@ -180,96 +155,14 @@ enum Access {
/// `t.sample(s, uv)` at every texel's centre, through a nearest clamp-to-edge sampler of /// `t.sample(s, uv)` at every texel's centre, through a nearest clamp-to-edge sampler of
/// normalized coordinates. /// normalized coordinates.
NearestSample, NearestSample,
/// `t.sample(s, uv)` at `linear_positions`, through a linear clamp-to-edge sampler of
/// normalized coordinates, over a texture of `hashed` bytes.
LinearSample,
/// `t.gather(s, uv, int2(0), c)` of each component `c` at `gather_positions`, through a
/// nearest clamp-to-edge sampler, over a texture of `hashed` bytes.
Gather,
}
/// The gather kernels, one a component, and the word each one's site carries.
const GATHER_ENTRIES: [(&str, &str); 4] = [
("fpv_swz_gather_x", "x"),
("fpv_swz_gather_y", "y"),
("fpv_swz_gather_z", "z"),
("fpv_swz_gather_w", "w"),
];
/// The 512 bytes a texture of the linear and gather accesses holds: byte `k` a hash of `k`, so
/// neighbouring pairs' chroma differ by amounts that are not all multiples of 4 and the decode's
/// rounding, `(3c + n + 2) >> 2`, shows.
fn hashed() -> Vec<u8> {
(0..WHOLE as u32)
.map(|k| {
let mut h = k.wrapping_mul(2_654_435_761).wrapping_add(0x9e37_79b9);
h ^= h >> 15;
h = h.wrapping_mul(0x85eb_ca6b);
h ^= h >> 13;
h as u8
})
.collect()
}
/// A normalized coordinate on one axis of a [`SIDE`]-wide texture, `at` texels in.
fn normalized(at: f32) -> f32 {
at / SIDE as f32
}
/// The linear sample's positions, rows outer: in every row's centre, a quarter of the way past
/// each texel's centre toward its right neighbour (the texel weighted 3 to 1); the corner of each
/// 2 by 2 footprint, where the four texels weigh alike; the centres of rows 0 and 7, where the
/// sample is the texel itself; and in rows 0 and 15, `u` at 0, at 1 and a quarter of the texture
/// past each edge, which clamp to the edge texels.
fn linear_positions() -> Vec<[f32; 2]> {
let mut points = Vec::new();
for y in 0..SIDE as u32 {
for x in 0..SIDE as u32 {
points.push([normalized(x as f32 + 0.75), normalized(y as f32 + 0.5)]);
}
}
for y in 0..SIDE as u32 {
for x in 0..SIDE as u32 {
points.push([normalized(x as f32 + 1.0), normalized(y as f32 + 1.0)]);
}
}
for y in [0u32, 7] {
for x in 0..SIDE as u32 {
points.push([normalized(x as f32 + 0.5), normalized(y as f32 + 0.5)]);
}
}
for y in [0u32, 15] {
for u in [0.0, 1.0, -0.25, 1.25] {
points.push([u, normalized(y as f32 + 0.5)]);
}
}
points
}
/// The gather's positions, rows outer: the corner of each 2 by 2 footprint, `(x + 1, y + 1)`
/// texels in, whose four texels are `(x, y)` to `(x + 1, y + 1)`, clamped to the edge in the last
/// row and column.
fn gather_positions() -> Vec<[f32; 2]> {
let mut points = Vec::new();
for y in 0..SIDE as u32 {
for x in 0..SIDE as u32 {
points.push([normalized(x as f32 + 1.0), normalized(y as f32 + 1.0)]);
}
}
points
} }
impl Access { impl Access {
/// The fixture's entry points this access runs, each with the word its site carries after /// The fixture's entry point this access runs.
/// the access's own (none where the access runs one). fn entry(self) -> &'static str {
fn entries(self) -> Vec<(&'static str, Option<&'static str>)> {
match self { match self {
Access::Read => vec![(READ_ENTRY, None)], Access::Read => READ_ENTRY,
Access::NearestSample | Access::LinearSample => vec![(SAMPLE_ENTRY, None)], Access::NearestSample => SAMPLE_ENTRY,
Access::Gather => GATHER_ENTRIES
.iter()
.map(|&(entry, word)| (entry, Some(word)))
.collect(),
} }
} }
@@ -278,44 +171,12 @@ impl Access {
match self { match self {
Access::Read => "reads", Access::Read => "reads",
Access::NearestSample => "samples", Access::NearestSample => "samples",
Access::LinearSample => "linear-samples",
Access::Gather => "gathers",
} }
} }
/// The bytes the texture holds: the step pattern for the read and the nearest sample, whose /// The positions the kernel reads: integer texel positions, or the texel centres as
/// recordings were taken over it, the hashed bytes for the linear sample and the gather. /// normalized coordinates.
fn texture_bytes(self) -> Vec<u8> {
match self {
Access::Read | Access::NearestSample => pattern(),
Access::LinearSample | Access::Gather => hashed(),
}
}
/// The positions the access reads, one a lane.
fn lanes(self) -> usize {
match self {
Access::Read | Access::NearestSample => TEXELS,
Access::LinearSample => linear_positions().len(),
Access::Gather => gather_positions().len(),
}
}
/// The positions the kernel reads: integer texel positions, the texel centres as normalized
/// coordinates, or the linear sample's or the gather's normalized positions.
fn positions(self) -> Vec<u8> { fn positions(self) -> Vec<u8> {
let floats = |points: Vec<[f32; 2]>| {
points
.iter()
.flatten()
.flat_map(|axis| axis.to_le_bytes())
.collect()
};
match self {
Access::LinearSample => return floats(linear_positions()),
Access::Gather => return floats(gather_positions()),
Access::Read | Access::NearestSample => {}
}
let mut bytes = Vec::with_capacity(TEXELS * 8); let mut bytes = Vec::with_capacity(TEXELS * 8);
for y in 0..SIDE as u32 { for y in 0..SIDE as u32 {
for x in 0..SIDE as u32 { for x in 0..SIDE as u32 {
@@ -324,7 +185,7 @@ impl Access {
bytes.extend(x.to_le_bytes()); bytes.extend(x.to_le_bytes());
bytes.extend(y.to_le_bytes()); bytes.extend(y.to_le_bytes());
} }
_ => { Access::NearestSample => {
let centre = |index: u32| (index as f32 + 0.5) / SIDE as f32; let centre = |index: u32| (index as f32 + 0.5) / SIDE as f32;
bytes.extend(centre(x).to_le_bytes()); bytes.extend(centre(x).to_le_bytes());
bytes.extend(centre(y).to_le_bytes()); bytes.extend(centre(y).to_le_bytes());
@@ -337,12 +198,13 @@ impl Access {
/// The sampler state the access binds, where it binds one. /// The sampler state the access binds, where it binds one.
fn sampler(self) -> Option<SamplerSpec> { fn sampler(self) -> Option<SamplerSpec> {
let filter = match self { match self {
Access::Read => return None, Access::Read => None,
Access::NearestSample | Access::Gather => SamplerMinMagFilter::Nearest, Access::NearestSample => Some(
Access::LinearSample => SamplerMinMagFilter::Linear, SamplerSpec::filtered(SamplerMinMagFilter::Nearest)
}; .addressed(SamplerAddressMode::ClampToEdge),
Some(SamplerSpec::filtered(filter).addressed(SamplerAddressMode::ClampToEdge)) ),
}
} }
} }
@@ -700,16 +562,6 @@ impl Case for ChromaCopies {
MetalSource::Run MetalSource::Run
} }
fn allowances(&self) -> Vec<Allowance> {
// Metal announces nothing. The runtime's 4:2:2 texture states the static note of its
// linear and bicubic samples, `bicubic-filter-arithmetic` (`Texture::precision_note`),
// which the rt side announces for every texture it makes. A declaration at the notices
// site alone: every byte still compares exactly.
vec![crate::replay::notice_allowance(
Degradation::BicubicFilterArithmetic.code(),
)]
}
fn inputs(&self) -> Result<Vec<Input>, String> { fn inputs(&self) -> Result<Vec<Input>, String> {
// The tables and the bytes they move, named one by one, so a diff of a failed input // The tables and the bytes they move, named one by one, so a diff of a failed input
// fingerprint says which of them changed rather than "the program". // fingerprint says which of them changed rather than "the program".
@@ -795,43 +647,32 @@ pub struct ChromaTexels {
/// The texels a [`SIDE`]-square texture holds. /// The texels a [`SIDE`]-square texture holds.
const TEXELS: usize = (SIDE * SIDE) as usize; const TEXELS: usize = (SIDE * SIDE) as usize;
/// The layout `lanes` `float4`s are compared under: one row a lane of four channels, so a diff /// The layout a read's `float4`s are compared under: one row a texel of four lanes, so a diff
/// names the position and the channel. /// names the texel and the channel.
fn texel_layout(lanes: usize) -> ByteLayout { fn texel_layout() -> ByteLayout {
ByteLayout { ByteLayout {
region: Region::Buffer { region: Region::Buffer {
offset: 0, offset: 0,
length: (lanes * 16) as u64, length: (TEXELS * 16) as u64,
}, },
element: Element::F32, element: Element::F32,
row_offset: 0, row_offset: 0,
row_elements: 4, row_elements: 4,
row_pitch: 16, row_pitch: 16,
rows: lanes as u32, rows: TEXELS as u32,
image_pitch: (lanes * 16) as u32, image_pitch: (TEXELS * 16) as u32,
images: 1, images: 1,
// A texel's four lanes fill its row, so there is nothing between them. // A texel's four lanes fill its row, so there is nothing between them.
gaps: Gaps::Ignored, gaps: Gaps::Ignored,
} }
} }
/// The entries `access` runs, one a line, as the case's `entry` input: the read's and the nearest
/// sample's input keeps its one entry's name alone, as their recordings were taken under.
fn entry_names(access: Access) -> String {
access
.entries()
.iter()
.map(|&(entry, _)| entry)
.collect::<Vec<_>>()
.join("\n")
}
impl ChromaTexels { impl ChromaTexels {
/// The fixture this case runs, at its first entry: every entry lives in the one fixture. /// The fixture this case runs.
fn fixture(&self) -> Fixture { fn fixture(&self) -> Fixture {
Fixture { Fixture {
name: READ_FIXTURE, name: READ_FIXTURE,
entry: self.access.entries()[0].0, entry: self.access.entry(),
} }
} }
} }
@@ -845,34 +686,15 @@ impl Case for ChromaTexels {
MetalSource::Run MetalSource::Run
} }
fn allowances(&self) -> Vec<Allowance> {
// Metal announces nothing. The runtime's 4:2:2 texture states the static note of its
// linear and bicubic samples, `bicubic-filter-arithmetic` (`Texture::precision_note`),
// which the rt side announces for every texture it makes; and a sample or gather through
// the fixture's runtime sampler slot announces `pixel-sampler-scaling` whatever the
// filter (`crate::replay::pixel_sampler_scaling_notice` holds why), measured through the
// rt side on lavapipe (Mesa 26.2.4) for every sampling access. Each is a declaration at
// the notices site alone: every texel still compares bit for bit.
let mut allowances = vec![crate::replay::notice_allowance(
Degradation::BicubicFilterArithmetic.code(),
)];
if self.access.sampler().is_some() {
allowances.push(crate::replay::pixel_sampler_scaling_notice());
}
allowances
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> { fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let fixture = self.fixture(); let fixture = self.fixture();
let mut shaders = Vec::new(); let mut shaders = Vec::new();
for (entry, _) in self.access.entries() { for extension in [RUNTIME_TEXT, METAL_TEXT] {
for extension in [RUNTIME_TEXT, METAL_TEXT] { shaders.push(ShaderRef {
shaders.push(ShaderRef { fixture: format!("{READ_FIXTURE}{extension}"),
fixture: format!("{READ_FIXTURE}{extension}"), entry: self.access.entry().to_owned(),
entry: entry.to_owned(), source_sha256: crate::sha256_hex(fixture.text(extension)?.as_bytes()),
source_sha256: crate::sha256_hex(fixture.text(extension)?.as_bytes()), });
});
}
} }
Ok(shaders) Ok(shaders)
} }
@@ -888,9 +710,9 @@ impl Case for ChromaTexels {
name: "air-typed".to_owned(), name: "air-typed".to_owned(),
digest: Digest::sha256(fixture.text(METAL_TEXT)?.as_bytes()), digest: Digest::sha256(fixture.text(METAL_TEXT)?.as_bytes()),
}, },
Input::bytes("entry", entry_names(self.access).as_bytes()), Input::bytes("entry", fixture.entry.as_bytes()),
Input::bytes("format", &self.format.as_raw().to_le_bytes()), Input::bytes("format", &self.format.as_raw().to_le_bytes()),
Input::bytes("texture:bytes", &self.access.texture_bytes()), Input::bytes("texture:bytes", &pattern()),
Input::bytes("positions", &self.access.positions()), Input::bytes("positions", &self.access.positions()),
Input::bytes("buffer:blank", &[BLANK]), Input::bytes("buffer:blank", &[BLANK]),
]; ];
@@ -907,18 +729,11 @@ impl Case for ChromaTexels {
failure: Failure::named("FixtureNotRead", why), failure: Failure::named("FixtureNotRead", why),
})?; })?;
let library = made(sites, "library", side.library(&source.source()))?; let library = made(sites, "library", side.library(&source.source()))?;
let entries = self.access.entries(); let pipeline = made(
// An access of one entry makes its calls in the order its recording was taken in: the sites,
// pipeline before the texture, the output before the sampler. "pipeline",
let single = entries.len() == 1; side.compute_pipeline(library, self.access.entry()),
let first = match single { )?;
true => Some(made(
sites,
"pipeline",
side.compute_pipeline(library, entries[0].0),
)?),
false => None,
};
// The texture is made with its bytes, which is the whole of what the case feeds it: what // The texture is made with its bytes, which is the whole of what the case feeds it: what
// a fresh texture reads is a separate question from what Metal's decode does with known // a fresh texture reads is a separate question from what Metal's decode does with known
// codes, and this case asks the second. // codes, and this case asks the second.
@@ -935,85 +750,50 @@ impl Case for ChromaTexels {
// different question of Metal. // different question of Metal.
TextureRole::Read, TextureRole::Read,
), ),
&self.access.texture_bytes(), &pattern(),
), ),
)?; )?;
let positions = made(sites, "positions", side.buffer(&self.access.positions()))?; let positions = made(sites, "positions", side.buffer(&self.access.positions()))?;
let lanes = self.access.lanes(); let output = made(sites, "output", side.buffer(&vec![BLANK; TEXELS * 16]))?;
let first_output = match single {
true => Some(made(
sites,
"output",
side.buffer(&vec![BLANK; lanes * 16]),
)?),
false => None,
};
let mut samplers = Vec::new(); let mut samplers = Vec::new();
if let Some(spec) = self.access.sampler() { if let Some(spec) = self.access.sampler() {
samplers.push(made(sites, "sampler", side.sampler(&spec))?); samplers.push(made(sites, "sampler", side.sampler(&spec))?);
} }
for (entry, component) in entries { let textures = [texture];
// A site of its own for each entry's calls where the access runs several. let buffers = [output, positions];
let at = |name: &str| match component { let command_buffer = made(
Some(word) => format!("{word}/{name}"), sites,
None => name.to_owned(), "dispatch",
}; side.dispatch_threads(
let pipeline = match first { pipeline,
Some(pipeline) => pipeline, &Bindings::new(&textures, &buffers).sampled(&samplers),
None => made( &[],
sites, [TEXELS as u32, 1, 1],
&at("pipeline"), [GROUP, 1, 1],
side.compute_pipeline(library, entry), ),
)?, )?;
}; let status = made(sites, "status", side.wait(command_buffer))?;
let output = match first_output { if status != Value::unit_variant("Completed") {
Some(output) => output, return Err(Abort {
None => made(sites, &at("output"), side.buffer(&vec![BLANK; lanes * 16]))?, at: "status".to_owned(),
}; failure: Failure::named("CommandBufferStatus", crate::diff::print(&status)),
let textures = [texture]; });
let buffers = [output, positions];
let command_buffer = made(
sites,
&at("dispatch"),
side.dispatch_threads(
pipeline,
&Bindings::new(&textures, &buffers).sampled(&samplers),
&[],
[lanes as u32, 1, 1],
[GROUP, 1, 1],
),
)?;
let status = made(sites, &at("status"), side.wait(command_buffer))?;
if status != Value::unit_variant("Completed") {
return Err(Abort {
at: at("status"),
failure: Failure::named("CommandBufferStatus", crate::diff::print(&status)),
});
}
let bytes = made(
sites,
&at("read-back"),
side.read_buffer(output, 0, lanes * 16),
)?;
if bytes.len() != lanes * 16 {
return Err(Abort {
at: at("read-back"),
failure: Failure::named(
"ShortReadBack",
format!("{} bytes of {}", bytes.len(), lanes * 16),
),
});
}
let digest = Digest::sha256(&bytes);
let leaf = match component {
Some(word) => format!("texels/{}/{}/{word}", self.word, self.access.word()),
None => format!("texels/{}/{}", self.word, self.access.word()),
};
sites.push(Node::leaf(
leaf,
Observed::bytes(bytes, texel_layout(lanes)).digested(digest),
));
} }
let bytes = made(sites, "read-back", side.read_buffer(output, 0, TEXELS * 16))?;
if bytes.len() != TEXELS * 16 {
return Err(Abort {
at: "read-back".to_owned(),
failure: Failure::named(
"ShortReadBack",
format!("{} bytes of {}", bytes.len(), TEXELS * 16),
),
});
}
let digest = Digest::sha256(&bytes);
sites.push(Node::leaf(
format!("texels/{}/{}", self.word, self.access.word()),
Observed::bytes(bytes, texel_layout()).digested(digest),
));
Ok(()) Ok(())
} }
} }
@@ -1023,13 +803,13 @@ mod tests {
use super::*; use super::*;
use std::collections::BTreeSet; use std::collections::BTreeSet;
/// Ten cases, each of a different question, and each name says which format it is of. /// Six cases, each of a different question, and each name says which format it is of.
#[test] #[test]
fn the_cases_name_their_format() { fn the_cases_name_their_format() {
let cases = all(); let cases = all();
assert_eq!(cases.len(), 10); assert_eq!(cases.len(), 6);
let names: BTreeSet<&str> = cases.iter().map(|case| case.name()).collect(); let names: BTreeSet<&str> = cases.iter().map(|case| case.name()).collect();
assert_eq!(names.len(), 10); assert_eq!(names.len(), 6);
for name in names { for name in names {
assert!( assert!(
name.ends_with("gbgr422") || name.ends_with("bgrg422"), name.ends_with("gbgr422") || name.ends_with("bgrg422"),
@@ -1151,56 +931,11 @@ mod tests {
assert!(spec.normalized_coordinates); assert!(spec.normalized_coordinates);
} }
/// The hashed texture makes the decode's rounding show: at some texel, for each chroma byte
/// of both formats, its pair's chroma `c` and the chroma `n` of the pair on its side give a
/// `3c + n` that is not a multiple of 4. The step pattern of the read and the nearest sample
/// gives none.
#[test]
fn the_hashed_texture_shows_the_decode_rounding() {
let row = ROW as usize;
let pairs = SIDE as usize / 2;
let off_quarter = |bytes: &[u8], chroma: usize| {
(0..SIDE as usize).any(|y| {
(0..SIDE as usize).any(|x| {
let pair = x / 2;
let side = match x % 2 {
0 => pair.saturating_sub(1),
_ => (pair + 1).min(pairs - 1),
};
let c = u32::from(bytes[y * row + pair * 4 + chroma]);
let n = u32::from(bytes[y * row + side * 4 + chroma]);
(3 * c + n) % 4 != 0
})
})
};
for chroma in [0, 1, 2, 3] {
assert!(off_quarter(&hashed(), chroma), "byte {chroma} of a pair");
assert!(!off_quarter(&pattern(), chroma), "byte {chroma} of a pair");
}
}
/// The linear sample and the gather read inside the texture and past its edges, and each
/// position is a normalized coordinate of the texture.
#[test]
fn the_linear_and_gather_positions_are_the_texture_s() {
assert_eq!(linear_positions().len(), 2 * TEXELS + 2 * SIDE as usize + 8);
assert_eq!(gather_positions().len(), TEXELS);
for [u, v] in linear_positions().into_iter().chain(gather_positions()) {
assert!((-0.25..=1.25).contains(&u), "{u}");
assert!((0.0..=1.0).contains(&v), "{v}");
}
assert_eq!(Access::Gather.entries().len(), 4);
let spec = Access::LinearSample.sampler().expect("a sampler state");
assert_eq!(spec.min_filter, SamplerMinMagFilter::Linear);
assert_eq!(spec.mag_filter, SamplerMinMagFilter::Linear);
assert_eq!(spec.s_address_mode, SamplerAddressMode::ClampToEdge);
}
/// The layout covers every texel and names the texel as its row, so a diff over 256 texels /// The layout covers every texel and names the texel as its row, so a diff over 256 texels
/// says which one moved. /// says which one moved.
#[test] #[test]
fn the_texel_layout_names_the_texel() { fn the_texel_layout_names_the_texel() {
let layout = texel_layout(TEXELS); let layout = texel_layout();
assert_eq!(layout.extent(), TEXELS * 16); assert_eq!(layout.extent(), TEXELS * 16);
assert_eq!(layout.at(0, 255, 3), 255 * 16 + 12); assert_eq!(layout.at(0, 255, 3), 255 * 16 + 12);
} }
@@ -41,9 +41,8 @@ use crate::transcript::{Node, Observed, Sites, Value};
use metal2vulkan::metal::BlendFactor; use metal2vulkan::metal::BlendFactor;
use super::extended_range_targets::{ use super::extended_range_targets::{
blend_notices, fixture, fixture_inputs, half_bytes, not_read, program, read_layout, fixture, fixture_inputs, half_bytes, not_read, program, read_layout, shader_refs, shape,
shader_refs, shape, texel_layout, Format, FILLS, FILL_HALF, FORMATS, HEIGHT, PLANES, texel_layout, Format, FILLS, FILL_HALF, FORMATS, HEIGHT, PLANES, READ_FLOAT, VERTEX, WIDTH,
READ_FLOAT, VERTEX, WIDTH,
}; };
/// The kernel that writes a `float4` into a two-plane extended-range texture, which is how the /// The kernel that writes a `float4` into a two-plane extended-range texture, which is how the
@@ -241,12 +240,9 @@ impl Case for ExtendedRangeBlend {
// device that blends as Metal does shows as announced with nothing differing -- which is // device that blends as Metal does shows as announced with nothing differing -- which is
// what this M3 Max and lavapipe both show -- and one that does not shows the code. The // what this M3 Max and lavapipe both show -- and one that does not shows the code. The
// allowance fails the case if the notice stops firing, so it cannot outlive its reason. // allowance fails the case if the notice stops firing, so it cannot outlive its reason.
let mut allowances = vec![crate::replay::notice_allowance( vec![crate::replay::notice_allowance(
Degradation::HalfOutputFastMathBlend.code(), Degradation::HalfOutputFastMathBlend.code(),
)]; )]
// A `BGR10_XR` or `BGRA10_XR` target's blend of its codes (`blend_notices`).
allowances.extend(blend_notices(self.format.format, Some(&self.blend)));
allowances
} }
fn shaders(&self) -> Result<Vec<ShaderRef>, String> { fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
@@ -1,8 +1,8 @@
//! A wide-gamut client's render pipelines into `BGRA10_XR` and its `_sRGB` twin: what a draw //! A wide-gamut client's render pipelines into `BGRA10_XR` and its `_sRGB` twin: what a draw
//! stores, compared code for code. //! stores, compared code for code.
//! //!
//! A `CAMetalLayer` that asks for wide gamut hands its client `BGRA10_XR` drawables, and a 2D //! A `CAMetalLayer` that asks for wide gamut hands its client `BGRA10_XR` drawables, and a client
//! renderer then makes every pipeline over that format: four samples resolved into the //! such as Impeller then makes every pipeline over that format: four samples resolved into the
//! drawable, a stencil (or depth and stencil) attachment, and blending on by default. Three //! drawable, a stencil (or depth and stencil) attachment, and blending on by default. Three
//! families hold those shapes against Metal: //! families hold those shapes against Metal:
//! //!
@@ -50,8 +50,8 @@ use crate::values::StoreAction;
use metal2vulkan::metal::{BlendFactor as F, BlendOperation as O, ColorWriteMask, PixelFormat}; use metal2vulkan::metal::{BlendFactor as F, BlendOperation as O, ColorWriteMask, PixelFormat};
use super::extended_range_targets::{ use super::extended_range_targets::{
blend_notices, fixture, fixture_inputs, half_bits, not_read, program, shader_refs, shape, fixture, fixture_inputs, half_bits, not_read, program, shader_refs, shape, texel_layout,
texel_layout, Format, FILLS, FILL_FLOAT, FILL_HALF, FORMATS, VERTEX, Format, FILLS, FILL_FLOAT, FILL_HALF, FORMATS, VERTEX,
}; };
/// The fixture's fill that writes depth alone (`[[depth(any)]]`), reading a `float` a sample. /// The fixture's fill that writes depth alone (`[[depth(any)]]`), reading a `float` a sample.
@@ -312,12 +312,9 @@ impl Case for GamutDraw {
MetalSource::Run MetalSource::Run
} }
/// The family's notices, and a `BGRA10_XR` target's blend of its codes (`blend_notices`): /// The family's notices, and nothing else: every texel compares exactly.
/// every texel compares exactly.
fn allowances(&self) -> Vec<Allowance> { fn allowances(&self) -> Vec<Allowance> {
let mut allowances = notices(); notices()
allowances.extend(blend_notices(self.format.format, Some(&self.blend)));
allowances
} }
fn shaders(&self) -> Result<Vec<ShaderRef>, String> { fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
@@ -736,12 +733,9 @@ impl Case for MaskedDraw {
MetalSource::Run MetalSource::Run
} }
/// The family's notices, and the second draw's blend of a `BGR10_XR` or `BGRA10_XR` target's /// The family's notices, and nothing else: every texel compares exactly.
/// codes (`blend_notices`): every texel compares exactly.
fn allowances(&self) -> Vec<Allowance> { fn allowances(&self) -> Vec<Allowance> {
let mut allowances = notices(); notices()
allowances.extend(blend_notices(self.format.format, self.blend.as_ref()));
allowances
} }
fn shaders(&self) -> Result<Vec<ShaderRef>, String> { fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
@@ -2,7 +2,7 @@
//! its gradients into: what the pass stores, compared code for code. //! its gradients into: what the pass stores, compared code for code.
//! //!
//! A `CAMetalLayer` that asks for wide gamut hands its client `BGRA10_XR` drawables, and a 2D //! A `CAMetalLayer` that asks for wide gamut hands its client `BGRA10_XR` drawables, and a 2D
//! renderer fills its gradients there by draws that evaluate the gradient in the //! renderer such as Impeller fills its gradients there by draws that evaluate the gradient in the
//! fragment function from a buffer of color stops, often at four samples resolved into the //! fragment function from a buffer of color stops, often at four samples resolved into the
//! drawable. Each case here is one pass over a 32 x 32 target cleared to an opaque color, with two //! drawable. Each case here is one pass over a 32 x 32 target cleared to an opaque color, with two
//! draws of the owned fixture `xr_gradients`: //! draws of the owned fixture `xr_gradients`:
@@ -34,8 +34,7 @@ use crate::values::StoreAction;
use metal2vulkan::metal::BlendFactor as F; use metal2vulkan::metal::BlendFactor as F;
use super::extended_range_targets::{ use super::extended_range_targets::{
blend_notices, fixture, fixture_inputs, not_read, program, shader_refs, texel_layout, Format, fixture, fixture_inputs, not_read, program, shader_refs, texel_layout, Format, FORMATS,
FORMATS,
}; };
/// The fixture and its entry points. /// The fixture and its entry points.
@@ -246,13 +245,9 @@ impl Case for GradientDraw {
/// still compares exactly): `half-output-fast-math-blend` (the fixture is a fast-math module /// still compares exactly): `half-output-fast-math-blend` (the fixture is a fast-math module
/// whose `half4` gradient a pipeline blends). /// whose `half4` gradient a pipeline blends).
fn allowances(&self) -> Vec<Allowance> { fn allowances(&self) -> Vec<Allowance> {
let mut allowances = vec![crate::replay::notice_allowance( vec![crate::replay::notice_allowance(
Degradation::HalfOutputFastMathBlend.code(), Degradation::HalfOutputFastMathBlend.code(),
)]; )]
// A `BGRA10_XR` target's blend of its codes (`blend_notices`).
let blend = self.blended.then_some(&OVER);
allowances.extend(blend_notices(self.format.format, blend));
allowances
} }
fn shaders(&self) -> Result<Vec<ShaderRef>, String> { fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
@@ -39,8 +39,8 @@ use crate::degradation::Degradation;
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT}; use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef; use crate::recording::ShaderRef;
use crate::render::{ use crate::render::{
Blend, ColorState, Dispatch, PassColor, Plane, ReadAt, RenderPass, RenderPipelineSpec, ColorState, Dispatch, PassColor, Plane, ReadAt, RenderPass, RenderPipelineSpec, RenderStep,
RenderStep, RenderWork, TargetSpec, RenderWork, TargetSpec,
}; };
use crate::transcript::{ use crate::transcript::{
Aspect, ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites, Value, Aspect, ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites, Value,
@@ -269,37 +269,6 @@ pub(super) fn half_bytes() -> Vec<u8> {
.collect() .collect()
} }
/// The notices a pipeline announces that blends `blend` into an attachment of `format`, where the
/// attachment is `BGR10_XR` or `BGRA10_XR`, whose images blend their codes: `extended-range-blend`
/// where the blend stores more than its source as it is, and `extended-range-blend-window` beside
/// it where its corrected source term can leave the code range. This restates the translator's
/// classification from the blend's factors (`PrecisionNote::ExtendedRangeBlendWindow`) for the
/// blends this family draws: one and zero, added, stores its source; straight alpha-over holds the
/// window; an addition of one and one and premultiplied source-over do not. A blend the family does
/// not draw is a panic here, so a new one is classified before it is recorded. Every texel still
/// compares exactly: a difference is the gap the notes describe.
pub(super) fn blend_notices(format: PixelFormat, blend: Option<&Blend>) -> Vec<Allowance> {
use metal2vulkan::metal::BlendFactor as F;
let codes = matches!(format, PixelFormat::BGR10XR | PixelFormat::BGRA10XR);
let Some(blend) = blend.filter(|_| codes) else {
return Vec::new();
};
let window = match (blend.source_rgb, blend.destination_rgb) {
(F::One, F::Zero) => return Vec::new(),
(F::SourceAlpha, F::OneMinusSourceAlpha) => false,
(F::One, F::One) | (F::One, F::OneMinusSourceAlpha) => true,
other => panic!("a blend this family does not draw: {other:?}"),
};
let mut notes = vec![Degradation::ExtendedRangeBlend];
if window {
notes.push(Degradation::ExtendedRangeBlendWindow);
}
notes
.into_iter()
.map(|kind| crate::replay::notice_allowance(kind.code()))
.collect()
}
/// The buffer the fills read their extent from: the row's width and the samples of a pixel, as the /// The buffer the fills read their extent from: the row's width and the samples of a pixel, as the
/// fixture's `Rt6Shape`. /// fixture's `Rt6Shape`.
pub(super) fn shape(width: u32, samples: u32) -> Vec<u8> { pub(super) fn shape(width: u32, samples: u32) -> Vec<u8> {
@@ -1,455 +0,0 @@
//! Which of a sampler's two filters Metal applies to a texture of **one level**, at an explicit
//! level and at a kernel's bias.
//!
//! A sampler whose minifying and magnifying filters differ names its filter by the level: the
//! magnifying one at a level of 0 or below, the minifying one above it. On a texture of one level
//! the clamp into the texture's levels takes every level to 0, so whether Metal reads the level
//! before or after that clamp is the whole question: after it, every sample would magnify. A Metal
//! probe of a one-level `rgba8Unorm` texture through samplers without a mip filter (the Apple M3
//! Max on macOS 27.0.1) read the choice before the clamp, and `metal2vulkan`'s
//! `lower::sampler::level` states the rule so. This case puts the question to Metal under every mip
//! filter and through clamps that move the level across 0 from either side, and compares the
//! runtime's answer, the device's own sampler, with Metal's.
//!
//! **The texture** is 16 by 4 `R32Float` of one level, texel `(x, y)` holding `1 + x + 16 y`, so a
//! sample names the texel it read and how it read it. **The lanes** sample a quarter of a texel
//! past each texel's centre toward its right neighbour, in each row (60 positions, the probe's), at
//! each of the probe's nine levels: -2, -0.5, 0, 1/64, 1/4, 1/2, 1, 2 and 5. There a nearest filter
//! reads texel `(x, y)` and a linear one `3/4` of it and `1/4` of `(x + 1, y)`, its value plus
//! `1/4`, exact in `float` on every device; a level is a value a `half` holds, so Metal's rounding
//! of it moves nothing.
//!
//! **The rows** are every `MTLSamplerMipFilter`, crossed with the two `(min, mag)` pairs whose
//! filters differ, crossed with three clamps: Metal's defaults `[0, FLT_MAX]`, `lodMinClamp` 1
//! (which raises every level above 0) and `lodMaxClamp` 0 (which lowers every level to 0). The
//! two clamps tell the sampler's clamp apart from the texture's: a choice read after the
//! sampler's clamp minifies at every level of the first and magnifies at every level of the
//! second.
//!
//! **`sampler-one-level-filters-level`**: the owned fixture `unv_runtime_levels`' `unv_rpos2d`
//! samples at `(p.x, p.y)` at `level(p.z)` through the runtime sampler at `[[sampler(0)]]` and
//! writes the first channel. **`sampler-one-level-filters-bias`**: `mip_level_sampling`'s
//! `mip_bias_kernel` samples at `bias(p.z)`, a kernel's level `p.z`, and writes the `float4`.
//!
//! **What Metal answered** (the Apple M3 Max on macOS 27.0.1), alike in both
//! cases and under all three mip filters, every lane of a cell one filter (`mag` the magnifying
//! filter, `min` the minifying one):
//!
//! | clamp | -2 | -0.5 | 0 | 1/64 | 1/4 | 1/2 | 1 | 2 | 5 |
//! |---|---|---|---|---|---|---|---|---|---|
//! | `[0, FLT_MAX]` | mag | mag | mag | min | min | min | min | min | min |
//! | `lodMinClamp` 1 | min | min | min | min | min | min | min | min | min |
//! | `lodMaxClamp` 0 | mag | mag | mag | mag | mag | mag | mag | mag | mag |
//!
//! So Metal reads its choice after the sampler's clamp and before the clamp into the texture's
//! one level, the rule `tests` holds every recorded lane to. The device's own sampler takes
//! Vulkan's choice, which reads `λ` after the sampler's `[minLod, maxLod]` and before the view's
//! levels, so the runtime's answer is expected to be Metal's on every device.
//!
//! Nothing here can fault a GPU: one compute dispatch of 540 threads a row, one read-only 16 by 4
//! texture, no loop.
use crate::allowance::Allowance;
use crate::case::{
call, made, Abort, Bindings, Case, Failure, Input, MetalSource, SamplerSpec, Side,
};
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef;
use crate::texture::{TextureRequest, Upload};
use crate::transcript::{ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites, Value};
use metal2vulkan::metal::{PixelFormat, SamplerMinMagFilter, SamplerMipFilter};
/// The texture's width and height.
const WIDTH: u32 = 16;
const HEIGHT: u32 = 4;
/// The levels every position is sampled at: the probe's nine, each a value a `half` holds.
const LEVELS: [f32; 9] = [-2.0, -0.5, 0.0, 0.015_625, 0.25, 0.5, 1.0, 2.0, 5.0];
/// The byte every output buffer holds before a row runs.
const FILL: u8 = 0xab;
/// The threads a group: the 540 lanes are nine groups of 60, so the grid is whole groups on every
/// device.
const GROUP: u32 = 60;
/// Every `MTLSamplerMipFilter`.
const MIP_FILTERS: [(&str, SamplerMipFilter); 3] = [
("not-mipmapped", SamplerMipFilter::NotMipmapped),
("nearest", SamplerMipFilter::Nearest),
("linear", SamplerMipFilter::Linear),
];
/// The two `(min, mag)` pairs whose filters differ.
const FILTER_PAIRS: [(&str, SamplerMinMagFilter, SamplerMinMagFilter); 2] = [
(
"nearest-min-linear-mag",
SamplerMinMagFilter::Nearest,
SamplerMinMagFilter::Linear,
),
(
"linear-min-nearest-mag",
SamplerMinMagFilter::Linear,
SamplerMinMagFilter::Nearest,
),
];
/// The `(lodMinClamp, lodMaxClamp)` pairs: Metal's defaults, a lower bound above 0 and an upper
/// bound of 0.
const CLAMPS: [(&str, f32, f32); 3] = [
("clamp-default", 0.0, f32::MAX),
("clamp-from-1", 1.0, f32::MAX),
("clamp-to-0", 0.0, 0.0),
];
/// What the kernel reads the level as.
#[derive(Clone, Copy, Debug)]
enum Kind {
/// `level(p.z)`, through `unv_rpos2d`, which writes the first channel.
Level,
/// `bias(p.z)`, through `mip_bias_kernel`, which writes the `float4`.
Bias,
}
/// One case of this module.
#[derive(Clone, Copy, Debug)]
pub struct OneLevelFilters {
name: &'static str,
kind: Kind,
}
/// Every case of this module.
pub fn all() -> Vec<Box<dyn Case>> {
[
("sampler-one-level-filters-level", Kind::Level),
("sampler-one-level-filters-bias", Kind::Bias),
]
.into_iter()
.map(|(name, kind)| Box::new(OneLevelFilters { name, kind }) as Box<dyn Case>)
.collect()
}
/// Texel `(x, y)`: `1 + x + 16 y`, a small integer exact in `float`.
fn texel(x: u32, y: u32) -> f32 {
(1 + x + WIDTH * y) as f32
}
/// The texture's texels, row by row.
fn texture_bytes() -> Vec<u8> {
(0..HEIGHT)
.flat_map(|y| (0..WIDTH).map(move |x| texel(x, y)))
.flat_map(f32::to_le_bytes)
.collect()
}
/// The texels each lane samples beside: every texel but a row's last, row by row.
fn positions() -> Vec<(u32, u32)> {
(0..HEIGHT)
.flat_map(|y| (0..WIDTH - 1).map(move |x| (x, y)))
.collect()
}
/// The lanes: every position at each level, level by level.
fn lanes() -> u32 {
(LEVELS.len() * positions().len()) as u32
}
/// The parameter buffer: `(s, t, level, 0)` a lane, a quarter of a texel past the texel's centre
/// toward its right neighbour.
fn params() -> Vec<u8> {
let mut out = Vec::new();
for &level in &LEVELS {
for (x, y) in positions() {
let s = (x as f32 + 0.75) / WIDTH as f32;
let t = (y as f32 + 0.5) / HEIGHT as f32;
for word in [s, t, level, 0.0] {
out.extend(word.to_le_bytes());
}
}
}
out
}
/// Every row: its name and the sampler state it makes.
fn rows() -> Vec<(String, SamplerSpec)> {
let mut out = Vec::new();
for (mip_name, mip) in MIP_FILTERS {
for (pair, min, mag) in FILTER_PAIRS {
for (clamp, lo, hi) in CLAMPS {
let mut spec = SamplerSpec::new().mipped(mip).clamped_from(lo);
spec.lod_max_clamp = hi;
spec.min_filter = min;
spec.mag_filter = mag;
out.push((format!("{mip_name}-{pair}-{clamp}"), spec));
}
}
}
out
}
impl OneLevelFilters {
/// The fixture and entry point the case runs.
fn fixture(&self) -> Fixture {
match self.kind {
Kind::Level => Fixture {
name: "unv_runtime_levels",
entry: "unv_rpos2d",
},
Kind::Bias => Fixture {
name: "mip_level_sampling",
entry: "mip_bias_kernel",
},
}
}
/// The `float`s a lane writes.
fn lane_floats(&self) -> u32 {
match self.kind {
Kind::Level => 1,
Kind::Bias => 4,
}
}
/// The bytes a row's output buffer takes.
fn output_bytes(&self) -> usize {
(lanes() * self.lane_floats() * 4) as usize
}
/// The layout a row's output is read under: one row of the layout a level, its positions'
/// results in order, so a diff names the level and the position.
fn layout(&self) -> ByteLayout {
let row_elements = positions().len() as u32 * self.lane_floats();
let rows = LEVELS.len() as u32;
ByteLayout {
region: Region::Buffer {
offset: 0,
length: self.output_bytes() as u64,
},
element: Element::F32,
row_offset: 0,
row_elements,
row_pitch: row_elements * 4,
rows,
image_pitch: rows * row_elements * 4,
images: 1,
gaps: Gaps::Compared,
}
}
}
impl Case for OneLevelFilters {
fn name(&self) -> &'static str {
self.name
}
fn metal_source(&self) -> MetalSource {
MetalSource::Run
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let fixture = self.fixture();
let mut shaders = Vec::new();
for extension in [RUNTIME_TEXT, METAL_TEXT] {
shaders.push(ShaderRef {
fixture: format!("{}{extension}", fixture.name),
entry: fixture.entry.to_owned(),
source_sha256: crate::sha256_hex(fixture.text(extension)?.as_bytes()),
});
}
Ok(shaders)
}
fn allowances(&self) -> Vec<Allowance> {
// Nothing is loosened: every sample of every row compares exactly. Every row samples
// through the runtime sampler at `[[sampler(0)]]`, which the runtime's pipelines note as
// scaled (`crate::replay::pixel_sampler_scaling_notice` holds why); the declaration sits
// at the notices site alone.
vec![crate::replay::pixel_sampler_scaling_notice()]
}
fn inputs(&self) -> Result<Vec<Input>, String> {
let fixture = self.fixture();
let mut inputs = vec![
Input {
name: "air".to_owned(),
digest: Digest::sha256(fixture.text(RUNTIME_TEXT)?.as_bytes()),
},
Input {
name: "air-typed".to_owned(),
digest: Digest::sha256(fixture.text(METAL_TEXT)?.as_bytes()),
},
Input::bytes("entry", fixture.entry.as_bytes()),
Input::bytes("buffer:params", &params()),
Input::bytes("buffer:out", &vec![FILL; self.output_bytes()]),
Input::bytes("texture:level-0", &texture_bytes()),
];
for (name, spec) in rows() {
inputs.push(Input::bytes(format!("sampler:{name}"), &spec.words()));
}
Ok(inputs)
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
let fixture = self.fixture();
let loaded = fixture.loaded().map_err(|why| Abort {
at: "library".to_owned(),
failure: Failure::named("FixtureNotRead", why),
})?;
let library = made(sites, "library", side.library(&loaded.source()))?;
let pipeline = made(
sites,
"pipeline",
side.compute_pipeline(library, fixture.entry),
)?;
let bytes = texture_bytes();
let uploads = [Upload::level_0([WIDTH, HEIGHT], WIDTH * 4, HEIGHT, &bytes)];
let request =
TextureRequest::read_2d(PixelFormat::R32Float.as_raw(), WIDTH, HEIGHT).loaded(&uploads);
let texture = made(sites, "texture", side.texture(&request))?;
let parameters = made(sites, "buffer/params", side.buffer(&params()))?;
for (name, spec) in rows() {
let at = |site: &str| format!("{name}/{site}");
let sampler = made(sites, &at("sampler"), side.sampler(&spec))?;
let output = made(
sites,
&at("buffer/out"),
side.buffer(&vec![FILL; self.output_bytes()]),
)?;
let command_buffer = made(
sites,
&at("dispatch"),
side.dispatch_threads(
pipeline,
&Bindings::new(&[texture], &[parameters, output]).sampled(&[sampler]),
&[],
[lanes(), 1, 1],
[GROUP, 1, 1],
),
)?;
call(
sites,
&at("status"),
side.wait(command_buffer),
Clone::clone,
)?;
let read = call(
sites,
&at("read-back"),
side.read_buffer(output, 0, self.output_bytes()),
|_| Value::Absent,
)?;
sites.push(
Node::branch(name.clone(), Vec::new())
.with(Node::leaf("sampled", Observed::bytes(read, self.layout()))),
);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The bytes the committed recording of `case` holds at row `row`, over every outcome of every
/// answer, or `None` where the tree holds no recording of the case yet. A recording that holds
/// no bytes at the row is a failure: that is a renamed site.
fn recorded(case: &str, row: &str) -> Option<Vec<Vec<u8>>> {
let recording = crate::recording::read(case).ok()?;
let mut out = Vec::new();
for answer in &recording.answers {
for outcome in &answer.outcomes {
let held = outcome
.transcript
.root
.child(row)
.and_then(|node| node.child("sampled"))
.map(|node| &node.observed.value);
match held {
Some(Value::Bytes(bytes)) => out.push(bytes.clone()),
_ => panic!("{case}: the recording holds no bytes at {row}/sampled"),
}
}
}
assert!(!out.is_empty(), "{case}: a recording with no outcome");
Some(out)
}
/// Whether a sample at `level` through a sampler clamping the level into `[lo, hi]` minifies:
/// where `L + q` of the level clamped into the sampler's clamp is above 0, `L` its floor and
/// `q` its fraction truncated onto sixty-fourths (`lower::sampler::level`). `last`, where
/// given, also clamps the level into the texture's levels `[0, last]` first, the reading that
/// module stated before that probe: on this texture of one level it magnifies everywhere.
fn minifies(level: f32, (lo, hi): (f32, f32), last: Option<f32>) -> bool {
let mut h = level.max(lo).min(hi);
if let Some(last) = last {
h = h.max(0.0).min(last);
}
let l = h.floor();
let q = ((h - l) * 64.0).floor() / 64.0;
l + q > 0.0
}
/// What `filter` reads at position `(x, y)`'s lane: the texel, or a linear filter's `3/4` of
/// it and `1/4` of its right neighbour, which is one more.
fn sampled(filter: SamplerMinMagFilter, (x, y): (u32, u32)) -> f32 {
match filter {
SamplerMinMagFilter::Linear => texel(x, y) + 0.25,
_ => texel(x, y),
}
}
/// Every lane of every recorded row is the filter Metal's rule names: the minifying one where
/// the level clamped into the sampler's clamp is above 0 on Metal's grid, before the clamp
/// into the texture's one level, and the magnifying one elsewhere. The reading that took the
/// choice after the texture's clamp names the other filter at every lane where the two
/// readings part, and the case holds such lanes: under the default clamp, at the six levels
/// above 0, and every level of `lodMinClamp` 1.
#[test]
fn the_recorded_filters_are_chosen_before_the_texture_levels_clamp() {
let mut parted = 0;
for case in all() {
let floats = match case.name() {
"sampler-one-level-filters-level" => 1,
_ => 4,
};
for (row, spec) in rows() {
let Some(outcomes) = recorded(case.name(), &row) else {
return;
};
let clamp = (spec.lod_min_clamp, spec.lod_max_clamp);
let filter = |minify: bool| match minify {
true => spec.min_filter,
false => spec.mag_filter,
};
for bytes in outcomes {
for (i, &level) in LEVELS.iter().enumerate() {
let before = filter(minifies(level, clamp, None));
let after = filter(minifies(level, clamp, Some(0.0)));
for (p, &position) in positions().iter().enumerate() {
let at = (i * positions().len() + p) * floats * 4;
let got = f32::from_le_bytes(
bytes[at..at + 4].try_into().expect("four bytes"),
);
let want = sampled(before, position);
assert_eq!(
got,
want,
"{} {row}: level {level} at {position:?} read {got}, where the \
{before:?} filter reads {want}",
case.name()
);
if sampled(after, position) != got {
parted += 1;
}
}
}
}
}
}
// Per case and outcome: 6 rows (3 mip filters, 2 pairs) at 6 levels under the default
// clamp, and at all 9 under `lodMinClamp` 1, 60 positions each.
assert!(parted >= 2 * 6 * (6 + 9) * 60, "{parted} lanes parted");
}
}
@@ -23,13 +23,14 @@
//! `the_recorded_digests_are_the_m4_answers` hold the recorded M3 answers against the digests an //! `the_recorded_digests_are_the_m4_answers` hold the recorded M3 answers against the digests an
//! Apple M4 answered: same question, two chips. //! Apple M4 answered: same question, two chips.
//! //!
//! **What may differ, and what justifies it.** A nearest site hands the device's normalized //! **What may differ, and what justifies it.** A `const` site hands the device's unnormalized
//! sampler its texel's centre over the size, where the device reads exactly Metal's texel (a //! sampler the coordinate itself, and a nearest `slot` or `arg` site hands the device's normalized
//! nearest `const` site clamped to the edge fetches the texel). A linear site hands it the //! sampler its texel's centre over the size, where the device reads exactly Metal's texel. A linear
//! coordinate divided by the size, which the device's sampler reads in its own arithmetic: at a //! `slot` or `arg` site hands it the coordinate divided by the size, which the device's sampler
//! sub-texel step it may read the neighbouring step, which the runtime announces on every device //! reads in its own arithmetic: at a sub-texel step it may read the neighbouring step, which the
//! (`pixel-sampler-scaling`, and `argument-pixel-sampler-scaling` for `arg`). The `slot` site //! runtime announces on every device (`pixel-sampler-scaling`, and
//! announces it under a nearest state too, as the function does not know the bound state. //! `argument-pixel-sampler-scaling` for `arg`). The `slot` site announces it under a nearest
//! state too, as the function does not know the bound state.
//! Each notice is declared at the notices site alone, so a texel that differs still fails the case //! Each notice is declared at the notices site alone, so a texel that differs still fails the case
//! where it differs, and is a `known-gaps-rt.tsv` row naming the note. //! where it differs, and is a `known-gaps-rt.tsv` row naming the note.
//! //!
@@ -39,9 +40,8 @@
//! sign, or `-2^-126` beside them (`subnormal_grid`). A nearest `slot` or `arg` site hands the //! sign, or `-2^-126` beside them (`subnormal_grid`). A nearest `slot` or `arg` site hands the
//! device its texel's centre `floor(x) + 0.5`, whose `floor` reads a subnormal by the device's //! device its texel's centre `floor(x) + 0.5`, whose `floor` reads a subnormal by the device's
//! float controls (`device-denormals`, a native note): where a negative subnormal is a texel apart //! float controls (`device-denormals`, a native note): where a negative subnormal is a texel apart
//! from zero to Metal's sampler (the recorded answers read texel -1 there, and texel 0 at a //! from zero to Metal's sampler, an address mode that reads texel -1 as texel 0 (clamp to edge,
//! positive subnormal), an address mode that reads texel -1 as texel 0 (clamp to edge, mirror //! mirror clamp to edge) answers alike, and clamp to zero and to the border read the border.
//! clamp to edge) answers alike, and clamp to zero and to the border read the border.
//! //!
//! Nothing here can fault a GPU: one small texture, three or four compute passes a case, no loop. //! Nothing here can fault a GPU: one small texture, three or four compute passes a case, no loop.
//! The coordinates do reach outside the texture, which is what the address modes are for. //! The coordinates do reach outside the texture, which is what the address modes are for.
@@ -1,258 +0,0 @@
//! `sparse-read-through`: what Metal 4.1's `sparse_read(sampler s, coord, offset, lod)` answers
//! through a sampler of a texture that is not sparse: each read's colour, and its residency
//! (`sparse_color::resident()`).
//!
//! The kernel is the owned fixture `a2_sparse_read_through`. Thread `i` reads a 4 × 4
//! `RGBA32Float` texture of two levels at [`POSITIONS`]`[i]` (x, y, then the level) through four
//! constexpr samplers, `clamp_to_edge`, `clamp_to_zero`, `clamp_to_border` (opaque white) and
//! `repeat`, and stores the four colours' words, then the four residencies (1 for resident). The
//! positions lie inside the texture, one and several texels past each edge, at level 1 (which a
//! sampler without a mip filter reads as level 0), and at levels past the texture's last.
//!
//! Our own probe of this kernel on the Apple M3 Max (macOS 27.0.1), plain and under Metal's
//! validation layer (which reported nothing), read every residency as resident, at every position
//! and through every sampler, with the colours of a read through a sampler (the conformance family
//! `read_through`): the edge texel through `clamp_to_edge` and `repeat`, the border texel through
//! `clamp_to_zero` and `clamp_to_border`, zero in every lane at a level past the last. The runtime
//! answers resident, a constant, so the recording, which is the M3 Max's, holds it to that answer.
//!
//! One compute pass of [`THREADS`] threads, no loop, and every coordinate outside the texture is
//! the sampler's to address: nothing here can fault a GPU.
use crate::case::{call, made, Abort, Bindings, Case, Failure, Input, MetalSource, Side};
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef;
use crate::texture::{TextureRequest, Upload};
use crate::transcript::{ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites};
use metal2vulkan::metal::PixelFormat;
/// The fixture the kernel lives in, and the kernel.
const FIXTURE: &str = "a2_sparse_read_through";
/// The texture's width and height at level 0.
const SIDE: u32 = 4;
/// The texture's levels.
const LEVELS: u32 = 2;
/// Each thread's position: x, y, the level, and a word the kernel does not read.
pub const POSITIONS: [[i32; 4]; 12] = [
[1, 2, 0, 0],
[3, 3, 0, 0],
[4, 1, 0, 0],
[-1, 2, 0, 0],
[2, -1, 0, 0],
[7, 9, 0, 0],
[-6, -5, 0, 0],
[1, 1, 1, 0],
[3, 0, 1, 0],
[5, 5, 1, 0],
[0, 0, 2, 0],
[2, 1, 5, 0],
];
/// The threads: one a position.
pub const THREADS: u32 = POSITIONS.len() as u32;
/// The bytes a thread stores: five `uint4`s.
const STORED: u32 = 80;
/// The byte every output word holds before the dispatch.
const BLANK: u8 = 0xab;
/// The texel at `(x, y)` of `level`: distinct within and between the levels, and exact in
/// `float`.
pub fn texel(level: u32, x: u32, y: u32) -> [f32; 4] {
let (x, y) = (x as f32, y as f32);
match level {
0 => [x + 0.25, y + 0.5, (x + 4.0 * y) / 16.0, 1.0],
_ => [x + 10.25, y + 10.5, 0.75, 0.5],
}
}
/// Each level's bytes, row by row.
fn levels() -> Vec<Vec<u8>> {
(0..LEVELS)
.map(|level| {
let side = SIDE >> level;
(0..side)
.flat_map(|y| (0..side).map(move |x| (x, y)))
.flat_map(|(x, y)| texel(level, x, y))
.flat_map(f32::to_le_bytes)
.collect()
})
.collect()
}
/// The uploads of `levels`' bytes, one a level.
fn uploads(levels: &[Vec<u8>]) -> Vec<Upload<'_>> {
(0..LEVELS)
.zip(levels)
.map(|(level, bytes)| {
let side = SIDE >> level;
Upload {
level,
..Upload::level_0([side, side], side * 16, side, bytes)
}
})
.collect()
}
/// The texture of `uploads`.
fn request<'a>(uploads: &'a [Upload<'a>]) -> TextureRequest<'a> {
TextureRequest::read_2d(PixelFormat::RGBA32Float.as_raw(), SIDE, SIDE)
.levels(LEVELS)
.loaded(uploads)
}
/// Buffer 0: each thread's position, four `int`s.
fn positions() -> Vec<u8> {
POSITIONS
.iter()
.flatten()
.flat_map(|word| word.to_le_bytes())
.collect()
}
/// The layout the stored words compare under: one row a thread.
fn stored_layout() -> ByteLayout {
let length = THREADS * STORED;
ByteLayout {
region: Region::Buffer {
offset: 0,
length: u64::from(length),
},
element: Element::U32,
row_offset: 0,
row_elements: STORED / 4,
row_pitch: STORED,
rows: THREADS,
image_pitch: length,
images: 1,
gaps: Gaps::Ignored,
}
}
/// The case.
pub struct SparseReadThrough;
impl Case for SparseReadThrough {
fn name(&self) -> &'static str {
"sparse-read-through"
}
fn metal_source(&self) -> MetalSource {
MetalSource::Run
}
fn allowances(&self) -> Vec<crate::allowance::Allowance> {
// One declaration, which loosens no value: the kernel writes `out[5 * i + k]` for five
// `k`, stores the translator does not find disjoint between two threads of one
// SIMD-group, so the runtime's pipeline notes SIMD-group access pairs on every device
// (`crate::replay::simdgroup_access_order_notice`; measured through the rt side on
// lavapipe). Each thread writes slots of its own, so the note moves no value.
vec![crate::replay::simdgroup_access_order_notice()]
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let fixture = Fixture {
name: FIXTURE,
entry: FIXTURE,
};
let mut shaders = Vec::new();
for extension in [RUNTIME_TEXT, METAL_TEXT] {
shaders.push(ShaderRef {
fixture: format!("{FIXTURE}{extension}"),
entry: FIXTURE.to_owned(),
source_sha256: crate::sha256_hex(fixture.text(extension)?.as_bytes()),
});
}
Ok(shaders)
}
fn inputs(&self) -> Result<Vec<Input>, String> {
let fixture = Fixture::new(FIXTURE);
let levels = levels();
Ok(vec![
Input {
name: "air".to_owned(),
digest: Digest::sha256(fixture.text(RUNTIME_TEXT)?.as_bytes()),
},
Input {
name: "air-typed".to_owned(),
digest: Digest::sha256(fixture.text(METAL_TEXT)?.as_bytes()),
},
Input::bytes("texture", &request(&uploads(&levels)).words()),
Input::bytes("positions", &positions()),
])
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
let loaded = Fixture::new(FIXTURE).loaded().map_err(|why| Abort {
at: "library".to_owned(),
failure: Failure::named("FixtureNotRead", why),
})?;
let library = made(sites, "library", side.library(&loaded.source()))?;
let pipeline = made(sites, "pipeline", side.compute_pipeline(library, FIXTURE))?;
let levels = levels();
let uploads = uploads(&levels);
let texture = made(sites, "texture", side.texture(&request(&uploads)))?;
let positions = made(sites, "buffer/positions", side.buffer(&positions()))?;
let blank = vec![BLANK; (THREADS * STORED) as usize];
let out = made(sites, "buffer/out", side.buffer(&blank))?;
let command_buffer = made(
sites,
"dispatch",
side.dispatch_threads(
pipeline,
&Bindings::new(&[texture], &[positions, out]),
&[],
[THREADS, 1, 1],
[THREADS, 1, 1],
),
)?;
call(sites, "status", side.wait(command_buffer), Clone::clone)?;
let stored = call(
sites,
"read-back",
side.read_buffer(out, 0, blank.len()),
|_| crate::transcript::Value::Absent,
)?;
sites.push(Node::leaf(
"stored",
Observed::bytes(stored, stored_layout()),
));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
/// Every texel of the two levels is distinct, so a read of the wrong texel or the wrong level
/// shows as a value, and the uploads hold each level whole.
#[test]
fn every_texel_is_distinct() {
let mut seen = BTreeSet::new();
for level in 0..LEVELS {
let side = SIDE >> level;
for y in 0..side {
for x in 0..side {
let bits = texel(level, x, y).map(f32::to_bits);
assert!(seen.insert(bits), "{level} ({x}, {y})");
}
}
}
let levels = levels();
for upload in uploads(&levels) {
assert_eq!(
upload.bytes.len(),
upload.needed(),
"level {}",
upload.level
);
}
}
}
@@ -718,17 +718,12 @@ impl Case for TextureFills {
// by copies from a buffer, which carry the note of an upload into one // by copies from a buffer, which carry the note of an upload into one
// (`restricted-depth-upload`): those bytes are a depth below 0, which Metal keeps and a // (`restricted-depth-upload`): those bytes are a depth below 0, which Metal keeps and a
// device that clamps does not, so the note loosens the notices site alone and the digest // device that clamps does not, so the note loosens the notices site alone and the digest
// still decides. A 4:2:2 texture (`GBGR422`, `BGRG422`) states the static note of its // still decides. The format's own digest still compares.
// linear and bicubic samples, which the rt side announces where it makes one
// (`bicubic-filter-arithmetic`). The format's own digest still compares.
use crate::degradation::Degradation as D; use crate::degradation::Degradation as D;
let mut allowances = vec![notice_allowance(D::CompressedTexelDecode.code())]; let mut allowances = vec![notice_allowance(D::CompressedTexelDecode.code())];
if matches!(self.raw, 252 | 260) { if matches!(self.raw, 252 | 260) {
allowances.push(notice_allowance(D::RestrictedDepthUpload.code())); allowances.push(notice_allowance(D::RestrictedDepthUpload.code()));
} }
if matches!(self.raw, 240 | 241) {
allowances.push(notice_allowance(D::BicubicFilterArithmetic.code()));
}
allowances allowances
} }
@@ -147,18 +147,13 @@ const FORMATS: [(PixelFormat, u32, &str); 76] = [
/// for copies alone (`metal::format::copies_only`) is /// for copies alone (`metal::format::copies_only`) is
/// [`format_footprints`](crate::cases::format_footprints)'s, which records the same host round /// [`format_footprints`](crate::cases::format_footprints)'s, which records the same host round
/// trip of it beside the footprints and texture types Metal answers for it, so it is none here. /// trip of it beside the footprints and texture types Metal answers for it, so it is none here.
/// So is a 4:2:2 format (`GBGR422`, `BGRG422`), whose image holds Metal's bytes two to a texel of a
/// 2-texel block: [`chroma_pairs`](crate::cases::chroma_pairs)' copy cases record its host round
/// trips, of regions on and off the pairs.
/// ///
/// It is the table's guard and nothing else reads it: [`FORMATS`] holds the names a case must /// It is the table's guard and nothing else reads it: [`FORMATS`] holds the names a case must
/// answer with as static strings, so the list cannot be built from the predicate at run time, and /// answer with as static strings, so the list cannot be built from the predicate at run time, and
/// this is what keeps the two from parting. /// this is what keeps the two from parting.
#[cfg(test)] #[cfg(test)]
fn texel_bytes(pf: PixelFormat) -> Option<u32> { fn texel_bytes(pf: PixelFormat) -> Option<u32> {
if metal2vulkan::metal::format::copies_only(pf) if metal2vulkan::metal::format::copies_only(pf) {
|| matches!(pf, PixelFormat::GBGR422 | PixelFormat::BGRG422)
{
return None; return None;
} }
let block = metal2vulkan::metal::format::byte_format(pf)?.block()?; let block = metal2vulkan::metal::format::byte_format(pf)?.block()?;
@@ -32,6 +32,8 @@ pub enum Degradation {
DepthDenormals, DepthDenormals,
/// [`PrecisionNote::F16FmaDoubleRounding`]. /// [`PrecisionNote::F16FmaDoubleRounding`].
F16FmaDoubleRounding, F16FmaDoubleRounding,
/// [`PrecisionNote::F16IntConvDoubleRounding`].
F16IntConvDoubleRounding,
/// [`PrecisionNote::GradFromBias`]. /// [`PrecisionNote::GradFromBias`].
GradFromBias, GradFromBias,
/// [`PrecisionNote::DeviceTranscendentals`]. /// [`PrecisionNote::DeviceTranscendentals`].
@@ -172,10 +174,6 @@ pub enum Degradation {
DeviceHalfDenormals, DeviceHalfDenormals,
/// [`PrecisionNote::RoundedSampleDepthCopy`]. /// [`PrecisionNote::RoundedSampleDepthCopy`].
RoundedSampleDepthCopy, RoundedSampleDepthCopy,
/// [`PrecisionNote::ExtendedRangeBlend`].
ExtendedRangeBlend,
/// [`PrecisionNote::ExtendedRangeBlendWindow`].
ExtendedRangeBlendWindow,
} }
impl Degradation { impl Degradation {
@@ -191,6 +189,7 @@ impl Degradation {
Degradation::CompressedTexelDecode, Degradation::CompressedTexelDecode,
Degradation::DepthDenormals, Degradation::DepthDenormals,
Degradation::F16FmaDoubleRounding, Degradation::F16FmaDoubleRounding,
Degradation::F16IntConvDoubleRounding,
Degradation::GradFromBias, Degradation::GradFromBias,
Degradation::DeviceTranscendentals, Degradation::DeviceTranscendentals,
Degradation::ReductionOrder, Degradation::ReductionOrder,
@@ -261,8 +260,6 @@ impl Degradation {
Degradation::StencilOutputOverlap, Degradation::StencilOutputOverlap,
Degradation::DeviceHalfDenormals, Degradation::DeviceHalfDenormals,
Degradation::RoundedSampleDepthCopy, Degradation::RoundedSampleDepthCopy,
Degradation::ExtendedRangeBlend,
Degradation::ExtendedRangeBlendWindow,
]; ];
/// The kind's code, `metal2vulkan-degrade-<kind>`: its precision note's, which the translator /// The kind's code, `metal2vulkan-degrade-<kind>`: its precision note's, which the translator
@@ -284,6 +281,7 @@ impl Degradation {
Degradation::CompressedTexelDecode => PrecisionNote::CompressedTexelDecode, Degradation::CompressedTexelDecode => PrecisionNote::CompressedTexelDecode,
Degradation::DepthDenormals => PrecisionNote::DepthDenormals, Degradation::DepthDenormals => PrecisionNote::DepthDenormals,
Degradation::F16FmaDoubleRounding => PrecisionNote::F16FmaDoubleRounding, Degradation::F16FmaDoubleRounding => PrecisionNote::F16FmaDoubleRounding,
Degradation::F16IntConvDoubleRounding => PrecisionNote::F16IntConvDoubleRounding,
Degradation::GradFromBias => PrecisionNote::GradFromBias, Degradation::GradFromBias => PrecisionNote::GradFromBias,
Degradation::DeviceTranscendentals => PrecisionNote::DeviceTranscendentals, Degradation::DeviceTranscendentals => PrecisionNote::DeviceTranscendentals,
Degradation::ReductionOrder => PrecisionNote::ReductionOrder, Degradation::ReductionOrder => PrecisionNote::ReductionOrder,
@@ -356,8 +354,6 @@ impl Degradation {
Degradation::StencilOutputOverlap => PrecisionNote::StencilOutputOverlap, Degradation::StencilOutputOverlap => PrecisionNote::StencilOutputOverlap,
Degradation::DeviceHalfDenormals => PrecisionNote::DeviceHalfDenormals, Degradation::DeviceHalfDenormals => PrecisionNote::DeviceHalfDenormals,
Degradation::RoundedSampleDepthCopy => PrecisionNote::RoundedSampleDepthCopy, Degradation::RoundedSampleDepthCopy => PrecisionNote::RoundedSampleDepthCopy,
Degradation::ExtendedRangeBlend => PrecisionNote::ExtendedRangeBlend,
Degradation::ExtendedRangeBlendWindow => PrecisionNote::ExtendedRangeBlendWindow,
} }
} }
@@ -365,6 +361,7 @@ impl Degradation {
pub const fn from_precision_note(note: PrecisionNote) -> Degradation { pub const fn from_precision_note(note: PrecisionNote) -> Degradation {
match note { match note {
PrecisionNote::F16FmaDoubleRounding => Degradation::F16FmaDoubleRounding, PrecisionNote::F16FmaDoubleRounding => Degradation::F16FmaDoubleRounding,
PrecisionNote::F16IntConvDoubleRounding => Degradation::F16IntConvDoubleRounding,
PrecisionNote::GradFromBias => Degradation::GradFromBias, PrecisionNote::GradFromBias => Degradation::GradFromBias,
PrecisionNote::DeviceTranscendentals => Degradation::DeviceTranscendentals, PrecisionNote::DeviceTranscendentals => Degradation::DeviceTranscendentals,
PrecisionNote::ReductionOrder => Degradation::ReductionOrder, PrecisionNote::ReductionOrder => Degradation::ReductionOrder,
@@ -446,8 +443,6 @@ impl Degradation {
PrecisionNote::StencilOutputOverlap => Degradation::StencilOutputOverlap, PrecisionNote::StencilOutputOverlap => Degradation::StencilOutputOverlap,
PrecisionNote::DeviceHalfDenormals => Degradation::DeviceHalfDenormals, PrecisionNote::DeviceHalfDenormals => Degradation::DeviceHalfDenormals,
PrecisionNote::RoundedSampleDepthCopy => Degradation::RoundedSampleDepthCopy, PrecisionNote::RoundedSampleDepthCopy => Degradation::RoundedSampleDepthCopy,
PrecisionNote::ExtendedRangeBlend => Degradation::ExtendedRangeBlend,
PrecisionNote::ExtendedRangeBlendWindow => Degradation::ExtendedRangeBlendWindow,
} }
} }
} }
@@ -1,31 +1,26 @@
//! The translator's pipeline descriptors as a side states and reads them for the descriptor //! The translator's pipeline descriptors as a side states and reads them for the descriptor
//! families ([`crate::render_descriptors`], [`crate::compute_descriptors`], //! families ([`crate::render_descriptors`], [`crate::compute_descriptors`]), and the stage lists
//! [`crate::mesh_descriptors`]), and the stage lists and buffer mutability every pipeline //! and buffer mutability every pipeline descriptor family reads.
//! descriptor family reads.
//! //!
//! The runtime takes Metal's pipeline descriptors as the translator's //! The runtime takes Metal's pipeline descriptors as the translator's
//! ([`RenderPipelineDescriptor`], [`ComputePipelineDescriptor`], [`MeshPipelineDescriptor`]), so //! ([`RenderPipelineDescriptor`], [`ComputePipelineDescriptor`]), so the stating and the reading
//! the stating and the reading are one walk. What neither descriptor holds, its `label` and its //! are one walk. What neither descriptor holds, its `label` and its `binaryArchives`, the side
//! `binaryArchives`, the side answers itself as a [`Field`]. //! answers itself as a [`Field`].
use crate::case::Field; use crate::case::Field;
use crate::compute_descriptors::{ use crate::compute_descriptors::{
ComputeDescriptorFacts, SuppliedLists as ComputeSuppliedLists, AWAY as COMPUTE_AWAY, ComputeDescriptorFacts, SuppliedLists as ComputeSuppliedLists, AWAY as COMPUTE_AWAY,
}; };
use crate::mesh_descriptors::{
DescriptorLimits as MeshDescriptorLimits, MeshDescriptorFacts,
SuppliedLists as MeshSuppliedLists, AWAY as MESH_AWAY,
};
use crate::render_descriptors::{ use crate::render_descriptors::{
AttributeFacts as DescriptorAttributeFacts, ColorAway, ColorFacts, LayoutFacts, LinkedCounts, AttributeFacts as DescriptorAttributeFacts, ColorFacts, LayoutFacts, LinkedCounts,
RenderDescriptorFacts, SuppliedLists, VertexDescriptorFacts, AWAY, READ_BUFFERS, READ_COLORS, RenderDescriptorFacts, SuppliedLists, VertexDescriptorFacts, AWAY, READ_BUFFERS, READ_COLORS,
READ_VERTEX_SLOTS, READ_VERTEX_SLOTS,
}; };
use metal2vulkan::metal::{Mutability, PixelFormat}; use metal2vulkan::metal::{Mutability, PixelFormat};
use metal2vulkan::pipeline::{ use metal2vulkan::pipeline::{
ColorAttachmentDescriptor, ComputePipelineDescriptor, MeshPipelineDescriptor, ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource,
RenderPipelineDescriptor, StageSource, TessellationDescriptor, VertexAttributeDescriptor, TessellationDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor,
VertexBufferLayoutDescriptor, VertexDescriptor, VertexDescriptor,
}; };
/// Set every field of the translator's descriptor that [`AWAY`] states, each away from Metal's /// Set every field of the translator's descriptor that [`AWAY`] states, each away from Metal's
@@ -59,7 +54,20 @@ pub(crate) fn state_render(descriptor: &mut RenderPipelineDescriptor) {
AWAY.support_adding_fragment_binary_functions; AWAY.support_adding_fragment_binary_functions;
descriptor.max_vertex_call_stack_depth = AWAY.max_vertex_call_stack_depth; descriptor.max_vertex_call_stack_depth = AWAY.max_vertex_call_stack_depth;
descriptor.max_fragment_call_stack_depth = AWAY.max_fragment_call_stack_depth; descriptor.max_fragment_call_stack_depth = AWAY.max_fragment_call_stack_depth;
state_colors(&mut descriptor.color_attachments, AWAY.colors); for color in AWAY.colors {
let mut attachment = ColorAttachmentDescriptor::new(color.pixel_format);
attachment.blending_enabled = color.blending_enabled;
attachment.source_rgb_blend_factor = color.source_rgb;
attachment.destination_rgb_blend_factor = color.destination_rgb;
attachment.rgb_blend_operation = color.rgb_operation;
attachment.source_alpha_blend_factor = color.source_alpha;
attachment.destination_alpha_blend_factor = color.destination_alpha;
attachment.alpha_blend_operation = color.alpha_operation;
attachment.write_mask = color.write_mask;
if let Some(slot) = descriptor.color_attachments.get_mut(color.index as usize) {
*slot = Some(attachment);
}
}
for (index, mutability) in AWAY.vertex_buffers { for (index, mutability) in AWAY.vertex_buffers {
descriptor.vertex_buffers.insert(*index, *mutability); descriptor.vertex_buffers.insert(*index, *mutability);
} }
@@ -104,7 +112,27 @@ pub(crate) fn read_render(
) -> RenderDescriptorFacts { ) -> RenderDescriptorFacts {
let (vertex_libraries, vertex_linked) = stage_lists(Some(&descriptor.vertex)); let (vertex_libraries, vertex_linked) = stage_lists(Some(&descriptor.vertex));
let (fragment_libraries, fragment_linked) = stage_lists(descriptor.fragment.as_ref()); let (fragment_libraries, fragment_linked) = stage_lists(descriptor.fragment.as_ref());
let colors = read_colors(&descriptor.color_attachments); let colors = (0..READ_COLORS)
.map(|index| {
let held = descriptor
.color_attachments
.get(index as usize)
.and_then(Option::as_ref)
.copied()
.unwrap_or_else(|| ColorAttachmentDescriptor::new(PixelFormat::Invalid));
ColorFacts {
pixel_format: held.pixel_format.as_raw(),
blending_enabled: held.blending_enabled,
source_rgb: held.source_rgb_blend_factor.as_raw(),
destination_rgb: held.destination_rgb_blend_factor.as_raw(),
rgb_operation: held.rgb_blend_operation.as_raw(),
source_alpha: held.source_alpha_blend_factor.as_raw(),
destination_alpha: held.destination_alpha_blend_factor.as_raw(),
alpha_operation: held.alpha_blend_operation.as_raw(),
write_mask: held.write_mask.as_raw(),
}
})
.collect();
let tessellation = descriptor.tessellation.unwrap_or_default(); let tessellation = descriptor.tessellation.unwrap_or_default();
RenderDescriptorFacts { RenderDescriptorFacts {
label, label,
@@ -155,145 +183,6 @@ pub(crate) fn read_render(
} }
} }
/// Set each stated colour attachment of `colors` in `attachments`, at its index.
fn state_colors(attachments: &mut [Option<ColorAttachmentDescriptor>], colors: &[ColorAway]) {
for color in colors {
let mut attachment = ColorAttachmentDescriptor::new(color.pixel_format);
attachment.blending_enabled = color.blending_enabled;
attachment.source_rgb_blend_factor = color.source_rgb;
attachment.destination_rgb_blend_factor = color.destination_rgb;
attachment.rgb_blend_operation = color.rgb_operation;
attachment.source_alpha_blend_factor = color.source_alpha;
attachment.destination_alpha_blend_factor = color.destination_alpha;
attachment.alpha_blend_operation = color.alpha_operation;
attachment.write_mask = color.write_mask;
if let Some(slot) = attachments.get_mut(color.index as usize) {
*slot = Some(attachment);
}
}
}
/// The first [`READ_COLORS`] colour attachments of `attachments`, each slot nothing set Metal's
/// `MTLPixelFormatInvalid` with blending off and every channel written (the runtime's claim about
/// Metal's default, which each family's Metal recording checks).
fn read_colors(attachments: &[Option<ColorAttachmentDescriptor>]) -> Vec<ColorFacts> {
(0..READ_COLORS)
.map(|index| {
let held = attachments
.get(index as usize)
.and_then(Option::as_ref)
.copied()
.unwrap_or_else(|| ColorAttachmentDescriptor::new(PixelFormat::Invalid));
ColorFacts {
pixel_format: held.pixel_format.as_raw(),
blending_enabled: held.blending_enabled,
source_rgb: held.source_rgb_blend_factor.as_raw(),
destination_rgb: held.destination_rgb_blend_factor.as_raw(),
rgb_operation: held.rgb_blend_operation.as_raw(),
source_alpha: held.source_alpha_blend_factor.as_raw(),
destination_alpha: held.destination_alpha_blend_factor.as_raw(),
alpha_operation: held.alpha_blend_operation.as_raw(),
write_mask: held.write_mask.as_raw(),
}
})
.collect()
}
/// Set every field of the translator's mesh descriptor that [`MESH_AWAY`] states, each away from
/// Metal's own default. A limit Metal holds as 0 or a zero size is the runtime's `None`, so a
/// stated one is `Some`.
///
/// The label is no field of the translator's descriptor, as [`state_render`] says.
pub(crate) fn state_mesh(descriptor: &mut MeshPipelineDescriptor) {
let stated = |held: u32| (held != 0).then_some(held);
let sized = |held: [u32; 3]| (held != [0; 3]).then_some(held);
descriptor.raster_sample_count = MESH_AWAY.raster_sample_count;
descriptor.alpha_to_coverage = MESH_AWAY.alpha_to_coverage;
descriptor.alpha_to_one = MESH_AWAY.alpha_to_one;
descriptor.rasterization_enabled = MESH_AWAY.rasterization_enabled;
descriptor.depth_format = Some(MESH_AWAY.depth_format);
descriptor.stencil_format = Some(MESH_AWAY.stencil_format);
descriptor.support_indirect_command_buffers = MESH_AWAY.support_indirect_command_buffers;
let limits = MESH_AWAY.limits;
descriptor.max_total_threads_per_object_threadgroup =
stated(limits.max_total_threads_per_object_threadgroup);
descriptor.max_total_threads_per_mesh_threadgroup =
stated(limits.max_total_threads_per_mesh_threadgroup);
descriptor.object_threadgroup_size_is_multiple_of_thread_execution_width =
limits.object_threadgroup_size_is_multiple_of_thread_execution_width;
descriptor.mesh_threadgroup_size_is_multiple_of_thread_execution_width =
limits.mesh_threadgroup_size_is_multiple_of_thread_execution_width;
descriptor.payload_memory_length = stated(limits.payload_memory_length);
descriptor.max_total_threadgroups_per_mesh_grid =
stated(limits.max_total_threadgroups_per_mesh_grid);
descriptor.max_vertex_amplification_count = limits.max_vertex_amplification_count;
descriptor.required_threads_per_object_threadgroup =
sized(limits.required_threads_per_object_threadgroup);
descriptor.required_threads_per_mesh_threadgroup =
sized(limits.required_threads_per_mesh_threadgroup);
state_colors(&mut descriptor.color_attachments, MESH_AWAY.colors);
}
/// What the translator's mesh `descriptor` answers of itself, beside the `label` and
/// `binary_archives` the side answers, as [`read_render`] reads a render one: a limit the
/// descriptor holds as `None` is Metal's 0 or zero size.
pub(crate) fn read_mesh(
descriptor: &MeshPipelineDescriptor,
label: Field<Option<String>>,
binary_archives: Field<u64>,
supplied: bool,
) -> MeshDescriptorFacts {
MeshDescriptorFacts {
label,
object_function: descriptor.object.as_ref().map(stage_entry),
mesh_function: Some(stage_entry(&descriptor.mesh)),
fragment_function: descriptor.fragment.as_ref().map(stage_entry),
raster_sample_count: u64::from(descriptor.raster_sample_count),
alpha_to_coverage_enabled: descriptor.alpha_to_coverage,
alpha_to_one_enabled: descriptor.alpha_to_one,
rasterization_enabled: descriptor.rasterization_enabled,
colors: read_colors(&descriptor.color_attachments),
depth_attachment_pixel_format: descriptor
.depth_format
.unwrap_or(PixelFormat::Invalid)
.as_raw(),
stencil_attachment_pixel_format: descriptor
.stencil_format
.unwrap_or(PixelFormat::Invalid)
.as_raw(),
support_indirect_command_buffers: descriptor.support_indirect_command_buffers,
binary_archives,
limits: MeshDescriptorLimits {
max_total_threads_per_object_threadgroup: descriptor
.max_total_threads_per_object_threadgroup
.unwrap_or(0),
max_total_threads_per_mesh_threadgroup: descriptor
.max_total_threads_per_mesh_threadgroup
.unwrap_or(0),
object_threadgroup_size_is_multiple_of_thread_execution_width: descriptor
.object_threadgroup_size_is_multiple_of_thread_execution_width,
mesh_threadgroup_size_is_multiple_of_thread_execution_width: descriptor
.mesh_threadgroup_size_is_multiple_of_thread_execution_width,
payload_memory_length: descriptor.payload_memory_length.unwrap_or(0),
max_total_threadgroups_per_mesh_grid: descriptor
.max_total_threadgroups_per_mesh_grid
.unwrap_or(0),
max_vertex_amplification_count: descriptor.max_vertex_amplification_count,
required_threads_per_object_threadgroup: descriptor
.required_threads_per_object_threadgroup
.unwrap_or([0; 3]),
required_threads_per_mesh_threadgroup: descriptor
.required_threads_per_mesh_threadgroup
.unwrap_or([0; 3]),
},
supplied: supplied.then(|| MeshSuppliedLists {
object_linked_functions: stage_lists(descriptor.object.as_ref()).1,
mesh_linked_functions: stage_lists(Some(&descriptor.mesh)).1,
fragment_linked_functions: stage_lists(descriptor.fragment.as_ref()).1,
}),
}
}
/// The mutability of a buffer-index map's first [`READ_BUFFERS`] slots, the runtime's side of /// The mutability of a buffer-index map's first [`READ_BUFFERS`] slots, the runtime's side of
/// Metal's pipeline buffer array. /// Metal's pipeline buffer array.
/// ///
@@ -58,7 +58,6 @@
//! own `init` left. The three stage functions are all **nullable** in `objc2-metal` 0.3.2, unlike //! own `init` left. The three stage functions are all **nullable** in `objc2-metal` 0.3.2, unlike
//! the tile descriptor's, so a nil object function is a value the site records rather than a panic. //! the tile descriptor's, so a nil object function is a value the site records rather than a panic.
use crate::case::{field, Field};
use crate::render_descriptors::{optional, ordinal, ColorAway, ColorFacts, LinkedCounts, Shape}; use crate::render_descriptors::{optional, ordinal, ColorAway, ColorFacts, LinkedCounts, Shape};
use crate::transcript::{Node, NodeName, Observed, Value}; use crate::transcript::{Node, NodeName, Observed, Value};
use metal2vulkan::metal; use metal2vulkan::metal;
@@ -344,12 +343,11 @@ pub struct SuppliedLists {
} }
/// What a mesh render pipeline descriptor answers of itself. Each field is one Metal getter's /// What a mesh render pipeline descriptor answers of itself. Each field is one Metal getter's
/// answer, an enumeration by its raw ordinal so an ordinal neither side names still compares, and /// answer, an enumeration by its raw ordinal so an ordinal neither side names still compares.
/// a [`Field`] one a side may refuse alone, the descriptor's other getters still compared.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct MeshDescriptorFacts { pub struct MeshDescriptorFacts {
/// `label`; `None` is Metal's nil. /// `label`; `None` is Metal's nil.
pub label: Field<Option<String>>, pub label: Option<String>,
/// `objectFunction`'s own `name`; `None` where the descriptor holds none. /// `objectFunction`'s own `name`; `None` where the descriptor holds none.
pub object_function: Option<String>, pub object_function: Option<String>,
/// `meshFunction`'s own `name`. /// `meshFunction`'s own `name`.
@@ -366,7 +364,7 @@ pub struct MeshDescriptorFacts {
pub stencil_attachment_pixel_format: u32, pub stencil_attachment_pixel_format: u32,
pub support_indirect_command_buffers: bool, pub support_indirect_command_buffers: bool,
/// `binaryArchives`' length; a nil list is 0. /// `binaryArchives`' length; a nil list is 0.
pub binary_archives: Field<u64>, pub binary_archives: u64,
/// The limit fields. /// The limit fields.
pub limits: DescriptorLimits, pub limits: DescriptorLimits,
/// The three per-stage linked-function lists, which [`Shape::Reset`] does not read. /// The three per-stage linked-function lists, which [`Shape::Reset`] does not read.
@@ -378,7 +376,7 @@ impl MeshDescriptorFacts {
pub fn node(&self, name: impl Into<NodeName>) -> Node { pub fn node(&self, name: impl Into<NodeName>) -> Node {
let value = Observed::value; let value = Observed::value;
let mut node = Node::branch(name, Vec::new()) let mut node = Node::branch(name, Vec::new())
.with(Node::leaf("label", field(&self.label, optional))) .with(Node::leaf("label", value(optional(&self.label))))
.with(Node::leaf( .with(Node::leaf(
"object_function", "object_function",
value(optional(&self.object_function)), value(optional(&self.object_function)),
@@ -433,7 +431,7 @@ impl MeshDescriptorFacts {
)) ))
.with(Node::leaf( .with(Node::leaf(
"binary_archives", "binary_archives",
field(&self.binary_archives, |count| Value::Uint(*count)), value(Value::Uint(self.binary_archives)),
)) ))
.with(self.limits.node("limits")); .with(self.limits.node("limits"));
if let Some(supplied) = &self.supplied { if let Some(supplied) = &self.supplied {
@@ -1933,7 +1933,7 @@ fn read_mesh_descriptor(
let mesh: Option<Retained<ProtocolObject<dyn MTLFunction>>> = descriptor.meshFunction(); let mesh: Option<Retained<ProtocolObject<dyn MTLFunction>>> = descriptor.meshFunction();
let fragment: Option<Retained<ProtocolObject<dyn MTLFunction>>> = descriptor.fragmentFunction(); let fragment: Option<Retained<ProtocolObject<dyn MTLFunction>>> = descriptor.fragmentFunction();
MeshDescriptorFacts { MeshDescriptorFacts {
label: Ok(descriptor.label().map(|label| label.to_string())), label: descriptor.label().map(|label| label.to_string()),
object_function: object.map(|held| held.name().to_string()), object_function: object.map(|held| held.name().to_string()),
mesh_function: mesh.map(|held| held.name().to_string()), mesh_function: mesh.map(|held| held.name().to_string()),
fragment_function: fragment.map(|held| held.name().to_string()), fragment_function: fragment.map(|held| held.name().to_string()),
@@ -1945,7 +1945,7 @@ fn read_mesh_descriptor(
depth_attachment_pixel_format: descriptor.depthAttachmentPixelFormat().0 as u32, depth_attachment_pixel_format: descriptor.depthAttachmentPixelFormat().0 as u32,
stencil_attachment_pixel_format: descriptor.stencilAttachmentPixelFormat().0 as u32, stencil_attachment_pixel_format: descriptor.stencilAttachmentPixelFormat().0 as u32,
support_indirect_command_buffers: descriptor.supportIndirectCommandBuffers(), support_indirect_command_buffers: descriptor.supportIndirectCommandBuffers(),
binary_archives: Ok(archives.map_or(0, |held| held.len() as u64)), binary_archives: archives.map_or(0, |held| held.len() as u64),
limits: read_mesh_limits(descriptor), limits: read_mesh_limits(descriptor),
supplied: supplied.then(|| read_mesh_supplied(descriptor)), supplied: supplied.then(|| read_mesh_supplied(descriptor)),
} }
@@ -3893,7 +3893,7 @@ impl Side for MetalSide {
state.requiredThreadsPerObjectThreadgroup(), state.requiredThreadsPerObjectThreadgroup(),
), ),
required_threads_per_mesh_threadgroup: axes(state.requiredThreadsPerMeshThreadgroup()), required_threads_per_mesh_threadgroup: axes(state.requiredThreadsPerMeshThreadgroup()),
max_total_threads_per_threadgroup: Ok(state.maxTotalThreadsPerThreadgroup() as u64), max_total_threads_per_threadgroup: state.maxTotalThreadsPerThreadgroup() as u64,
})) }))
} }
@@ -38,7 +38,6 @@
//! for both (docs/API.md, accepted differences): such a state's two object-stage getters are not //! for both (docs/API.md, accepted differences): such a state's two object-stage getters are not
//! read. //! read.
use crate::case::{field, Field};
use crate::pipeline_facts::size; use crate::pipeline_facts::size;
use crate::transcript::{Node, NodeName, Observed, Value}; use crate::transcript::{Node, NodeName, Observed, Value};
@@ -166,9 +165,8 @@ pub struct MeshStateLimits {
pub required_threads_per_object_threadgroup: [u64; 3], pub required_threads_per_object_threadgroup: [u64; 3],
/// `requiredThreadsPerMeshThreadgroup`. /// `requiredThreadsPerMeshThreadgroup`.
pub required_threads_per_mesh_threadgroup: [u64; 3], pub required_threads_per_mesh_threadgroup: [u64; 3],
/// `maxTotalThreadsPerThreadgroup`, a tile threadgroup's, which a drawing state answers 0 /// `maxTotalThreadsPerThreadgroup`, which a drawing state answers 0 for.
/// for: a [`Field`] a side without tile render states refuses alone. pub max_total_threads_per_threadgroup: u64,
pub max_total_threads_per_threadgroup: Field<u64>,
} }
/// What a made compute pipeline state answers of its limit. /// What a made compute pipeline state answers of its limit.
@@ -194,58 +192,48 @@ fn optional(held: Option<u64>) -> Value {
} }
} }
impl MeshStateLimits {
/// The made state's answers as sites under `node`, the creation's.
fn with_sites(&self, node: Node) -> Node {
let value = Observed::value;
node.with(Node::leaf(
"max_total_threads_per_object_threadgroup",
value(optional(self.max_total_threads_per_object_threadgroup)),
))
.with(Node::leaf(
"max_total_threads_per_mesh_threadgroup",
value(Value::Uint(self.max_total_threads_per_mesh_threadgroup)),
))
.with(Node::leaf(
"object_thread_execution_width",
value(optional(self.object_thread_execution_width)),
))
.with(Node::leaf(
"mesh_thread_execution_width",
value(Value::Uint(self.mesh_thread_execution_width)),
))
.with(Node::leaf(
"max_total_threadgroups_per_mesh_grid",
value(Value::Uint(self.max_total_threadgroups_per_mesh_grid)),
))
.with(Node::leaf(
"required_threads_per_object_threadgroup",
value(size(&self.required_threads_per_object_threadgroup)),
))
.with(Node::leaf(
"required_threads_per_mesh_threadgroup",
value(size(&self.required_threads_per_mesh_threadgroup)),
))
.with(Node::leaf(
"max_total_threads_per_threadgroup",
field(&self.max_total_threads_per_threadgroup, |threads| {
Value::Uint(*threads)
}),
))
}
}
impl Creation<MeshStateLimits> { impl Creation<MeshStateLimits> {
/// The answer as the sites a case emits under one node, so both sides emit one shape. /// The answer as the sites a case emits under one node, so both sides emit one shape.
pub fn node(&self, name: impl Into<NodeName>) -> Node { pub fn node(&self, name: impl Into<NodeName>) -> Node {
let node = Node::branch(name, Vec::new()).with(Node::leaf( let value = Observed::value;
"refused", let mut node = Node::branch(name, Vec::new())
Observed::value(Value::Bool(self.refused)), .with(Node::leaf("refused", value(Value::Bool(self.refused))));
)); if let Some(state) = &self.state {
match &self.state { node = node
Some(state) => state.with_sites(node), .with(Node::leaf(
None => node, "max_total_threads_per_object_threadgroup",
value(optional(state.max_total_threads_per_object_threadgroup)),
))
.with(Node::leaf(
"max_total_threads_per_mesh_threadgroup",
value(Value::Uint(state.max_total_threads_per_mesh_threadgroup)),
))
.with(Node::leaf(
"object_thread_execution_width",
value(optional(state.object_thread_execution_width)),
))
.with(Node::leaf(
"mesh_thread_execution_width",
value(Value::Uint(state.mesh_thread_execution_width)),
))
.with(Node::leaf(
"max_total_threadgroups_per_mesh_grid",
value(Value::Uint(state.max_total_threadgroups_per_mesh_grid)),
))
.with(Node::leaf(
"required_threads_per_object_threadgroup",
value(size(&state.required_threads_per_object_threadgroup)),
))
.with(Node::leaf(
"required_threads_per_mesh_threadgroup",
value(size(&state.required_threads_per_mesh_threadgroup)),
))
.with(Node::leaf(
"max_total_threads_per_threadgroup",
value(Value::Uint(state.max_total_threads_per_threadgroup)),
));
} }
node
} }
} }
+1 -62
View File
@@ -52,7 +52,6 @@ pub(crate) mod fields;
mod functions; mod functions;
mod heap_sizes; mod heap_sizes;
mod managed_naming; mod managed_naming;
mod mesh;
mod render; mod render;
mod state_facts; mod state_facts;
mod states; mod states;
@@ -1737,61 +1736,6 @@ impl Side for RtSide<'_> {
self.mesh_target(width, height) self.mesh_target(width, height)
} }
fn mesh_pipeline(
&mut self,
library: Handle,
functions: &crate::case::MeshFunctions<'_>,
) -> Answer<Handle> {
self.mesh_state(library, functions, false)
}
fn mesh_pipeline_for_commands(
&mut self,
library: Handle,
functions: &crate::case::MeshFunctions<'_>,
) -> Answer<Handle> {
self.mesh_state(library, functions, true)
}
fn mesh_pass(
&mut self,
targets: &[Handle],
steps: &[crate::case::MeshStep],
) -> Answer<crate::case::PassOutcome> {
self.run_mesh_pass(targets, steps)
}
fn mesh_pipeline_limits(
&mut self,
library: Handle,
spec: &crate::pipeline_limits::MeshLimitsSpec<'_>,
) -> Answer<crate::pipeline_limits::Creation<crate::pipeline_limits::MeshStateLimits>> {
self.mesh_limits(library, spec)
}
fn mesh_descriptor_facts(
&mut self,
library: Handle,
spec: &crate::mesh_descriptors::DescriptorSpec<'_>,
) -> Answer<crate::mesh_descriptors::MeshDescriptorFacts> {
self.mesh_descriptor(library, spec)
}
/// The consumer's own: a mesh pipeline's bindings are its reflection's
/// (`reflection_is_the_consumers`).
fn mesh_pipeline_bindings(
&mut self,
_library: Handle,
_spec: &crate::case::MeshReflectionSpec<'_>,
_options: u64,
) -> Answer<crate::function_bindings::StageReflection> {
Err(reflection_is_the_consumers())
}
fn mesh_command_buffer(&mut self, commands: &[crate::case::MeshCommand]) -> Answer<Handle> {
self.mesh_commands(commands)
}
fn visible_function_table( fn visible_function_table(
&mut self, &mut self,
caller: Handle, caller: Handle,
@@ -2045,7 +1989,7 @@ mod answered {
}; };
/// Each call the side answers, with a case that reaches it. /// Each call the side answers, with a case that reaches it.
const CALLS: [(&str, &str); 25] = [ const CALLS: [(&str, &str); 20] = [
( (
"heap_buffer_size_and_align", "heap_buffer_size_and_align",
crate::cases::device_queries::HEAP_BUFFERS, crate::cases::device_queries::HEAP_BUFFERS,
@@ -2102,11 +2046,6 @@ mod answered {
"newBufferWithBytesNoCopy", "newBufferWithBytesNoCopy",
"host-page-writes-kernel-store-writable", "host-page-writes-kernel-store-writable",
), ),
("mesh_pipeline", "mesh-grid-draws"),
("mesh_pass", "mesh-grid-draws"),
("mesh_pipeline_limits", "mesh-limits-plain"),
("mesh_descriptor_facts", "mesh-descriptor-defaults"),
("mesh_pipeline_for_commands", "mesh-commands-own-state"),
]; ];
/// The calls `value` records as unavailable, wherever in it they sit. /// The calls `value` records as unavailable, wherever in it they sit.
@@ -1,294 +0,0 @@
//! The rt side's mesh render pipeline calls: a state of a case's object, mesh and fragment
//! functions over its targets, with or without `supportIndirectCommandBuffers`; one pass of a
//! case's mesh steps; what a made state answers of its limits; a mesh descriptor read back before
//! any state is made; and an indirect command buffer of mesh commands, which the runtime refuses
//! by its command types.
//!
//! The runtime takes Metal's mesh descriptor as the translator's
//! ([`rt::MeshPipelineDescriptor`]), so a descriptor is stated and read through the walk both
//! sides share ([`crate::descriptor_reads`]). The runtime keeps no label and takes no binary
//! archive, and it makes no tile render state, so those getters answer refused fields.
use super::states::refuses_as_metal;
use super::{keep, waited_for, RtSide, WAIT};
use crate::case::{
Answer, Failure, Field, Handle, MeshCommand, MeshFunctions, MeshStep, PassOutcome,
};
use crate::descriptor_reads;
use crate::mesh_descriptors::{DescriptorSpec, MeshDescriptorFacts};
use crate::pipeline_limits::{floored, Creation, MeshLimitsSpec, MeshStateLimits};
use crate::transcript::{Negative, Value};
use metal2vulkan_runtime as rt;
/// A typed error of the runtime as the failure it records.
fn of_rt(error: rt::Error) -> Failure {
Failure::of_rt(&error)
}
/// `label`: the runtime keeps none, on a descriptor or on what it makes of one.
fn label() -> Field<Option<String>> {
Err(Failure::unavailable("label"))
}
/// `binaryArchives`: the runtime takes no binary archive.
fn binary_archives() -> Field<u64> {
Err(Failure::unavailable("binaryArchives"))
}
/// `maxTotalThreadsPerThreadgroup`, a tile threadgroup's: the runtime makes no tile render state,
/// so a drawing state has no such getter.
fn tile_threads() -> Field<u64> {
Err(Failure::unavailable("maxTotalThreadsPerThreadgroup"))
}
/// The mesh family's colour format, [`crate::case::TARGET_FORMAT`].
const TARGET: rt::PixelFormat = rt::PixelFormat::RGBA32Uint;
impl RtSide<'_> {
/// The translator's mesh descriptor of the library's `mesh` function, and of `object` where
/// the case names one, every other field Metal's default.
fn mesh_stages(
&self,
library: Handle,
object: Option<&str>,
mesh: &str,
) -> Answer<rt::MeshPipelineDescriptor> {
let mut descriptor = rt::MeshPipelineDescriptor::new(self.kernel(library, mesh)?);
descriptor.object = object
.map(|object| self.kernel(library, object))
.transpose()?;
Ok(descriptor)
}
/// [`crate::case::Side::mesh_pipeline`], and with `for_commands`
/// [`crate::case::Side::mesh_pipeline_for_commands`]: the runtime's state of the functions over
/// `functions.attachments` colour attachments of [`TARGET`].
pub(super) fn mesh_state(
&mut self,
library: Handle,
functions: &MeshFunctions<'_>,
for_commands: bool,
) -> Answer<Handle> {
let mut descriptor = self.mesh_stages(library, functions.object, functions.mesh)?;
descriptor.fragment = Some(self.kernel(library, functions.fragment)?);
for at in 0..functions.attachments as usize {
let slot = (descriptor.color_attachments.get_mut(at))
.ok_or_else(|| Failure::named("NoSuchAttachment", format!("color {at}")))?;
*slot = Some(rt::ColorAttachmentDescriptor::new(TARGET));
}
descriptor.support_indirect_command_buffers = for_commands;
let on = self.on;
let state = (on.device)
.new_mesh_render_pipeline_state(&descriptor, |samplers| Ok(on.sampler_ids(samplers)))
.map_err(|error| on.failure(&error))?;
Ok(keep(&mut self.render_pipelines, state))
}
/// [`crate::case::Side::mesh_pass`]: one render pass over `targets`, each cleared to zero and
/// stored, every step encoded whatever an earlier one answered (a refused call leaves the
/// encoder as it was), then the command buffer committed and waited for within [`WAIT`].
pub(super) fn run_mesh_pass(
&mut self,
targets: &[Handle],
steps: &[MeshStep],
) -> Answer<PassOutcome> {
let mut pass = rt::RenderPassDescriptor::default();
for (at, &target) in targets.iter().enumerate() {
let texture = self.held_texture(target)?.clone();
let attachment = (pass.color_attachments.get_mut(at))
.ok_or_else(|| Failure::named("NoSuchAttachment", format!("color {at}")))?;
attachment.texture = Some(texture);
attachment.load_action = rt::LoadAction::Clear;
attachment.clear_color = rt::ClearColor::new(0.0, 0.0, 0.0, 0.0);
attachment.store_action = rt::StoreAction::Store;
}
let command_buffer = self.queue()?.command_buffer().map_err(of_rt)?;
let mut encoder = (command_buffer.render_command_encoder(&pass)).map_err(of_rt)?;
let refused: Vec<Option<Failure>> = (steps.iter())
.map(|step| self.mesh_step(&mut encoder, step).err())
.collect();
encoder.end_encoding();
command_buffer.commit().map_err(of_rt)?;
for (step, refused) in steps.iter().zip(&refused) {
if let (MeshStep::Pipeline(state), None) = (step, refused) {
self.drawn.insert(state.0 as usize);
}
}
let Some(word) = waited_for(&command_buffer, WAIT) else {
return Ok(PassOutcome {
refused,
status: Value::Nothing(Negative::NeverReturned),
error: None,
});
};
Ok(PassOutcome {
refused,
status: Value::unit_variant(word),
error: (command_buffer.error()).map(|error| Value::unit_variant(format!("{error:?}"))),
})
}
/// One step of a mesh pass on `encoder`.
fn mesh_step(&self, encoder: &mut rt::RenderCommandEncoder, step: &MeshStep) -> Answer<()> {
match step {
MeshStep::Pipeline(state) => {
let state = (self.render_pipelines.get(state.0 as usize)).ok_or_else(|| {
Failure::named("NoSuchHandle", format!("mesh pipeline {}", state.0))
})?;
encoder.set_render_pipeline_state(state).map_err(of_rt)
}
MeshStep::ObjectBuffer {
buffer,
offset,
index,
} => (encoder.set_object_buffer(Some(self.held(*buffer)?), *offset, *index))
.map_err(of_rt),
MeshStep::ObjectBytes { bytes, index } => {
encoder.set_object_bytes(bytes, *index).map_err(of_rt)
}
MeshStep::MeshBuffer {
buffer,
offset,
index,
} => {
(encoder.set_mesh_buffer(Some(self.held(*buffer)?), *offset, *index)).map_err(of_rt)
}
MeshStep::FragmentBuffer {
buffer,
offset,
index,
} => (encoder.set_fragment_buffer(Some(self.held(*buffer)?), *offset, *index))
.map_err(of_rt),
MeshStep::DrawThreadgroups {
groups,
object,
mesh,
} => (encoder.draw_mesh_threadgroups(*groups, *object, *mesh)).map_err(of_rt),
MeshStep::DrawThreads {
threads,
object,
mesh,
} => (encoder.draw_mesh_threads(*threads, *object, *mesh)).map_err(of_rt),
MeshStep::DrawIndirect {
buffer,
offset,
object,
mesh,
} => (encoder.draw_mesh_threadgroups_indirect(
self.held(*buffer)?,
*offset,
*object,
*mesh,
))
.map_err(of_rt),
// The scope, the stages and the buffers only narrow what Metal orders: the runtime's
// barrier, which serves both of Metal's calls, orders every access of the encoder's
// draws so far before its later ones.
MeshStep::BarrierScope { .. } => encoder.memory_barrier().map_err(of_rt),
MeshStep::BarrierResources { buffers, .. } => {
for &buffer in buffers {
self.held(buffer)?;
}
encoder.memory_barrier().map_err(of_rt)
}
}
}
/// [`crate::case::Side::mesh_pipeline_limits`]: the runtime's state of the descriptor,
/// rasterization disabled, and what it answers of its limits, or Metal's refusal where the
/// runtime's error is one.
pub(super) fn mesh_limits(
&mut self,
library: Handle,
spec: &MeshLimitsSpec<'_>,
) -> Answer<Creation<MeshStateLimits>> {
let mut descriptor = self.mesh_stages(library, spec.object, spec.mesh)?;
descriptor.rasterization_enabled = false;
descriptor.max_vertex_amplification_count = spec.amplification;
let stated = |held: u32| (held != 0).then_some(held);
descriptor.max_total_threads_per_object_threadgroup = stated(spec.max_object);
descriptor.max_total_threads_per_mesh_threadgroup = stated(spec.max_mesh);
descriptor.max_total_threadgroups_per_mesh_grid = stated(spec.max_grid);
descriptor.payload_memory_length = stated(spec.payload);
let on = self.on;
let state = match (on.device)
.new_mesh_render_pipeline_state(&descriptor, |samplers| Ok(on.sampler_ids(samplers)))
{
Ok(state) => state,
Err(error) if refuses_as_metal(&error) => return Ok(Creation::refused()),
Err(error) => return Err(on.failure(&error)),
};
let object = spec.object.is_some();
Ok(Creation::made(MeshStateLimits {
max_total_threads_per_object_threadgroup: object
.then(|| floored(u64::from(state.max_total_threads_per_object_threadgroup()))),
max_total_threads_per_mesh_threadgroup: floored(u64::from(
state.max_total_threads_per_mesh_threadgroup(),
)),
object_thread_execution_width: object
.then(|| u64::from(state.object_thread_execution_width())),
mesh_thread_execution_width: u64::from(state.mesh_thread_execution_width()),
max_total_threadgroups_per_mesh_grid: u64::from(
state.max_total_threadgroups_per_mesh_grid(),
),
required_threads_per_object_threadgroup: state
.required_threads_per_object_threadgroup()
.map(u64::from),
required_threads_per_mesh_threadgroup: state
.required_threads_per_mesh_threadgroup()
.map(u64::from),
max_total_threads_per_threadgroup: tile_threads(),
}))
}
/// [`crate::case::Side::mesh_descriptor_facts`]: the translator's descriptor of the library's
/// stages, stated and reset as the spec's shape says, then read. The runtime has no mutable
/// descriptor object, so Metal's `init` is `MeshPipelineDescriptor::new` and its `reset` is the
/// same call again, the stages set again after it, as the Metal side sets them.
pub(super) fn mesh_descriptor(
&self,
library: Handle,
spec: &DescriptorSpec<'_>,
) -> Answer<MeshDescriptorFacts> {
let fresh = || -> Answer<rt::MeshPipelineDescriptor> {
let mut descriptor = self.mesh_stages(library, spec.object, spec.mesh)?;
descriptor.fragment = Some(self.kernel(library, spec.fragment)?);
Ok(descriptor)
};
let mut descriptor = fresh()?;
if spec.shape.sets() {
descriptor_reads::state_mesh(&mut descriptor);
}
if spec.shape.resets() {
descriptor = fresh()?;
}
Ok(descriptor_reads::read_mesh(
&descriptor,
label(),
binary_archives(),
!spec.shape.resets(),
))
}
/// [`crate::case::Side::mesh_command_buffer`]: the runtime's indirect command buffer of both
/// mesh draw kinds, each command setting its own state and buffers, which the runtime refuses
/// by its command types before it makes anything. Were one made, its commands could not be
/// encoded: the runtime encodes no command on the CPU.
pub(super) fn mesh_commands(&mut self, commands: &[MeshCommand]) -> Answer<Handle> {
let mut descriptor = rt::IndirectCommandBufferDescriptor::new();
descriptor.command_types = rt::IndirectCommandType::DRAW_MESH_THREADGROUPS
| rt::IndirectCommandType::DRAW_MESH_THREADS;
descriptor.inherit_pipeline_state = false;
descriptor.inherit_buffers = false;
let count = u32::try_from(commands.len().max(1))
.map_err(|_| Failure::named("TooManyCommands", format!("{}", commands.len())))?;
match self
.on
.device
.new_indirect_command_buffer(&descriptor, count)
{
Err(error) => Err(self.on.failure(&error)),
Ok(_) => Err(Failure::unavailable("indirectRenderCommandAtIndex:")),
}
}
}
@@ -20,7 +20,7 @@ fn of_rt(error: rt::Error) -> crate::case::Failure {
/// Whether the runtime's error is Metal's own refusal of the descriptor: its validation's /// Whether the runtime's error is Metal's own refusal of the descriptor: its validation's
/// (`Refused`) or the translator's refusal of a descriptor Metal refuses (`InvalidDescriptor`). /// (`Refused`) or the translator's refusal of a descriptor Metal refuses (`InvalidDescriptor`).
pub(super) fn refuses_as_metal(error: &rt::Error) -> bool { fn refuses_as_metal(error: &rt::Error) -> bool {
matches!( matches!(
error, error,
rt::Error::Refused(_) rt::Error::Refused(_)
+3 -16
View File
@@ -44,11 +44,9 @@ pub fn selected(names: &[String]) -> Result<Vec<Box<dyn Case>>, String> {
/// venue's surfaces took, and a case whose whole grids ran an observing kernel's /// venue's surfaces took, and a case whose whole grids ran an observing kernel's
/// partial-threadgroups variant prints how many (`Metrics::partial_variant_whole_grids`), and a /// partial-threadgroups variant prints how many (`Metrics::partial_variant_whole_grids`), and a
/// case whose dispatches and draws pushed a storage texture's level fields prints how many /// case whose dispatches and draws pushed a storage texture's level fields prints how many
/// (`Metrics::level_field_commands`), and a case that drew mesh draws prints how many of each form /// (`Metrics::level_field_commands`), and each pass prints its dispatches by the form their kernels
/// (`Metrics::mesh_draws_launched`, `Metrics::mesh_object_grids_whole`, /// reached their buffers in (`Metrics::bound_dispatches`, `Metrics::address_dispatches`): nothing
/// `Metrics::mesh_object_grids_in_pieces`), and each pass prints its dispatches by the form their /// in a verdict reads any of them.
/// kernels reached their buffers in (`Metrics::bound_dispatches`, `Metrics::address_dispatches`):
/// nothing in a verdict reads any of them.
pub fn replay_rt_on_under( pub fn replay_rt_on_under(
venues: Venues, venues: Venues,
cases: &[Box<dyn Case>], cases: &[Box<dyn Case>],
@@ -82,17 +80,6 @@ pub fn replay_rt_on_under(
device.venue().device device.venue().device
); );
} }
let launched = after.mesh_draws_launched - before.mesh_draws_launched;
let grids = after.mesh_object_grids_whole - before.mesh_object_grids_whole;
let pieces = after.mesh_object_grids_in_pieces - before.mesh_object_grids_in_pieces;
if launched + grids + pieces > 0 {
println!(
"mesh forms: {} on {}: {launched} launched, {grids} object grids whole, \
{pieces} in pieces",
case.name(),
device.venue().device
);
}
let levels = after.level_field_commands - before.level_field_commands; let levels = after.level_field_commands - before.level_field_commands;
if levels > 0 { if levels > 0 {
println!( println!(
+139 -398
View File
@@ -219,13 +219,11 @@ four histograms of each command buffer's stages, in 23 power-of-two buckets from
2^22 us (about 4.19 s) or more, filled from the times the command buffer already reports: commit 2^22 us (about 4.19 s) or more, filled from the times the command buffer already reports: commit
to scheduled (`commit_to_scheduled`, counted as it is scheduled), scheduled to GPU start, the GPU to scheduled (`commit_to_scheduled`, counted as it is scheduled), scheduled to GPU start, the GPU
run, and GPU end to the host time its handlers begin (counted as it retires, for one that run, and GPU end to the host time its handlers begin (counted as it retires, for one that
completes with GPU times, but not one with nothing for the GPU whose submission is a Managed completes with GPU times), each beside its spans' sum in nanoseconds (`commit_to_scheduled_nanos`
buffer's copy-in, which is the runtime's own GPU run), each beside its spans' sum in nanoseconds and the three like it); of scheduled to GPU start, the part under the GPU spans of other command
(`commit_to_scheduled_nanos` and the three like it); of scheduled to GPU start, the part under the buffers retired before it, the runtime's own included (`scheduled_to_gpu_start_behind_nanos`); GPU
GPU spans of other command buffers retired before it, the runtime's own included end to handlers split at the completion thread's six steps, for all and for those of 1,024 us or
(`scheduled_to_gpu_start_behind_nanos`); GPU end to handlers split at the completion thread's six more (`gpu_end_to_handler_steps_nanos`, `gpu_end_to_handler_tail` and its steps); the clock
steps, for all and for those of 1,024 us or more (`gpu_end_to_handler_steps_nanos`,
`gpu_end_to_handler_tail` and its steps); the clock
calibrations and their calls' time (`calibrations`, `calibration_nanos`); the segments the submit thread held for an event's value that neither calibrations and their calls' time (`calibrations`, `calibration_nanos`); the segments the submit thread held for an event's value that neither
the host had set nor a submitted signal promised, by the length of each hold (`event_holds`, in the host had set nor a submitted signal promised, by the length of each hold (`event_holds`, in
the same buckets); the groups a queue held without room that went once a completion left room the same buckets); the groups a queue held without room that went once a completion left room
@@ -891,10 +889,7 @@ wrote, are what the image holds after it (the save runs on the GPU after the sub
queue touches. Metal's make touches no bytes, and a CPU write to a Shared buffer that no pending GPU queue touches. Metal's make touches no bytes, and a CPU write to a Shared buffer that no pending GPU
command uses is defined; a save and write-back at a later submission would let one thread's commit command uses is defined; a save and write-back at a later submission would let one thread's commit
revert another thread's write. The make waits for the GPU work already submitted, so it is refused revert another thread's write. The make waits for the GPU work already submitted, so it is refused
in a scheduled handler, which runs on the submit thread (`Refusal::InScheduledHandler`). Its wait in a scheduled handler, which runs on the submit thread (`Refusal::InScheduledHandler`). The two
for the batch returns only once the batch completed or the device is lost: a `vkWaitSemaphores` that
fails for want of memory or with `VK_ERROR_UNKNOWN` leaves the batch pending, so the call is made
again, and no write-back runs after the make returns, with an error or without. The two
copies count in `Metrics::over_copies_host_memory_restore` (`OverCause::HostMemoryRestore`, a cause copies count in `Metrics::over_copies_host_memory_restore` (`OverCause::HostMemoryRestore`, a cause
of their own, so that `over_copies_host_memory` counts a copied texture's copies at its uses alone), of their own, so that `over_copies_host_memory` counts a copied texture's copies at its uses alone),
each of the bytes bound under the image (and in `over_copies`, `over_copies_imported` and each of the bytes bound under the image (and in `over_copies`, `over_copies_imported` and
@@ -1224,16 +1219,14 @@ the descriptor's width and height, on a dedicated import of its handle, counted
as Direct3D 11 copies any texture of default usage; sampled for `D3D11_BIND_SHADER_RESOURCE`, as Direct3D 11 copies any texture of default usage; sampled for `D3D11_BIND_SHADER_RESOURCE`,
rendered for `D3D11_BIND_RENDER_TARGET`, storage for `D3D11_BIND_UNORDERED_ACCESS`; each where rendered for `D3D11_BIND_RENDER_TARGET`, storage for `D3D11_BIND_UNORDERED_ACCESS`; each where
the descriptor's format holds it and the import query the descriptor's format holds it and the import query
(`vkGetPhysicalDeviceImageFormatProperties2`) offers it: the handle importable and among the (`vkGetPhysicalDeviceImageFormatProperties2`) offers it. Vulkan states no rule for an image over
image's compatible handle types (`VUID-VkImageCreateInfo-pNext-00990`). Vulkan states no rule for an image over
memory another API made with other parameters: its rule for an import of Vulkan's own export is memory another API made with other parameters: its rule for an import of Vulkan's own export is
the same image (`VUID-VkMemoryDedicatedAllocateInfo-image-01876`), and its memory aliasing the same image (`VUID-VkMemoryDedicatedAllocateInfo-image-01876`), and its memory aliasing
promises a consistent reading to images of the same creation parameters. A texture whose uses promises a consistent reading to images of the same creation parameters. A texture whose uses
ask more (`ShaderWrite` on a texture made without `D3D11_BIND_UNORDERED_ACCESS`) is ask more (`ShaderWrite` on a texture made without `D3D11_BIND_UNORDERED_ACCESS`) is
`Gap::SurfaceUsage`. So the image never takes the attachment feedback loop's usage, which Direct3D `Gap::SurfaceUsage`. The one usage beside them is the attachment feedback loop's, which Direct3D
11's description has no counterpart for: a draw that reads a plane as an attachment of its own 11's description has no counterpart for: taken where the descriptor's texture is a render target
pass reads it through a copy into the plane's shadow on every device, with the loop or without it a draw may read in its own pass. The image is mutable where it lists more than its own format, and
(Known gaps of render encoders). The image is mutable where it lists more than its own format, and
it lists at most two more, the two places it asks beyond the texture Direct3D 11 made: the it lists at most two more, the two places it asks beyond the texture Direct3D 11 made: the
descriptor's format where it differs (a chroma plane of `R16Uint` under an `RG8Unorm` texture, the descriptor's format where it differs (a chroma plane of `R16Uint` under an `RG8Unorm` texture, the
same bytes per texel in Metal's same view class), and the descriptor's sRGB sibling, which a guest same bytes per texel in Metal's same view class), and the descriptor's sRGB sibling, which a guest
@@ -1641,15 +1634,15 @@ exported block, an exported surface in either form, and a Direct3D 11 import.
texture over any import), all 13,613 such copies (228.6 MiB) were of textures over imported texture over any import), all 13,613 such copies (228.6 MiB) were of textures over imported
memory, 1.05 copies and 16 KB a frame on average over 13,005 frames and 78 copies in the worst memory, 1.05 copies and 16 KB a frame on average over 13,005 frames and 78 copies in the worst
one; no texture over a block of the runtime's own was copied. one; no texture over a block of the runtime's own was copied.
- A driver may hold a submit of the process for the length of a free (the NVIDIA rows below). rt - On the NVIDIA cards we measured in Thunderbolt enclosures, freeing host-visible memory takes
frees one idle allocation at a time, at its idle age, whatever the queues are doing. about 1.1 ms per MiB and holds any submit of the same process for its length; on an internal
`Metrics::allocations_freed` counts the frees, `Metrics::submissions_during_frees` the submit NVIDIA card the same free takes about 0.5 ms per 16 MiB. rt frees one idle allocation at a time,
calls that met one of the block-maker thread's frees, and at its idle age, whatever the queues are doing. `Metrics::allocations_freed` counts the frees,
`Metrics::submit_call_nanos_during_frees` their time. `Metrics::submissions_during_frees` the submit calls that met one of the block-maker thread's
- On the NVIDIA cards measured (an RTX 3090 under NVIDIA's Linux driver 620.70.06, and an RTX 2080), frees, and `Metrics::submit_call_nanos_during_frees` their time.
the driver holds a submit made while another thread is inside `vkAllocateMemory` or `vkFreeMemory` - NVIDIA's Linux driver holds a submit made while another thread is inside `vkAllocateMemory` or
until that call returns, device-local memory included, and calls made back to back hold it through `vkFreeMemory` until that call returns, device-local memory included, and calls made back to back
all of them. So as each of its allocations and frees returns, the block-maker hold it through all of them. So as each of its allocations and frees returns, the block-maker
thread marks the `vkQueueSubmit2` calls of rt's inside the driver then, and starts its next one thread marks the `vkQueueSubmit2` calls of rt's inside the driver then, and starts its next one
only once all of them have returned; with none left inside it goes straight on, and what it made only once all of them have returned; with none left inside it goes straight on, and what it made
is handed on as its call returns. A submit waits out at most one of its calls, the one it met. Its is handed on as its call returns. A submit waits out at most one of its calls, the one it met. Its
@@ -1770,19 +1763,19 @@ exported block, an exported surface in either form, and a Direct3D 11 import.
Shaders reach textures and samplers by index (`docs/RESOURCE-ID.md`). Every pipeline takes set 1, Shaders reach textures and samplers by index (`docs/RESOURCE-ID.md`). Every pipeline takes set 1,
one descriptor set the device makes at creation, of seven arrays whose element `i` is the object one descriptor set the device makes at creation, of seven arrays whose element `i` is the object
whose `gpuResourceID` holds index `i`: 65,536 sampled textures and then 65,536 second elements whose `gpuResourceID` holds index `i`: 65,536 sampled textures (binding 0), 65,536 storage
(binding 0), 65,536 storage textures and then 65,536 level elements (binding 1), 8,000 samplers of textures and then 65,536 level elements (binding 1), 8,000 samplers of each use, plain, depth comparison and integer texture
each use, plain, depth comparison and integer texture (bindings 2, 3 and 4), and 65,536 uniform and (bindings 2, 3 and 4), and 65,536 uniform and 65,536 storage texel buffers, the texture buffers
65,536 storage texel buffers, the texture buffers (bindings 5 and 6). A texture's index is the same element of both (bindings 5 and 6). A texture's index is the same element of both texture arrays: one with a
texture arrays: one with a storage view takes both, any other the sampled one alone, and its storage storage view takes both, any other the sampled one alone, and its storage element stays null. A
element stays null. A texture buffer's index is the same element of both texel-buffer arrays: the texture buffer's index is the same element of both texel-buffer arrays: the uniform one where
uniform one where shaders read it, the storage one where they write it, the other null; its texture shaders read it, the storage one where they write it, the other null; its texture elements stay
elements stay null, as a texture's texel-buffer elements do. Every binding is partially bound, null, as a texture's texel-buffer elements do. Every binding is partially bound, updated after bind and
updated after bind and updated while unused elements are pending, so an object's element is written updated while unused elements are pending, so an object's element is written once, as it is
once, as it is made, with no lock, and never rewritten for layouts. made, with no lock, and never rewritten for layouts.
- Binding 0's elements 65,536 to 131,071 are second elements: element `i + 65,536` is texture - Where the device reads attachments (Floor, Attachment reads), binding 0 holds 131,072
`i`'s second element, which a draw pushes in place of elements: element `i + 65,536` is texture `i`'s second element, which a draw pushes in place of
the texture's own index while it reads an attachment of its pass through the texture. Through the texture's own index while it reads an attachment of its pass through the texture. Through
the attachment feedback loop it is the texture's view in the feedback layout, written with the attachment feedback loop it is the texture's view in the feedback layout, written with
element `i` for a texture whose image a pass may move there (a colour render target not in place element `i` for a texture whose image a pass may move there (a colour render target not in place
@@ -1891,7 +1884,7 @@ once, as it is made, with no lock, and never rewritten for layouts.
the usage. `TextureUsage` with no bits is Metal's unknown usage: shader read and write, render the usage. `TextureUsage` with no bits is Metal's unknown usage: shader read and write, render
target and pixel-format view. target and pixel-format view.
- The image's usage is the descriptor's plus transfer source and destination, and, for a colour - The image's usage is the descriptor's plus transfer source and destination, and, for a colour
render target, sampled, with the feedback usage where it has render target where the device reads attachments, sampled, with the feedback usage where it has
the attachment feedback loop (Render encoders). Its home layout is general where it has a storage the attachment feedback loop (Render encoders). Its home layout is general where it has a storage
element, shader-read-only where shaders only read it, and the attachment layout where only render element, shader-read-only where shaders only read it, and the attachment layout where only render
passes use it. Its elements of set 1 are written before the call returns, with that layout, and passes use it. Its elements of set 1 are written before the call returns, with that layout, and
@@ -1907,10 +1900,7 @@ once, as it is made, with no lock, and never rewritten for layouts.
first): its sRGB sibling whatever its usage, as Metal views a texture as its sibling without first): its sRGB sibling whatever its usage, as Metal views a texture as its sibling without
`PixelFormatView` usage, and with that usage every uncompressed colour format of the same bytes `PixelFormatView` usage, and with that usage every uncompressed colour format of the same bytes
a texel. A texture of no such format is not mutable. A view of another format takes the image's a texel. A texture of no such format is not mutable. A view of another format takes the image's
usage that its format's features hold (`VkImageViewUsageCreateInfo`), and a pass's attachment usage that its format's features hold (`VkImageViewUsageCreateInfo`). A texture made for shader
view of it the attachment usages of those, with, where the image has the feedback usage, the
feedback and sampled usages, which Vulkan asks of an attachment in the feedback layout
(`VUID-VkRenderingAttachmentInfo-imageView-10780`). A texture made for shader
writes whose own format the device does not store, where a format it lists does (an 8-bit sRGB writes whose own format the device does not store, where a format it lists does (an 8-bit sRGB
texture and its unorm sibling), takes the storage usage for those views texture and its unorm sibling), takes the storage usage for those views
(`VK_IMAGE_CREATE_EXTENDED_USAGE_BIT`), where the device's image format query makes that image (`VK_IMAGE_CREATE_EXTENDED_USAGE_BIT`), where the device's image format query makes that image
@@ -1936,17 +1926,9 @@ once, as it is made, with no lock, and never rewritten for layouts.
- A format is made where the translator's format table maps it for the usage on the device - A format is made where the translator's format table maps it for the usage on the device
(`vk_format`) to the format itself or to one whose view gives Metal's values (a swizzled or (`vk_format`) to the format itself or to one whose view gives Metal's values (a swizzled or
rotated view, alpha held in red, an RGBX format, a depth or stencil aspect of a combined rotated view, alpha held in red, an RGBX format, a depth or stencil aspect of a combined
format), and the device's image format query takes the image. `BGR10_XR` and `BGRA10_XR` are format), and the device's image format query takes the image. Elsewhere it is
made in the UNORM format of their bits (`A2R10G10B10_UNORM_PACK32`, `R16G16B16A16_UNORM`) for `Gap::TextureFormat`: the shaders of the identity domains read a texture through its view alone,
shader reads, whose codes every identity function's `float` sample, gather and read maps to so a format whose texels the shader converts (extended range, bfloat, YCbCr, decoded,
Metal's values where the texture's word names them, and for rendering: a fragment function
writes the codes Metal stores, a pass clears to them and resolves them, and a blend whose source
the function can correct is Vulkan's blend of the codes (docs/API.md). On a device whose format
query lacks that format for the usage the texture is `Gap::TextureFormat`, and one made for
shader writes has no storage element (below). Elsewhere it is `Gap::TextureFormat`: the shaders of the
identity domains read a texture through its view alone, so another format whose texels the
shader converts (the
extended-range `_sRGB` and two-plane formats, the padded 10-bit ones, bfloat, YCbCr, decoded,
copies-only, 24-bit depth held as 32-bit float) is not made. Past the query's extent, layers or copies-only, 24-bit depth held as 32-bit float) is not made. Past the query's extent, layers or
sample counts it is `Limit::TextureSize` or `Limit::TextureSamples`. sample counts it is `Limit::TextureSize` or `Limit::TextureSamples`.
- Refused as Metal refuses each descriptor (`Refusal::TextureZeroExtent`, - Refused as Metal refuses each descriptor (`Refusal::TextureZeroExtent`,
@@ -2380,42 +2362,6 @@ once, as it is made, with no lock, and never rewritten for layouts.
### Known gaps of textures ### Known gaps of textures
- Every `float` or `half` sample, gather and read of a sampled colour image maps its lanes as
`BGR10_XR` and `BGRA10_XR` codes and selects the mapped lanes where its texture's word names one
of them (docs/API.md), with no branch: on a texture of any other format the read pays the map's
arithmetic and the select, and a read the device's robustness bounds pays its in-range test.
In the compute harness's GPU time, against the form that branched on the word, alternated in one
run (medians of 4 rounds' p50s), `sampling`, `constexpr_sampling` and `texture_read` took +0.3%,
+2.7% and +0.8% on an RX 7900 XTX (RADV, Mesa 26.2.6, Linux), +0.5%, +1.3% and -0.2% on an
Iris Xe (ANV, Mesa 26.2.6, Linux), and +0.1%, +0.8% and 0.0% on an RTX 3090 (NVIDIA 620.70.06,
Linux).
These were measured before a sample's difference `w - 384` was kept uncontracted, which costs
a device that would fuse it into the product before it one operation a sample.
- A function with many `float` samples pays that map at each: one guest fragment function of 318
of them is first created, with every driver cache off, in 23 s on KosmicKrisp (Mesa 26.3.1, an
Apple M3 Max, macOS 27.0.1; two runs) and 9.2 s on ANV (Mesa 26.2.6, an Iris Xe, Linux), where
the same function without the map took 14 to 18 s and 4.0 s. Both are past
the 5 s creation ceiling the corpus tools check, as the function was without the map.
- A sample of a `BGR10_XR` or `BGRA10_XR` texture past its edge through a sampler's
`ClampToBorderColor` or `ClampToZero` reads the device's border colour as a code (opaque white
as `1.2529`, `BGRA10_XR`'s `1.2549`; black as `-0.7529`) where Metal reads 0 or 1, and a linear
sample across the edge blends toward it. A sample of a `BGRA10_XR` texel whose fields'
low 6 bits, which Metal neither reads nor writes, hold ones (bytes a CPU copy or a blit wrote)
filters them in, within `63/64` of a code step (`1 / 510`) of Metal's.
- A blended `BGR10_XR` or `BGRA10_XR` attachment blends its codes in the device's precision,
rounding to the field at every draw, where Metal's tile blends `half` values through the pass:
a channel stores Metal's code or one beside it a draw, and a `BGRA10_XR` field's six low bits
hold the fraction (`PrecisionNote::ExtendedRangeBlend`, docs/API.md). Where the blend's corrected
source term can leave the code range (an addition with a negative source; premultiplied
source-over with a source below `-0.7529` times its alpha), Vulkan clamps it, and a channel
stores a code up to 386 from Metal's (`PrecisionNote::ExtendedRangeBlendWindow`). Trigger: a
kept stream or a walk in which a pipeline carrying `ExtendedRangeBlendWindow` blends an
extended-range target and a picture differs from Metal's; the exact form, an ordered read of
the attachment where the device has the pixel interlock, then goes back to the planner. A blend
whose factors read the destination's colour, `BGRA10_XR`'s destination alpha, the blend colour
or a second output of the function's own, or a reverse subtraction, is refused
(`NotImplemented(Format)`); a blend whose destination factor reads the source's colour or alpha
reads it from a second output, which needs dual-source blending at attachment 0.
- A texture buffer with a swizzle other than each channel's own is `Gap::TextureBufferSwizzle`: - A texture buffer with a swizzle other than each channel's own is `Gap::TextureBufferSwizzle`:
Metal applies it to the reads, and neither a buffer view nor a `gpuResourceID` carries one. Metal applies it to the reads, and neither a buffer view nor a `gpuResourceID` carries one.
- A view of a texture buffer (`newTextureViewWithPixelFormat:` and its kin) is `Gap::TextureView` - A view of a texture buffer (`newTextureViewWithPixelFormat:` and its kin) is `Gap::TextureView`
@@ -2462,13 +2408,6 @@ once, as it is made, with no lock, and never rewritten for layouts.
view to take: the translator refuses, on a device that holds some format as words, a function view to take: the translator refuses, on a device that holds some format as words, a function
that reads an sRGB texture buffer's codes or writes fewer than four lanes; MSL reaches that reads an sRGB texture buffer's codes or writes fewer than four lanes; MSL reaches
neither. neither.
- A draw or dispatch whose function reaches a texture buffer through an argument buffer runs the
words twin where a texture buffer held as words lives on the device when the draw or dispatch is
recorded (`Gauges::word_texture_buffers`). On a device that holds some format as words, a texture
buffer held as words that is made after such a draw or dispatch is recorded and before it runs,
and that the draw or dispatch reaches through an argument buffer made resident by `use_heap` or
by a residency set, is accessed by the plain pipeline, which takes its `R32_UINT` view as the
format's own: the values it reads and writes are not Metal's.
- `replace_region` and `get_bytes` of a texture without named bytes go through the staging region: - `replace_region` and `get_bytes` of a texture without named bytes go through the staging region:
a copy Metal does not make, counted in `Metrics::bytes_copied`. a copy Metal does not make, counted in `Metrics::bytes_copied`.
- A blit copy between textures of a compressed region of whole blocks that ends inside one - A blit copy between textures of a compressed region of whole blocks that ends inside one
@@ -2784,55 +2723,13 @@ once, as it is made, with no lock, and never rewritten for layouts.
- A drawable's texture (see "Presenting") has no view of another pixel format - A drawable's texture (see "Presenting") has no view of another pixel format
(`Gap::TextureView`), and a draw that reads it as an attachment of its own pass is `Gap::Draw` (`Gap::TextureView`), and a draw that reads it as an attachment of its own pass is `Gap::Draw`
of `AttachmentRead`: the swapchain's image lists no other format and has no feedback usage. of `AttachmentRead`: the swapchain's image lists no other format and has no feedback usage.
- A texture of Metal's 4:2:2 chroma-pair formats, `GBGR422` and `BGRG422`, is held as its bytes, - A texture of Metal's 4:2:2 chroma-pair formats, `GBGR422` and `BGRG422`, is
an `R8G8_UNORM` image at its full width, since Vulkan's 4:2:2 formats (`G8B8G8R8_422_UNORM`, `Gap::TextureFormat` at every make and at `heap_texture_size_and_align`. Vulkan's 4:2:2 formats
`B8G8R8G8_422_UNORM`) are viewed only through a sampler Y′CbCr conversion, whose chroma (`G8B8G8R8_422_UNORM`, `B8G8R8G8_422_UNORM`) are viewed only through a sampler Y′CbCr
reconstruction is the implementation's. Only a function lowered for the texture reads its texels conversion, whose chroma reconstruction is the implementation's, so the translator's format
as Metal's (`LoweringInputs::chroma_pairs`, `LoweringInputs::chroma_handles`): a draw or table holds these two as a decoded `RGBA8Unorm` twin, which is not a form the runtime makes (a
dispatch that binds one at a texture slot its functions read, or that runs a function that may format held otherwise than through its view, above). The conformance cases `chroma_pairs` and
reach a `float` colour texture through a handle while one lives on the device `heap-sizes-422` record the refusal on every venue (`known-gaps-rt.tsv`).
(`Gauges::chroma_textures`), runs the state's content lowered for it. That content is made at
the first such draw or dispatch, a translation and its pipelines' compiles on the encoding thread
(`Metrics::chroma_contents`, within `Metrics::translations_at_encode`), kept in the device's map
of contents, and run by every such draw or dispatch (`Metrics::chroma_launches`); a state never
used with such a texture makes none, and its own module is the one it was. The content's make
is the translator's bounded lowering, as a state's is; on an RTX 3090 it took 4.7 ms.
- The first draw or dispatch that binds a 4:2:2 texture at a state's slot makes that state's
content and waits for it, where Metal makes none. On a Radeon 780M (RADV, Mesa 26.2.6), with the
driver's shader cache empty and then warm, a fragment content that decodes 40 sample sites in
line took 251 to 256 ms cold and 0.4 ms warm to create, after a 94 to 97 ms translation, where
the state's own pipeline took 78 to 83 ms cold; one sample site took 4.0 ms cold and 0.1 ms
warm. A camera preview's first open on that card, with the driver's shader cache empty, held
its frames for about a second (989 ms at the 99th percentile): its content, whose fragment
decodes 41 sample sites in line, took 111 ms to translate and its pipeline 870 ms to create. A
second open in the same session waited for nothing, as the device keeps the content.
- The content's read, nearest sample and gather of the texture are Metal's values exactly. A
decoded texel reads its own pair and the pair beside it, four fetches, and the two taps of a
footprint row share six, so a linear sample or a gather reads twelve texels where the device's
own access reads four, and a bicubic sample sixty-four. A sample through a constexpr sampler
holds its filter's decode alone; through any other sampler it holds the linear and the nearest
decode behind a branch on the sampler's filter, sixteen fetches. A linear sample through such a
sampler at each texel of a 1920 by 1080 frame took about 91 µs of an RTX 3090's time, 1.12 times
the 81 µs of the same kernel over an `RGBA8Unorm` texture of that size. Every tap is clamped to
the edge, whatever the sampler's address modes: Metal's `MTLPixelFormat.h` says of both formats
"When sampling, ClampToEdge is the only usable wrap mode". In a content lowered for handles,
each read, sample and gather through a handle tests whether its texture is such a texture; a
state whose functions reach textures through handles makes that content at its first draw or
dispatch while one lives on the device; in a consumer's session in which a camera preview opened,
0 such makes were seen. A linear or bicubic sample carries
`PrecisionNote::BicubicFilterArithmetic`, which the texture states as its static note
(`Texture::precision_note`). Shader-write and render-target usage, a swizzle, and a function
compiled outside the runtime that would read such a texture are `Gap::ChromaPairsUse`; a type
other than 2D, an odd width, more than one level and a view are `Refusal::ChromaPairs`, as Metal
refuses them. A copy between a buffer and such a texture of more than one row whose buffer rows
lie closer together than the region's rows are long, which Metal takes, is `Gap::ChromaPairsUse`
of `CloseRows`: one Vulkan copy region takes no row stride below its width, and one region a
row, each at its row's own buffer offset, would build it with no extra copy.
- A clear of a depth attachment converts the clear depth to a fixed-point code by the device's
rounding, which Vulkan lets be either of the two codes nearest it ("Conversion From Floating-Point
to Normalized Fixed-Point"): KosmicKrisp (Mesa 26.3.1, on an Apple M3 Max) clears a `Depth16Unorm`
texture to 0.25 as code 16383, where rounding to nearest gives 16384. No static note covers a
clear's conversion.
## Sampler states ## Sampler states
@@ -3387,9 +3284,8 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
that names no live buffer undefined; here it reads or writes whatever the device holds at that that names no live buffer undefined; here it reads or writes whatever the device holds at that
address, or faults, and a fault ends as the device ends it, up to a device loss that every guest address, or faults, and a fault ends as the device ends it, up to a device loss that every guest
process shares (above). What is bounded is a buffer argument's access at a byte offset that is process shares (above). What is bounded is a buffer argument's access at a byte offset that is
not a translation-time constant, and a load the translator makes where the program did not run not a translation-time constant: outside its buffer a load reads zero and a store does nothing
it: outside its buffer a load reads zero and a store does nothing (below). Any other access at a (below). An access at a constant offset is not checked.
constant offset is not checked.
- No guest word indexes a set 1 array past its length. A slot's texture or sampler, and a - No guest word indexes a set 1 array past its length. A slot's texture or sampler, and a
constexpr sampler, are read at the runtime's own placement (texture indices 1 to 65,535, sampler constexpr sampler, are read at the runtime's own placement (texture indices 1 to 65,535, sampler
indices 1 to 3,999; a placement outside them is refused). An argument buffer's texture is read at indices 1 to 3,999; a placement outside them is refused). An argument buffer's texture is read at
@@ -3407,8 +3303,7 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
device keeps from its first such dispatch or draw, its address the argument's pushed value, as device keeps from its first such dispatch or draw, its address the argument's pushed value, as
Metal's nil buffer reads zeros. Its pushed buffer is 0 bytes long, so every checked access of Metal's nil buffer reads zeros. Its pushed buffer is 0 bytes long, so every checked access of
it (below) is outside. Reads past the 64 KiB and writes through a nil argument at a constant it (below) is outside. Reads past the 64 KiB and writes through a nil argument at a constant
offset aren't covered, but for a load the translator makes where the program did not run it offset aren't covered.
(below), which is checked.
- A buffer argument's access at a byte offset that is not a translation-time constant is checked - A buffer argument's access at a byte offset that is not a translation-time constant is checked
against its buffer, from the buffer's start to its end, as Metal's domain is the buffer: a against its buffer, from the buffer's start to its end, as Metal's domain is the buffer: a
dispatch or draw pushes, beside the argument's address, the bind offset and the buffer's length dispatch or draw pushes, beside the argument's address, the bind offset and the buffer's length
@@ -3416,11 +3311,7 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
writes the buffer's bytes there. Outside the buffer, a load reads zero, from 16 bytes of zeros writes the buffer's bytes there. Outside the buffer, a load reads zero, from 16 bytes of zeros
the device keeps in a ring chunk of their own, taken at the first dispatch or draw that checks a the device keeps in a ring chunk of their own, taken at the first dispatch or draw that checks a
load, which nothing is bound to and nothing writes; a store or an atomic does nothing, and an load, which nothing is bound to and nothing writes; a store or an atomic does nothing, and an
atomic answers 0. This holds on every device. So is a load the translator makes where the atomic answers 0. This holds on every device. An access at a constant offset is not checked,
program did not run it, at any offset: a kernel's load of a `constant T&` argument's object
made in its entry block, ahead of the branch it stood behind, and a load of a branch's arm that
Metal's backend speculates, each of which a thread may run where the guest bound the argument
short or not at all. Any other access at a constant offset is not checked,
before the bind offset or past it: a draw or dispatch that binds a buffer shorter than the before the bind offset or past it: a draw or dispatch that binds a buffer shorter than the
function's constant-offset accesses to it meets the device's own out-of-bounds behaviour, and function's constant-offset accesses to it meets the device's own out-of-bounds behaviour, and
where nothing maps there that is a fault, which loses the device on NVIDIA's driver and on RADV where nothing maps there that is a fault, which loses the device on NVIDIA's driver and on RADV
@@ -4508,12 +4399,6 @@ cache is answered compile-required on both.
### Known gaps of pipeline states ### Known gaps of pipeline states
- A state of a kernel whose function was specialized with a required function constant left
without a value is refused (`Error::Translation`) where the translator's reading of that
constant leaves a structure it cannot lower, and Metal makes and runs the state: a kernel whose
explicit imageblock argument that constant gates, and whose body still reaches the imageblock,
carries the translator's `Unsupported{Imageblocks}` with `ImageblockCause::Missing`. What Metal
computes from such a constant is undefined (docs/API.md, "Function constants").
- A `half` simdgroup sum or product is Metal's tree of rounded `half` operations on every device, - A `half` simdgroup sum or product is Metal's tree of rounded `half` operations on every device,
where the device's reduction of the `float` values rounded once, which it replaces, was faster and where the device's reduction of the `float` values rounded once, which it replaces, was faster and
not Metal's answer. The tree has four forms, chosen by two queries: the SIMD-group operations not Metal's answer. The tree has four forms, chosen by two queries: the SIMD-group operations
@@ -4624,6 +4509,8 @@ cache is answered compile-required on both.
`MTLArgumentBuffersTier2`, which `Device::argument_buffers_support` answers: a state over a `MTLArgumentBuffersTier2`, which `Device::argument_buffers_support` answers: a state over a
function that holds one is `Error::Translation` of `Unsupported{IdentityDomains}`, not function that holds one is `Error::Translation` of `Unsupported{IdentityDomains}`, not
implemented, whose symbol names the first form it holds. By form: implemented, whose symbol names the first form it holds. By form:
- an object or mesh function ("a function of a stage other than a kernel, vertex or fragment
function"): no test yet;
- a fragment function over its tile's threadgroup memory (a `[[threadgroup(n)]]` argument of a - a fragment function over its tile's threadgroup memory (a `[[threadgroup(n)]]` argument of a
fragment function): the golden table holds the refusal (`engine/cfit_fragment_tile_memory`). No fragment function): the golden table holds the refusal (`engine/cfit_fragment_tile_memory`). No
guest of the consumer's can ask for one: Metal's feature set tables give tile shaders and guest of the consumer's can ask for one: Metal's feature set tables give tile shaders and
@@ -4643,11 +4530,11 @@ cache is answered compile-required on both.
through its device address"): no test yet; through its device address"): no test yet;
- a texture argument of a type the identity arrays hold no element of, or whose bound texture's - a texture argument of a type the identity arrays hold no element of, or whose bound texture's
state beyond its resource ID the function reads ("texture argument S: a type the identity state beyond its resource ID the function reads ("texture argument S: a type the identity
arrays hold no element of, or state of the bound texture beyond its resource ID"): no test arrays hold no element of, or state of the bound texture beyond its resource ID"), a depth
yet. A sampled cube or cube array read by face through `access::read` or `access::sample`, a cube read by face among them: no test yet. A sampled cube or cube array read by face through
depth cube's and depth cube array's included, is lowered, a sample of its cube view through `access::read` or `access::sample` is lowered, a sample of its cube view through element 0 of
element 0 of the sampler arrays (the default sampler, every level reached) at the texel's the sampler arrays (the default sampler, every level reached) at the texel's centre: the
centre: the device test `tests::cube_reads` and the validation case device test `tests::cube_reads` and the validation case
`cube_and_cube_array_face_reads_read_their_faces_under_the_identity_domains`. A storage cube `cube_and_cube_array_face_reads_read_their_faces_under_the_identity_domains`. A storage cube
written or read by face is lowered: the translator test written or read by face is lowered: the translator test
`a_storage_cube_written_by_face_is_the_2d_array_element_of_its_faces`; `a_storage_cube_written_by_face_is_the_2d_array_element_of_its_faces`;
@@ -4660,8 +4547,8 @@ cache is answered compile-required on both.
`under_the_identity_domains_a_runtime_samplers_query_reads_its_pushed_word`; `under_the_identity_domains_a_runtime_samplers_query_reads_its_pushed_word`;
- other state of a bound texture or sampler beyond its resource ID ("state of a bound texture - other state of a bound texture or sampler beyond its resource ID ("state of a bound texture
or sampler beyond its resource ID (F)", `F` the `RuntimeFact`): a cube's view shape, or sampler beyond its resource ID (F)", `F` the `RuntimeFact`): a cube's view shape,
`ImageViewShape`, and a storage texture's numeric type that nothing in the function states, `ImageViewShape`; a storage texture's numeric type that nothing in the function states,
`StorageTextureNumericType`: no test yet; `StorageTextureNumericType`; and a texture's swizzle, `TextureSwizzle`: no test yet;
- program-scope constant data past 64 KiB read through memory ("constant data of N bytes read - program-scope constant data past 64 KiB read through memory ("constant data of N bytes read
through memory"): `tests::engine_identity`'s through memory"): `tests::engine_identity`'s
`a_constant_blob_past_the_modules_bound_is_refused_naming_its_size` asserts the text; `a_constant_blob_past_the_modules_bound_is_refused_naming_its_size` asserts the text;
@@ -4816,12 +4703,10 @@ cache is answered compile-required on both.
its 8-bit sRGB textures' UNORM twins; a render state's content for a draw's buffers bound so, its 8-bit sRGB textures' UNORM twins; a render state's content for a draw's buffers bound so,
or for its 8-bit sRGB textures' UNORM twins; and a render state's content for a pass it does or for its 8-bit sRGB textures' UNORM twins; and a render state's content for a pass it does
not render into as made (a colour attachment the pass lacks, or a fetched colour in a 2D not render into as made (a colour attachment the pass lacks, or a fetched colour in a 2D
array); a compute or render state's content for the 4:2:2 textures a dispatch or draw reaches; array). Each is made once and kept, with its content or in the device's map of contents, so a
and a render content's depth range twin. Each is made once and kept, with its content or in the reuse makes nothing; a content the map forgot is made again. `Metrics::translations_at_encode`
device's map of contents, so a reuse makes nothing; a content the map forgot is made again. counts these makes, made or refused, and `translation_at_encode_max_nanos` holds the longest
`Metrics::translations_at_encode` counts these makes, made or refused, one. Only the first kind has a pre-pass that moves it off the encoding thread.
`translation_at_encode_nanos` sums their time and `translation_at_encode_max_nanos` holds the
longest one. Only the first kind has a pre-pass that moves it off the encoding thread.
- On Intel's Windows driver (101.2145) for the UHD 630, the driver's compile of a tiling kernel's - On Intel's Windows driver (101.2145) for the UHD 630, the driver's compile of a tiling kernel's
`VkPipeline`, the state's main one, took medians of 6,680 to 6,853 µs for the harness's `VkPipeline`, the state's main one, took medians of 6,680 to 6,853 µs for the harness's
`create_state` kernel, in three processes of 40 compiles each with no driver cache hit. The `create_state` kernel, in three processes of 40 compiles each with no driver cache hit. The
@@ -5111,10 +4996,7 @@ cache is answered compile-required on both.
descriptor's `inputPrimitiveTopology` names `MTLPrimitiveTopologyClassLine` or descriptor's `inputPrimitiveTopology` names `MTLPrimitiveTopologyClassLine` or
`MTLPrimitiveTopologyClassPoint`; otherwise each is `MTLPrimitiveTopologyClassPoint`; otherwise each is
made by the content's first draw of lines or of points, which waits for it made by the content's first draw of lines or of points, which waits for it
(`Metrics::first_use_waits`, `first_use_line_waits`, `first_use_point_waits`). A draw on (`Metrics::first_use_waits`, `first_use_line_waits`, `first_use_point_waits`). Of the two replay
another thread that needs the same `VkPipeline` while that make is in flight waits for it, a
first-use wait counted at the same place; one that needs another of the content's `VkPipeline`s
makes or takes its own and waits for no make but its own. Of the two replay
streams' 537 render contents drawn, 527 draw only triangles and 2 lines and triangles; a content streams' 537 render contents drawn, 527 draw only triangles and 2 lines and triangles; a content
drawn only as lines (8 of them) makes a triangle `VkPipeline` it never uses. A draw under the drawn only as lines (8 of them) makes a triangle `VkPipeline` it never uses. A draw under the
depth clip mode `Clamp` or the triangle fill mode `Lines` takes its class's `VkPipeline` for that depth clip mode `Clamp` or the triangle fill mode `Lines` takes its class's `VkPipeline` for that
@@ -5292,11 +5174,10 @@ cache is answered compile-required on both.
does, is not drawn. does, is not drawn.
- On a driver that keeps the topology class in a pipeline (dynamicPrimitiveTopologyUnrestricted - On a driver that keeps the topology class in a pipeline (dynamicPrimitiveTopologyUnrestricted
false; RADV), a render pipeline state's first draw in a second topology class compiles a second false; RADV), a render pipeline state's first draw in a second topology class compiles a second
pipeline in full when the driver's cache is cold, and that draw waits for it. On a 780M, a guest pipeline in full when the driver's cache is cold: 225 ms for the heaviest pipeline measured on a
session's start made 4 such pipelines, all of the line class, in 1,171 to 1,205 ms in all: one 780M, 0.9 to 1.5 ms for the others, nothing once the driver's cache holds it. A driver without
heavy state's took 1,166 to 1,198 ms and each of the other three under 10 ms. None is made once the restriction serves it from its cache (0.1 ms on ANV). Linking from pipeline libraries would
the driver's cache holds it. A driver without the restriction serves it from its cache (0.1 ms avoid it; the floor does not have them.
on ANV). Linking from pipeline libraries would avoid it; the floor does not have them.
- Each render content is one whole `VkPipeline`, compiled with no shared library parts, so a cold - Each render content is one whole `VkPipeline`, compiled with no shared library parts, so a cold
make pays the content's whole compile. A recorded session's heaviest content, a fragment make pays the content's whole compile. A recorded session's heaviest content, a fragment
function of about 30,800 SPIR-V instructions, takes 1,408 ms of driver time cold on an RTX 3090 function of about 30,800 SPIR-V instructions, takes 1,408 ms of driver time cold on an RTX 3090
@@ -5307,60 +5188,16 @@ cache is answered compile-required on both.
render content's record (The cache directory), so it decodes and specializes no function: on render content's record (The cache directory), so it decodes and specializes no function: on
lavapipe, a recorded session's warm render state creation is 31 to 44% faster with the records lavapipe, a recorded session's warm render state creation is 31 to 44% faster with the records
than without them. than without them.
- Mesh render pipeline states are made and drawn. `Device::new_mesh_render_pipeline_state` - Mesh render pipelines are not built. No call makes a state of a `MTLMeshRenderPipelineDescriptor`
(`newRenderPipelineStateWithMeshDescriptor:`) makes the state and its one `VkPipeline`, and the (`newRenderPipelineStateWithMeshDescriptor:`), and the render encoder has no object or mesh
state answers its thread and grid maxima. The render encoder binds the object and mesh functions' binding and no mesh draw (`drawMeshThreadgroups:`, `drawMeshThreads:` and the indirect form), so
tables (`set_object_*`, `set_mesh_*`) and draws `drawMeshThreadgroups:`, `drawMeshThreads:` and no type here names them and the consumer refuses them itself. `new_render_pipeline_state` takes
`drawMeshThreadgroupsWithIndirectBuffer:` (of a state without an object function, below); a draw a vertex function: an object or mesh function in its place is the translator's refusal
of primitives or patches with a mesh state, or a mesh draw with a vertex function's, is (`Error::Translation`). The translator's mesh lowering (docs/API.md, "Mesh pipelines") is only
`Refusal::MeshDraw`. A draw whose object or mesh threadgroup is within Metal's maximum and past compiled and validated: it has never been compared with Metal on a GPU, and rt makes no
the state's capped one (below) is `Limit::MeshThreadgroupThreads`, naming the stage's Vulkan limit `VkPipeline` of it. No replay stream or live session has used one; harvested guest
and its value, and counted (`Metrics::mesh_threadgroups_past_device`): Metal draws it. An object functions declare them, and validation's committed object and mesh cases qualify on Metal alone
grid past the device's task limits runs in pieces of one multi-draw, whose records lie in one ring (its `mesh_render_pipeline` requirement).
chunk, so a grid of more than 5,461 pieces (about 2.29 × 10^10 object threadgroups: a piece holds
4,194,240 or 4,194,304 on the committed profiles with mesh shading) is
`Limit::ObjectThreadgroups`; Metal states no limit there. An indirect mesh draw of a state with an
object function is refused at the draw (`Gap::Draw` of `DrawKind::IndirectObjectGrid`), where
Metal draws it: its object grid is the GPU's, and one past the device's task limits runs in pieces
whose number only the counts decide, which the runtime never reads on the host and no command
inside the pass can write. An indirect draw of a state without an object function is drawn through
the launcher. Each recorded draw is counted by its form (`Metrics::mesh_draws_launched`,
`Metrics::mesh_object_grids_whole`, `Metrics::mesh_object_grids_in_pieces`). No guest has met
either refusal: no replay stream or live session has used a mesh
state. Each creation compiles its content: the translator gives no key of a mesh descriptor before
its compile, so neither the device's map of contents nor the cache directory holds one, and a
guest that makes one state many times compiles it each time. An object or mesh function with a
`[[threadgroup(n)]]` argument is refused at the creation (`Gap::RenderPipeline`), as
`setObjectThreadgroupMemoryLength:atIndex:` and its mesh form are not built; they are built when
the first replay stream, consumer walk or guest makes a mesh state whose object or mesh function
declares one. Each stage's thread maximum is Metal's (the descriptor's required size, else its
maximum, else the function's, else 1024), capped by the stage's Vulkan limit
(`maxTaskWorkGroupInvocations` and `maxTaskWorkGroupSize[0]`, or the mesh stage's), so a device
whose limit is below Metal's answers less than an M3 Max. The conformance suite's 44 cases of mesh
pipelines, recorded on an Apple M3 Max under macOS 27.0.1, are compared on lavapipe (Mesa 26.2.4),
the RTX 5080 Laptop (NVIDIA 615.71.09), the RTX 3090 (NVIDIA 620.70.06), and the Radeon 780M and
the RX 7900 XTX (RADV, Mesa 26.2.6). On each of them, 9 match Metal exactly, 5 match with their
precision notes announced, 29 are refused as the conformance ledger lists, and
`mesh-barrier-readers` differs: behind its four barriers with the fragment stage in their after
stages, the reader draw sees the fragment writer's words, as the header orders, where the M3's
reader did not; Metal's feature set tables (note 3) do not support such a barrier on Apple3
through Apple11 GPUs, so that recording is outside what Metal documents. An object grid past the
task total, drawn in pieces, is drawn by a device test of 4,194,305 object threadgroups on
lavapipe, the RTX 3090, the Radeon 780M and the RX 7900 XTX; no conformance case draws one. Each
stage's workgroup is the state's maximum M, so a draw of a smaller threadgroup runs the rest of
its workgroup idle, and a state without an object function launches its mesh grid from the
launcher's one task invocation. On the RTX 3090 (NVIDIA 620.70.06), a draw of one group through
the launcher took 10,720 ns of GPU time where a one-triangle draw of a vertex state on the same
kind of pass took 12,704 ns, and 65,535 groups of 4 threads took 1.01 times as long at M 128 as at
M 4 (149,504 and 148,672 ns; 2.12 ns a group). On the RX 7900 XTX (RADV, Mesa 26.2.6), the one
group took 64,720 ns where the triangle took 7,920 ns, 8.2 times as long, and a one-group draw of
a state with an object function, whose task stage is the function's, took 74,560 ns: the cost is a
task stage's on that driver, not the launcher's. There the 65,535 groups took 1.39 times as long
at M 256 as at M 4 (221,120 and 159,280 ns; 2.39 ns a group). Each time is the median of nine
command buffers. Harvested guest functions declare object and mesh functions. Validation's
engine candidate draws its committed object and mesh cases through these calls and compares
them with Metal's, but for the case whose object function declares threadgroup memory, which
qualifies on Metal alone (its `mesh_threadgroup_memory` requirement).
- On a Vulkan driver built on Metal (Mesa's KosmicKrisp on the Mac), a fragment function that - On a Vulkan driver built on Metal (Mesa's KosmicKrisp on the Mac), a fragment function that
declares `[[early_fragment_tests]]` loses every texture write in a pipeline of more than one declares `[[early_fragment_tests]]` loses every texture write in a pipeline of more than one
sample: it runs, and its buffer writes land, but none of its texture writes does. This is sample: it runs, and its buffer writes land, but none of its texture writes does. This is
@@ -5642,26 +5479,15 @@ cache is answered compile-required on both.
Metal stores it. Metal stores it.
- A viewport depth range past `[0, 1]` (OpenGL's `[-1, 1]`) is set, as Metal and its API - A viewport depth range past `[0, 1]` (OpenGL's `[-1, 1]`) is set, as Metal and its API
validation take it. Metal maps clip space's z through it unclamped into a fragment function's validation take it. Metal maps clip space's z through it unclamped into a fragment function's
`[[position]].z`, a depth attachment stores that, and a `[[depth]]` output, clamped to `[[position]].z`, and a depth attachment stores that, and a `[[depth]]` output, clamped to
`[0, 1]`, the depth test compares the clamped value, and clip space's `0 <= z <= w` clips `[0, 1]` (an Apple M3 Max, macOS 27.0.1: the conformance crate's
whatever the range (an Apple M3 Max, macOS 27.0.1: the conformance crate's
`probes/viewport_depth_past_unit.m`). The runtime enables no `VK_EXT_depth_range_unrestricted`, `probes/viewport_depth_past_unit.m`). The runtime enables no `VK_EXT_depth_range_unrestricted`,
so it records the range cut to `[0, 1]`, which shows nowhere in a draw whose pass has no depth so it records the range cut to `[0, 1]`, which shows nowhere in a draw whose pass has no depth
attachment and whose fragment function reads no `[[position]]` z or w, since clipping is in attachment and whose fragment function reads no `[[position]]` z or w, since clipping is in
clip space; such a draw draws through the state's own content, as Metal's. Every other draw clip space; such a draw draws as Metal's. Every other draw while such a range is set is a known
under the `Clip` depth clip mode draws through the state's depth range twin: its content gap, refused at the draw (`DrawKind::Viewport`). Whether a range is past `[0, 1]` is found when
lowered again, its vertex function storing `znear * w + (zfar - znear) * z` as its position's the viewports are set, and whether a draw is refused for it when they or the pipeline state
z and its clip space's z bounds, `z` and `w - z`, as two clip distances after its own, drawn are set, so a draw reads one field for it.
with the viewport at `[0, 1]` and the device's depth clamp (`depthClamp`, Floor). So it clips,
reads, stores and tests what Metal does, through the device's arithmetic
(`RenderCommandEncoder::DEPTH_RANGE_NOTE`). The twin folds the first viewport's range: a vertex
function that writes `[[viewport_array_index]]` draws through it where every viewport set has
that range. A twin is made by the first draw of its content that needs it, on the encoding
thread (`Metrics::depth_range_twins`, timed as a make at encode), and is held with that
content for the content's life; no map of its own keeps it. Whether a range is past `[0, 1]`
is found when the viewports are set, and whether a draw is refused or goes through the twin
when they, the pipeline state or the depth clip mode are set, so a draw reads one field for
it.
- `set_viewports` and `set_scissor_rects` are `setViewports:count:` and - `set_viewports` and `set_scissor_rects` are `setViewports:count:` and
`setScissorRects:count:`, 1 to 16 each, recorded with their count (`vkCmdSetViewportWithCount`, `setScissorRects:count:`, 1 to 16 each, recorded with their count (`vkCmdSetViewportWithCount`,
`vkCmdSetScissorWithCount`, so no pipeline is made for a count). A vertex function's `vkCmdSetScissorWithCount`, so no pipeline is made for a count). A vertex function's
@@ -5673,8 +5499,8 @@ cache is answered compile-required on both.
the rectangles set where several are, each cut to the pixels its viewport covers. The index is the rectangles set where several are, each cut to the pixels its viewport covers. The index is
stored as the function writes it, as a layer index is (Layered rendering, below). stored as the function writes it, as a layer index is (Layered rendering, below).
- A draw may read an attachment of its own pass through a texture, as Metal reads a render - A draw may read an attachment of its own pass through a texture, as Metal reads a render
target (Floor, Attachment reads): through the attachment feedback loop where the device has it, target, where the device reads attachments (Floor, Attachment reads): through the attachment
else through a copy. The texture reaches the feedback loop where the device has it, else through a copy. The texture reaches the
attachment's level and layer, the fragment function reads it and nothing writes it, and its attachment's level and layer, the fragment function reads it and nothing writes it, and its
image is a colour render target, which one attachment of the pass renders. A texture in place image is a colour render target, which one attachment of the pass renders. A texture in place
over a buffer is read through the loop where its linear image took the feedback usage, else over a buffer is read through the loop where its linear image took the feedback usage, else
@@ -5707,33 +5533,23 @@ cache is answered compile-required on both.
attachment through the loop, through a texture or by a fetch (below), counts in attachment through the loop, through a texture or by a fetch (below), counts in
`Metrics::attachment_loop_reads`, its barriers in `Metrics::barriers`. `Metrics::attachment_loop_reads`, its barriers in `Metrics::barriers`.
- Through a copy, on a device without the feedback loop, and for a surface plane or a texture in - Through a copy, on a device without the feedback loop, and for a surface plane or a texture in
place over a buffer whose image took no feedback usage, a Direct3D 11 plane's on every device place over a buffer whose image took no feedback usage (Exported surfaces; Memory blocks and
(Exported surfaces; Memory blocks and buffers), the draw reads the image's shadow: an image of the same buffers), the draw reads the image's shadow: an image of the same
format, extent, levels and layers, made at the first draw that reads the image and freed with it format, extent, levels and layers, made at the first draw that reads the image and freed with it
(`Gauges::shadows` and `shadow_bytes`). A texture that reaches the attachment's level and layer (`Gauges::shadows` and `shadow_bytes`). A texture that reaches the attachment's level and layer
reads the shadow through its second element; one that reaches neither reads the image at home. reads the shadow through its second element; one that reaches neither reads the image at home.
Where the draw reads what the shadow does not hold, the rendering ends, one barrier orders every Where the draw reads what the shadow does not hold, the rendering ends, one barrier orders every
earlier command before the copies and moves what they copy to the transfer layouts, the copies earlier command before the copies and moves what they copy to the transfer layouts, the copies
are recorded (`Metrics::attachment_read_copies` and `attachment_read_copy_bytes`), one barrier are recorded (`Metrics::attachment_read_copies` and `attachment_read_copy_bytes`), one barrier
moves it all back, and the rendering begins again. Their bytes are parted by read, at the moves it all back, and the rendering begins again. A slot the fragment function reads only at its
fragment's own pixel or of all a texture reaches (`attachment_read_copy_bytes_own_pixel` and own pixel reads the draw's scissor, a pixel wider each way, clamped into its level; any other
`attachment_read_copy_bytes_whole_texture`), and by when they come: the pass's first copy into slot reads every level and layer its texture reaches. What is new to the shadow is copied as one
the shadow, the first after a memory barrier left it holding nothing, or a read past what it
holds (`attachment_read_copy_bytes_first_in_pass`, `attachment_read_copy_bytes_after_barrier`
and `attachment_read_copy_bytes_beyond_held`). A narrower form, whose memory barrier forgets
only the rectangle bounding the scissors of the pass's draws, is not taken: on Intel's Windows
driver (101.2145) for the UHD Graphics 630, Windows 11, it would have removed 42.4% of these
bytes over a desktop boot and 25.6% over a 40 s 1080p H.264 playback. A slot the fragment
function reads only at its own pixel reads the draw's scissor, a pixel wider each way, clamped
into its level; any other slot reads every level and layer its texture reaches. What is new to the shadow is copied as one
area where it is one (a wider scissor's band), else as the whole read, with no look-ahead. At the area where it is one (a wider scissor's band), else as the whole read, with no look-ahead. At the
pass's first draw, where the pass cleared the attachment and every read of its level and layer pass's first draw, where the pass cleared the attachment and every read of its level and layer
lies in it alone and inside Metal's render area, and the shadow is of the attachment's format, lies in it alone and inside Metal's render area, the shadow's level and layer is cleared to
the shadow's level and layer is cleared to the pass's clear colour between the same barriers the pass's clear colour between the same barriers instead of copied (the shadow is of the
instead of copied, so the clear writes the texels the pass's did. A draw of the pass before it, attachment's format, so the clear writes the texels the pass's did); a draw of the pass before
of any pipeline, leaves the copy, as does an attachment that is a view of another format than it, of any pipeline, leaves the copy.
its texture's: the shadow keeps the texture's format, so a pass that clears such a view and
reads it at its first draw and again after a memory barrier copies twice.
- A fragment function's read of a colour attachment (`[[color(n)]]`, framebuffer fetch) reads the - A fragment function's read of a colour attachment (`[[color(n)]]`, framebuffer fetch) reads the
attachment's texture at the fragment's own pixel, through its second element, whose index the attachment's texture at the fragment's own pixel, through its second element, whose index the
draw pushes (`PushField::FetchedColor`): in the feedback layout, or through the image's shadow, draw pushes (`PushField::FetchedColor`): in the feedback layout, or through the image's shadow,
@@ -5797,27 +5613,6 @@ cache is answered compile-required on both.
### Known gaps of render encoders ### Known gaps of render encoders
- A draw under a viewport depth range past `[0, 1]` that its depth attachment or fragment
function reads draws through its state's depth range twin (`set_viewport`, above), whose
lowering and `VkPipeline` compile are a stall of the first such draw of each content: 1.3 to
1.5 ms on lavapipe (Mesa 26.2.6) and 5.1 to 5.5 ms on an RTX 3090 (NVIDIA 620.70.06), three runs
each of release builds with the drivers' disk shader caches off, the twin's lowering up to
1.4 ms of it. The twin holds `VkPipeline`s of its own beside its content's: at most 8 (the
triangle class's 4, the line and the point class's 2 each, as the `Clamp` mode never reaches
it), and as many again for its words twin where the content has one, so a content and its twin
hold at most 48 where the content alone holds 32, for the content's life. Its two clip
distances need the device's `maxClipDistances` and `maxCombinedClipAndCullDistances` to take
the vertex function's own and 2 more: a draw of a function past them is refused with the
translator's limit refusal (`Error::Translation`), kept with the content so a later draw
answers it without lowering again. Under the `Clamp` depth clip mode, which stores the depth
clamped to the range's part in `[0, 1]` (the probe above), such a draw is refused
(`DrawKind::Viewport`), as is a draw of a vertex function that writes `[[viewport_array_index]]`
while the viewports set have different ranges, one of them past `[0, 1]` (the twin folds one
range), a draw of a vertex function the consumer compiled, which has no AIR to fold, and a mesh
draw, which has no vertex function: the fold in a mesh function that writes no per-primitive
viewport index is not built. A mesh state lowers none of its functions apart from its compile,
so its fragment function, from its AIR, is taken to read `[[position]]`'s z or w, and its draws
under such a range are refused with or without a depth attachment.
- On a device with the attachment feedback loop, every pipeline of a state whose functions can - On a device with the attachment feedback loop, every pipeline of a state whose functions can
read a texture takes the loop's colour flag, whether or not a draw hands it an attachment of read a texture takes the loop's colour flag, whether or not a draw hands it an attachment of
its pass, and one whose functions read none takes no flag. What the flag costs a draw that reads its pass, and one whose functions read none takes no flag. What the flag costs a draw that reads
@@ -5844,12 +5639,7 @@ cache is answered compile-required on both.
driver runs tessellation as compute work, and for an indirect draw dispatches the vertex and driver runs tessellation as compute work, and for an indirect draw dispatches the vertex and
control-point grid sizes it computes in threads as that many threadgroups, so the extra work control-point grid sizes it computes in threads as that many threadgroups, so the extra work
overwrites the next instance's vertices and control points (read from the driver's source, not overwrites the next instance's vertices and control points (read from the driver's source, not
instrumented). By the same source, the control-point work past the last instance's patches instrumented). A bare Vulkan program of 2 patches in 2 instances, with no runtime code, lost the
writes over the draw's own vertex outputs, so an indirect patch draw of one instance can go wrong
the same way; no run has shown one wrong. Every form that would hand the driver no such draw
writes a new indirect command from the guest's arguments outside the render pass, so it would
copy those arguments and end and restart the pass at every indirect patch draw on every device;
the runtime keeps the one form. A bare Vulkan program of 2 patches in 2 instances, with no runtime code, lost the
second instance's second patch in 3 of 8 indirect draws and in none of 8 direct ones under second instance's second patch in 3 of 8 indirect draws and in none of 8 direct ones under
KosmicKrisp, and in none under MoltenVK on the same GPU; its indirect draws of one instance were KosmicKrisp, and in none under MoltenVK on the same GPU; its indirect draws of one instance were
right. Three of the runtime's device tests draw patches of two instances with `indirect` true, and right. Three of the runtime's device tests draw patches of two instances with `indirect` true, and
@@ -5882,12 +5672,9 @@ cache is answered compile-required on both.
the largest extent past either side of the origin, is a viewport wider or taller than the largest extent past either side of the origin, is a viewport wider or taller than
`maxViewportDimensions` over the area, or one whose edge lies inside the last pixel of an area of `maxViewportDimensions` over the area, or one whose edge lies inside the last pixel of an area of
that largest size; at a draw, a viewport depth range past `[0, 1]` where the draw's pass has a that largest size; at a draw, a viewport depth range past `[0, 1]` where the draw's pass has a
depth attachment or its fragment function may read `[[position]]`'s z or w and no depth range depth attachment or its fragment function may read `[[position]]`'s z or w (above); a pipeline
twin draws it (under the `Clamp` mode, for a vertex function that writes state whose formats are not the pass's attachments' (but for colours
`[[viewport_array_index]]` under viewports of different ranges, for a vertex function the past the pass's last colour attachment, above), a draw that binds a texture whose image the pass
consumer compiled, or for a mesh draw: above, and the depth range twin's known gap below); a
pipeline state whose formats are not the pass's attachments' (but for colours past the pass's
last colour attachment, above), a draw that binds a texture whose image the pass
renders, where neither the feedback loop nor a copy reads it: on a device without the attachment renders, where neither the feedback loop nor a copy reads it: on a device without the attachment
reads, from the vertex function at the rendered level and layer, written, of a depth or stencil reads, from the vertex function at the rendered level and layer, written, of a depth or stencil
attachment, of an image the device takes neither the feedback usage nor a shadow for (its format's attachment, of an image the device takes neither the feedback usage nor a shadow for (its format's
@@ -5915,9 +5702,9 @@ cache is answered compile-required on both.
(`PushField::FetchedColor`), if a guest meets it: (`PushField::FetchedColor`), if a guest meets it:
- a padded extended-range attachment's blend (`R10Unorm_X6`, `RG10Unorm_X12`, their `_sRGB` - a padded extended-range attachment's blend (`R10Unorm_X6`, `RG10Unorm_X12`, their `_sRGB`
twins and `RGB10A2Unorm_sRGB`), refused naming `FramebufferFetch`, not implemented; twins and `RGB10A2Unorm_sRGB`), refused naming `FramebufferFetch`, not implemented;
- a write of some of the codes one word of an extended-range attachment holds (the two-plane - a write of some of the codes one word of an extended-range attachment holds (`BGR10_XR`, the
forms' colour word and the `_sRGB` twins', under a mask of some of those codes), refused two-plane forms' colour word and their `_sRGB` twins, under a mask of some of those codes),
naming `FramebufferFetch`, not implemented; refused naming `FramebufferFetch`, not implemented;
- a blend no Vulkan state gives on an attachment whose image holds its channels rotated - a blend no Vulkan state gives on an attachment whose image holds its channels rotated
(`ARGB8Unorm` reading destination alpha), refused naming `FramebufferFetch`, not implemented; (`ARGB8Unorm` reading destination alpha), refused naming `FramebufferFetch`, not implemented;
- a word attachment written under a mask of some of its channels, which takes its format's own - a word attachment written under a mask of some of its channels, which takes its format's own
@@ -5966,16 +5753,6 @@ cache is answered compile-required on both.
attachment of its own pass through its shadow, the copy a device without the feedback loop attachment of its own pass through its shadow, the copy a device without the feedback loop
takes, which Metal does not make (`Metrics::attachment_read_copies` and takes, which Metal does not make (`Metrics::attachment_read_copies` and
`attachment_read_copy_bytes`, in `bytes_copied` too). `attachment_read_copy_bytes`, in `bytes_copied` too).
- A Direct3D 11 plane (`Device::import_d3d11_surface`, on Windows) whose texture is a render
target shaders read is read as an attachment of its own pass through its shadow on every device,
the copy a device without the feedback loop takes, which Metal does not make
(`Metrics::attachment_read_copies` and `attachment_read_copy_bytes`, in `bytes_copied` too):
its image takes the usage its Direct3D 11 texture's bind flags give and no other, and that
description has no counterpart for the feedback usage (Exported surfaces). How often a guest
draw reads a plane it renders to is expected to be near zero, not verified beyond two runs on
an Intel UHD 630 under Windows that counted no render pass over a plane: a desktop boot, and a
video player's 41 s playback of a 1920 × 1080, 30 fps H.264 clip (934 pictures drawn, 2,053
Direct3D 11 plane submissions).
- A colour render target in place over a buffer (Memory blocks and buffers), on a device with - A colour render target in place over a buffer (Memory blocks and buffers), on a device with
the feedback loop whose linear image query (`vkGetPhysicalDeviceImageFormatProperties2`: the the feedback loop whose linear image query (`vkGetPhysicalDeviceImageFormatProperties2`: the
texture's format and usage in linear tiling, with the sampled and feedback usages added) texture's format and usage in linear tiling, with the sampled and feedback usages added)
@@ -6096,8 +5873,8 @@ cache is answered compile-required on both.
`VUID-VkRenderingInfo-multisampledRenderToSingleSampled-06857`), a resolve the runtime does not `VUID-VkRenderingInfo-multisampledRenderToSingleSampled-06857`), a resolve the runtime does not
build (`Resolve`: into a resolve texture of another pixel format, of more than one sample, or build (`Resolve`: into a resolve texture of another pixel format, of more than one sample, or
whose level is not the attachment level's size; out of an attachment of one sample; of an whose level is not the attachment level's size; out of an attachment of one sample; of an
extended-range format but `BGR10_XR` and `BGRA10_XR`, or of a bfloat or YCbCr format, whose extended-range, bfloat or YCbCr format, whose image Vulkan's average would read in its own
image Vulkan's average would read in its own encoding; or of a depth and a stencil attachment into two views), a resolve into a texture made encoding; or of a depth and a stencil attachment into two views), a resolve into a texture made
without `RenderTarget` usage whose image has no attachment usage (`ResolveUsage`: Metal without `RenderTarget` usage whose image has no attachment usage (`ResolveUsage`: Metal
resolves into a texture of any usage; Vulkan only into a view with the attachment usage, resolves into a texture of any usage; Vulkan only into a view with the attachment usage,
`VUID-VkRenderingInfo-colorAttachmentCount-09476`, which a one-sample colour texture of an `VUID-VkRenderingInfo-colorAttachmentCount-09476`, which a one-sample colour texture of an
@@ -6119,7 +5896,7 @@ cache is answered compile-required on both.
`resolveDepthPlane` (`TextureType`; a resolve texture of another type is resolved into as at `resolveDepthPlane` (`TextureType`; a resolve texture of another type is resolved into as at
plane 0, as Metal with its validation layer off does, probe `resolve_depth_planes.m`), the plane 0, as Metal with its validation layer off does, probe `resolve_depth_planes.m`), the
`CustomSampleDepthStore` store action, a clear of a format only a shader clears (extended `CustomSampleDepthStore` store action, a clear of a format only a shader clears (extended
range but `BGR10_XR` and `BGRA10_XR`, bfloat, YCbCr), a `renderTargetArrayLength` past the device's `maxFramebufferLayers` range, bfloat, YCbCr), a `renderTargetArrayLength` past the device's `maxFramebufferLayers`
(`ArrayLength`: Vulkan renders at most that many layers, (`ArrayLength`: Vulkan renders at most that many layers,
`VUID-VkRenderingInfo-layerCount-07817`, and requires 256 of it, where Metal's arrays hold 2048 `VUID-VkRenderingInfo-layerCount-07817`, and requires 256 of it, where Metal's arrays hold 2048
slices), and a pass with no attachment past the device's `maxFramebufferWidth` or slices), and a pass with no attachment past the device's `maxFramebufferWidth` or
@@ -6223,8 +6000,7 @@ cache is answered compile-required on both.
the pass's first draw that reads the image, at the first after a memory barrier after draws, the pass's first draw that reads the image, at the first after a memory barrier after draws,
and where a draw reads what the shadow does not hold, the rendering ended and begun again and where a draw reads what the shadow does not hold, the rendering ended and begun again
around the copies and their two barriers; where the draw is the pass's first and reads only around the copies and their two barriers; where the draw is the pass's first and reads only
what its pass cleared, a clear of the shadow takes the copies' place, except through a view of what its pass cleared, a clear of the shadow takes the copies' place. Its cost, measured on the
another format than its texture's, whose shadow keeps the texture's format. Its cost, measured on the
UHD 630 in the harness (release; GPU time a pass, the median over four rounds of each round's UHD 630 in the harness (release; GPU time a pass, the median over four rounds of each round's
median) by a pass that loads its `BGRA8Unorm` target, ends for a copy of all of it and begins median) by a pass that loads its `BGRA8Unorm` target, ends for a copy of all of it and begins
again, against the same pass without the copy: 39.0 µs a MiB at 1920 × 1080 and 53.5 µs a MiB again, against the same pass without the copy: 39.0 µs a MiB at 1920 × 1080 and 53.5 µs a MiB
@@ -6440,8 +6216,7 @@ pass's end orders its writes before every later command.
first command (4 bytes each), then any other leading word (4 bytes each); first command (4 bytes each), then any other leading word (4 bytes each);
4. its buffer slots' words, in slot order (8 bytes each); 4. its buffer slots' words, in slot order (8 bytes each);
5. its other fields, including, for each slot it reads at an offset that is not a 5. its other fields, including, for each slot it reads at an offset that is not a
translation-time constant or by a load made where the program did not run it, that slot's translation-time constant, that slot's bounds and the zero range's address (8 bytes each);
bounds and the zero range's address (8 bytes each);
6. 24 bytes of gap and a 4-byte tail word, or its last bounds field as the tail. 6. 24 bytes of gap and a 4-byte tail word, or its last bounds field as the tail.
From the first field that does not fit, its fields sit in its parameter block. So a vertex From the first field that does not fit, its fields sit in its parameter block. So a vertex
function with no other leading address pushes 25 slot words ((248 - 16 - 28) / 8, rounded down) function with no other leading address pushes 25 slot words ((248 - 16 - 28) / 8, rounded down)
@@ -6527,13 +6302,6 @@ pass's end orders its writes before every later command.
`copyIndirectCommandBuffer:sourceRange:destination:destinationIndex:`, compute commands, and a `copyIndirectCommandBuffer:sourceRange:destination:destinationIndex:`, compute commands, and a
function's draws other than plain or indexed triangles and plain or indexed patch draws, which function's draws other than plain or indexed triangles and plain or indexed patch draws, which
the translator refuses (`Unsupported{GpuEncodedIndirectCommands, NotImplemented}`). the translator refuses (`Unsupported{GpuEncodedIndirectCommands, NotImplemented}`).
- Mesh draw commands (`MTLIndirectCommandTypeDrawMeshThreadgroups` and
`MTLIndirectCommandTypeDrawMeshThreads`, alone or beside other types) are refused as
`CommandTypes`. Two general gaps come before them: the conformance suite's three mesh command
cases each set their own pipeline state (`CommandPipelines`) and are encoded by the CPU, which is
not built. With both of those built, the mesh types take a command layout of their own (the
`VK_INDIRECT_COMMANDS_TOKEN_TYPE_DRAW_MESH_TASKS_EXT` token), with each draw's group counts and
threadgroup sizes, as a direct mesh draw pushes them.
## Presenting ## Presenting
@@ -6692,7 +6460,6 @@ Presenting runs on the runtime's own device; nothing is exported or imported.
| `VK_EXT_device_generated_commands` | device, with indirect command buffers | an indirect command buffer's execution, through `deviceGeneratedCommands`, enabled where the device reports it with the limits an execution needs (Indirect command buffers, above) | | `VK_EXT_device_generated_commands` | device, with indirect command buffers | an indirect command buffer's execution, through `deviceGeneratedCommands`, enabled where the device reports it with the limits an execution needs (Indirect command buffers, above) |
| `VK_KHR_maintenance5` | device, with indirect command buffers | the preprocess buffers' usage flag (`VkBufferUsageFlags2CreateInfoKHR`), through `maintenance5`, enabled with the extension above alone | | `VK_KHR_maintenance5` | device, with indirect command buffers | the preprocess buffers' usage flag (`VkBufferUsageFlags2CreateInfoKHR`), through `maintenance5`, enabled with the extension above alone |
| `VK_KHR_fragment_shader_barycentric` | device, where reported | a fragment function's `[[barycentric_coord]]`, through the barycentric feature below; `Device::extensions` names it only where that feature is enabled | | `VK_KHR_fragment_shader_barycentric` | device, where reported | a fragment function's `[[barycentric_coord]]`, through the barycentric feature below; `Device::extensions` names it only where that feature is enabled |
| `VK_EXT_mesh_shader` | device, with the mesh stages | Metal's object and mesh functions, as task and mesh shaders, through the mesh-stage features below (Mesh stages, below); `Device::extensions` names it only with all three |
### Features ### Features
@@ -6886,39 +6653,39 @@ pipeline states). So `Device::extensions` names the extension only with its feat
### Limits ### Limits
The descriptor limits are what the runtime's fixed arrays need: 65,536 sampled textures with their The descriptor limits are what the runtime's fixed arrays need: 65,536 sampled textures, 65,536
65,536 second elements, 65,536 storage textures and 65,536 level elements, 65,536 read and 65,536 storage textures and 65,536 level elements, 65,536 read and 65,536 written texture buffers, and three arrays of 8,000
written texture buffers, and three arrays of 8,000 samplers, one per use (plain, depth comparison, samplers, one per use (plain, depth comparison, integer texture): 4,000 indices and 4,000 variant
integer texture): 4,000 indices and 4,000 variant elements each (Set 1 and index grants). A read elements each (Set 1 and index grants). A read texture buffer (a uniform texel buffer) counts
texture buffer (a uniform texel buffer) counts against the sampled-image limits and a written one (a against the sampled-image limits and a written one (a storage texel buffer) against the
storage texel buffer) against the storage-image limits. Vulkan requires at least 500,000 of each storage-image limits. Vulkan requires at least 500,000 of each texture and sampler limit and of
texture and sampler limit and of the two resource totals on a device that supports the two resource totals on a device that supports `descriptorIndexing`, as every lab device does.
`descriptorIndexing`, as every lab device does. 4,000 is Vulkan's minimum 4,000 is Vulkan's minimum `maxSamplerAllocationCount`. Of the lab's devices, the least
`maxSamplerAllocationCount`. Of the lab's devices, the least
`maxPerStageDescriptorUpdateAfterBindSamplers` and `maxDescriptorSetUpdateAfterBindSamplers` is `maxPerStageDescriptorUpdateAfterBindSamplers` and `maxDescriptorSetUpdateAfterBindSamplers` is
500,000 (MoltenVK on an Apple M3 Max) and the least `maxUpdateAfterBindDescriptorsInAllPools` 500,000 (MoltenVK on an Apple M3 Max) and the least `maxUpdateAfterBindDescriptorsInAllPools`
1,048,576 (Intel UHD Graphics 630 on Windows). The compute limits let a threadgroup take Metal's 1,048,576 (Intel UHD Graphics 630 on Windows). The compute limits let a threadgroup take
1,024 threads in any shape up to 1,024 by 1,024 by 64. `maxColorAttachments` holds Metal's eight Metal's 1,024 threads in any shape up to 1,024 by 1,024 by 64. `maxColorAttachments` holds
color attachments on every device; Vulkan 1.3 requires 4 of it, and Vulkan 1.4 8. Metal's eight color attachments on every device; Vulkan 1.3 requires 4 of it, and Vulkan 1.4 8.
`maxFragmentOutputAttachments` holds a fragment function's output to each of them; Vulkan 1.3 and `maxFragmentOutputAttachments` holds a fragment function's output to each of them; Vulkan 1.3 and
1.4 require 4 of it, and Roadmap 2026 8. A Boolean limit's minimum is 1, `VK_TRUE`; 1.4 require 4 of it, and Roadmap 2026 8.
`timestampValidBits` is the queue family's. No `maxPushConstantsSize` is asked: the push window, and A Boolean limit's minimum is 1,
the pipeline layout's one push range, is the device's `maxPushConstantsSize` up to 256 bytes `VK_TRUE`; `timestampValidBits` is the queue family's. No `maxPushConstantsSize` is asked: the
(`metal2vulkan::device::DeviceProfile::push_window`), at least Vulkan's least, 128, and a function's push window, and the pipeline layout's one push range, is the device's `maxPushConstantsSize` up to
fields past it go to a parameter block whose address the window holds. On a device below 256 an 256 bytes (`metal2vulkan::device::DeviceProfile::push_window`), at least Vulkan's least, 128, and a
indirect command reaches fewer vertex slots (Known gaps of indirect command buffers). function's fields past it go to a parameter block whose address the window holds. On a device
below 256 an indirect command reaches fewer vertex slots (Known gaps of indirect command buffers).
| Limit | Minimum | Used for | | Limit | Minimum | Used for |
|---|---|---| |---|---|---|
| `maxPerStageDescriptorUpdateAfterBindSampledImages` | `196608` | the sampled-texture array with its second elements, and the read texture-buffer array | | `maxPerStageDescriptorUpdateAfterBindSampledImages` | `131072` | the sampled-texture and read texture-buffer arrays |
| `maxDescriptorSetUpdateAfterBindSampledImages` | `196608` | the sampled-texture array with its second elements, and the read texture-buffer array | | `maxDescriptorSetUpdateAfterBindSampledImages` | `131072` | the sampled-texture and read texture-buffer arrays |
| `maxPerStageDescriptorUpdateAfterBindStorageImages` | `196608` | the storage-texture array with its level elements, and the written texture-buffer array | | `maxPerStageDescriptorUpdateAfterBindStorageImages` | `196608` | the storage-texture array with its level elements, and the written texture-buffer array |
| `maxDescriptorSetUpdateAfterBindStorageImages` | `196608` | the storage-texture array with its level elements, and the written texture-buffer array | | `maxDescriptorSetUpdateAfterBindStorageImages` | `196608` | the storage-texture array with its level elements, and the written texture-buffer array |
| `maxPerStageDescriptorUpdateAfterBindSamplers` | `24000` | the three sampler arrays; the lab's least is 500,000 | | `maxPerStageDescriptorUpdateAfterBindSamplers` | `24000` | the three sampler arrays; the lab's least is 500,000 |
| `maxDescriptorSetUpdateAfterBindSamplers` | `24000` | the three sampler arrays; the lab's least is 500,000 | | `maxDescriptorSetUpdateAfterBindSamplers` | `24000` | the three sampler arrays; the lab's least is 500,000 |
| `maxSamplerAllocationCount` | `4000` | Vulkan's minimum: live samplers | | `maxSamplerAllocationCount` | `4000` | Vulkan's minimum: live samplers |
| `maxPerStageUpdateAfterBindResources` | `393216` | the four texture and texture-buffer arrays, the second and level elements among them, in one stage; a fragment stage needs its `maxColorAttachments` more | | `maxPerStageUpdateAfterBindResources` | `327680` | the four texture and texture-buffer arrays, the level elements among them, in one stage; a fragment stage needs its `maxColorAttachments` more |
| `maxUpdateAfterBindDescriptorsInAllPools` | `417216` | all seven arrays; the lab's least is 1,048,576 | | `maxUpdateAfterBindDescriptorsInAllPools` | `351680` | all seven arrays; the lab's least is 1,048,576 |
| `maxComputeWorkGroupInvocations` | `1024` | Metal's most threads per threadgroup | | `maxComputeWorkGroupInvocations` | `1024` | Metal's most threads per threadgroup |
| `maxComputeWorkGroupSize[0]` | `1024` | a threadgroup's width | | `maxComputeWorkGroupSize[0]` | `1024` | a threadgroup's width |
| `maxComputeWorkGroupSize[1]` | `1024` | a threadgroup's height | | `maxComputeWorkGroupSize[1]` | `1024` | a threadgroup's height |
@@ -7026,14 +6793,19 @@ blocks), and only that call makes a sparse buffer. Elsewhere the call refuses.
### Attachment reads ### Attachment reads
A draw that reads, through a texture, an attachment its own pass renders (Metal's read of a render A draw that reads, through a texture, an attachment its own pass renders (Metal's read of a
target) is built on every device: the floor's limits above hold the sampled-texture array's second render target) is built where the device's descriptor limits hold the sampled-texture array's
elements (`floor::Capabilities::attachment_reads` is always true). The draw reads through the second elements beside the floor's arrays: 65,536 sampled images more than the limits above name
attachment feedback loop where the device also lists the extension marked "with the feedback loop" (`maxPerStageDescriptorUpdateAfterBindSampledImages`,
above and reports the feature below, which device creation then enables, and neither otherwise `maxDescriptorSetUpdateAfterBindSampledImages`, `maxPerStageUpdateAfterBindResources` and
(`floor::Capabilities::feedback_loop`). A device that reads attachments without them reads through a `maxUpdateAfterBindDescriptorsInAllPools`); a device without them refuses such a draw
copy of the image into its shadow (Render encoders), a known gap. AMD's Windows driver is expected (`Gap::Draw` of `DrawKind::AttachmentRead`), and is otherwise the same
to take the loop, not verified in the lab (public reports of it list (`floor::Capabilities::attachment_reads`). The draw reads through the attachment feedback loop
where the device also lists the extension marked "with the feedback loop" above and reports the
feature below, which device creation then enables, and neither otherwise
(`floor::Capabilities::feedback_loop`). A device that reads attachments without them reads
through a copy of the image into its shadow (Render encoders), a known gap. AMD's Windows driver
is expected to take the loop, not verified in the lab (public reports of it list
`VK_EXT_attachment_feedback_loop_layout` from 2.0.250 on). `VK_EXT_attachment_feedback_loop_layout` from 2.0.250 on).
| Attachment-read feature | Structure | Used for | | Attachment-read feature | Structure | Used for |
@@ -7185,37 +6957,6 @@ covers them all. This was read in the release's source, not reproduced in the la
|---|---|---| |---|---|---|
| `extendedDynamicState` | `VkPhysicalDeviceExtendedDynamicStateFeaturesEXT` | no state of the runtime's; RADV 26.3.1's cache of fragment epilogs, which a depth or stencil output under a dynamic test enable draws through | | `extendedDynamicState` | `VkPhysicalDeviceExtendedDynamicStateFeaturesEXT` | no state of the runtime's; RADV 26.3.1's cache of fragment epilogs, which a depth or stencil output under a dynamic test enable draws through |
### Mesh stages
Where the device lists `VK_EXT_mesh_shader` and reports all three features below, device creation
enables the extension and the three, and none of them otherwise (`floor::MESH_EXTENSIONS`). An
object function is a task shader and a mesh function a mesh shader, and an object grid past the
task limits runs in pieces of one multi-draw, so a device that lacks any one of the three takes no
mesh render pipeline state: the translator refuses it, `Unsupported{MeshShading}` naming what the
device lacks. No answer chooses a second form.
| Mesh-stage feature | Structure | Used for |
|---|---|---|
| `taskShader` | `VkPhysicalDeviceMeshShaderFeaturesEXT` | an object function, as a task shader |
| `meshShader` | `VkPhysicalDeviceMeshShaderFeaturesEXT` | a mesh function, as a mesh shader |
| `multiDrawIndirect` | `VkPhysicalDeviceFeatures` | an object grid past the task stage's limits, drawn as pieces of one multi-draw of host-written records |
Of the venues run, four list no `VK_EXT_mesh_shader`, so a mesh render pipeline state is refused
there (vulkaninfo on each): the Radeon RX 550 (RADV, Mesa 26.2.6), the Iris Xe (ANV, Mesa 26.2.6),
and the M3 Max under KosmicKrisp (Mesa 26.3.1) and under MoltenVK (1.4.2). The others list it with
all three features, under these limits (vulkaninfo on each):
| Card (driver) | `maxTaskWorkGroupCount`; total | Task invocations and width | Mesh invocations and width | `maxTaskPayloadAndSharedMemorySize` |
|---|---|---|---|---|
| RTX 3090, RTX 2080 (NVIDIA 620.70.06); RTX 5080 Laptop (NVIDIA 615.71.09) | (4,194,304, 65,535, 65,535); 4,194,304 | 128 | 128 | 32,768 |
| RX 7900 XTX, Radeon 780M (RADV, Mesa 26.2.6) | (65,535, 65,535, 65,535); 4,194,304 | 1,024 | 256 | 65,536 |
| lavapipe (Mesa 26.2.4 and 26.2.6) | (65,536, 65,536, 65,536); 4,194,304 | 1,024 | 1,024 | 32,768 |
A stage's thread maximum is Metal's capped by its invocations and width, so on the NVIDIA cards a
state answers at most 128 for each stage where Metal answers up to 1,024, and a draw of a larger
threadgroup is `Limit::MeshThreadgroupThreads`; on the AMD cards the mesh stage's cap is 256. An
object grid past the task count or total is drawn in pieces (Known gaps of render pipeline states).
### Not enabled ### Not enabled
The translator's profile reads each feature below where a device enables it, and device creation The translator's profile reads each feature below where a device enables it, and device creation
+41 -30
View File
@@ -32,7 +32,8 @@
//! face: the translator samples the cube view there at the texel's centre and the read's level //! face: the translator samples the cube view there at the texel's centre and the read's level
//! (docs/RESOURCE-ID.md). The device writes every element once at creation ([`Arrays::new`]). //! (docs/RESOURCE-ID.md). The device writes every element once at creation ([`Arrays::new`]).
//! //!
//! The sampled-texture array holds 131,072 elements. Element `i + 65,536` is texture `i`'s second //! Where the device reads attachments through textures (`floor::Capabilities::attachment_reads`),
//! the sampled-texture array is twice as long: element `i + 65,536` is texture `i`'s second
//! element, which a draw pushes in place of the texture's own while it reads an attachment of its //! element, which a draw pushes in place of the texture's own while it reads an attachment of its
//! pass through the texture (`crate::render_encoder`). Through the attachment feedback loop it is //! pass through the texture (`crate::render_encoder`). Through the attachment feedback loop it is
//! the texture's sampled view in the feedback layout, written with element `i` for a texture whose //! the texture's sampled view in the feedback layout, written with element `i` for a texture whose
@@ -78,13 +79,6 @@ pub(crate) const UNIFORM_TEXELS_BINDING: u32 = 5;
/// The binding of the storage texel-buffer array: the texture buffers shaders write. /// The binding of the storage texel-buffer array: the texture buffers shaders write.
pub(crate) const STORAGE_TEXELS_BINDING: u32 = 6; pub(crate) const STORAGE_TEXELS_BINDING: u32 = 6;
/// The elements of the sampled-texture array: the textures' and their second elements'.
pub(crate) const SAMPLED_ELEMENTS: u32 = 2 * TEXTURES;
/// The element list of an index's every element at its array's default.
const DEFAULTS: [(usize, Option<vk::Sampler>); SAMPLER_ARRAYS as usize] =
[(0, None), (1, None), (2, None)];
/// Set 1's bindings, each its binding, descriptor type and count: the arrays a kernel's layout /// Set 1's bindings, each its binding, descriptor type and count: the arrays a kernel's layout
/// names under the identity domains, which every pipeline's layout takes from this set. Shaders /// names under the identity domains, which every pipeline's layout takes from this set. Shaders
/// declare the arrays unsized, and the set's layout holds [`layout_counts`] elements: more in the /// declare the arrays unsized, and the set's layout holds [`layout_counts`] elements: more in the
@@ -329,6 +323,8 @@ pub(crate) struct Arrays {
pub(crate) plain: vk::Sampler, pub(crate) plain: vk::Sampler,
/// The default sampler of the comparison array. /// The default sampler of the comparison array.
pub(crate) compare: vk::Sampler, pub(crate) compare: vk::Sampler,
/// Whether the sampled-texture array holds the second elements.
seconds: bool,
pub(crate) grants: Mutex<Grants>, pub(crate) grants: Mutex<Grants>,
/// The sampler each sampler array's element at each index holds, plain, comparison and /// The sampler each sampler array's element at each index holds, plain, comparison and
/// integer texture, as last written: a default, or a sampler the index's owner holds, so a /// integer texture, as last written: a default, or a sampler the index's owner holds, so a
@@ -337,8 +333,9 @@ pub(crate) struct Arrays {
} }
impl Arrays { impl Arrays {
/// Makes set 1 and writes every element its default. With `buffers`, set 0's layout holds a /// Makes set 1 and writes every element its default; with `seconds`, the sampled-texture
/// kernel's storage buffers ([`buffer_bindings`]); without, it is empty. /// array holds the second elements too. With `buffers`, set 0's layout holds a kernel's
/// storage buffers ([`buffer_bindings`]); without, it is empty.
/// ///
/// # Safety /// # Safety
/// ///
@@ -347,11 +344,11 @@ impl Arrays {
pub(crate) unsafe fn new( pub(crate) unsafe fn new(
device: &ash::Device, device: &ash::Device,
counters: &Counters, counters: &Counters,
buffers: bool, (seconds, buffers): (bool, bool),
) -> Result<Arrays, Error> { ) -> Result<Arrays, Error> {
let mut made = Made::default(); let mut made = Made::default();
// SAFETY: the caller's contract; what was made is destroyed where a later step fails. // SAFETY: the caller's contract; what was made is destroyed where a later step fails.
let arrays = unsafe { made.make(device, counters, buffers) }; let arrays = unsafe { made.make(device, counters, (seconds, buffers)) };
if arrays.is_err() { if arrays.is_err() {
// SAFETY: nothing else holds what was made. // SAFETY: nothing else holds what was made.
unsafe { made.destroy(device, counters) }; unsafe { made.destroy(device, counters) };
@@ -419,7 +416,7 @@ impl Arrays {
let storage = storage.or(displaced.then(vk::ImageView::null)); let storage = storage.or(displaced.then(vk::ImageView::null));
let second = match looped { let second = match looped {
Some(view) => Some((view, vk::ImageLayout::ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT)), Some(view) => Some((view, vk::ImageLayout::ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT)),
None => displaced.then(|| { None => (displaced && self.seconds).then(|| {
( (
vk::ImageView::null(), vk::ImageView::null(),
vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
@@ -440,7 +437,7 @@ impl Arrays {
/// another object can be placed there: the uniform texel-buffer array's with `views[0]` and /// another object can be placed there: the uniform texel-buffer array's with `views[0]` and
/// the storage one's with `views[1]`, a null descriptor where a view is null. Where it /// the storage one's with `views[1]`, a null descriptor where a view is null. Where it
/// displaced, it writes the index's texture elements null too (the sampled, the storage, and /// displaced, it writes the index's texture elements null too (the sampled, the storage, and
/// the second), which a texture there may have held. The /// the second where the set holds them), which a texture there may have held. The
/// descriptor-slot gauge rises where no object held the index. Its owner word, which /// descriptor-slot gauge rises where no object held the index. Its owner word, which
/// [`Arrays::vacate_texels`] takes. /// [`Arrays::vacate_texels`] takes.
/// ///
@@ -468,7 +465,8 @@ impl Arrays {
self.write_texels(device, index, views); self.write_texels(device, index, views);
if displaced { if displaced {
let null = vk::ImageView::null(); let null = vk::ImageView::null();
let second = Some((null, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)); let second =
(self.seconds).then_some((null, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL));
self.write_texture(device, index, None, Some(null), second); self.write_texture(device, index, None, Some(null), second);
} }
} }
@@ -774,7 +772,9 @@ impl Arrays {
if grants.vacate(IndexClass::Sampler, index, owner) { if grants.vacate(IndexClass::Sampler, index, owner) {
// SAFETY: the caller's contract; the lock is held, so no object is placed there // SAFETY: the caller's contract; the lock is held, so no object is placed there
// before every element is its default. // before every element is its default.
unsafe { self.write_samplers(device, counters, index, &DEFAULTS) }; unsafe {
self.write_samplers(device, counters, index, &[(0, None), (1, None), (2, None)])
};
counters.fall(Gauge::DescriptorSlots); counters.fall(Gauge::DescriptorSlots);
} }
} }
@@ -819,7 +819,7 @@ impl Arrays {
let mut grants = lock(&self.grants); let mut grants = lock(&self.grants);
// SAFETY: the caller's contract; the lock is held, so no variant is placed there before // SAFETY: the caller's contract; the lock is held, so no variant is placed there before
// every element is its default. // every element is its default.
unsafe { self.write_samplers(device, counters, index, &DEFAULTS) }; unsafe { self.write_samplers(device, counters, index, &[(0, None), (1, None), (2, None)]) };
grants.variants.push(index); grants.variants.push(index);
} }
@@ -993,8 +993,9 @@ impl Made {
&mut self, &mut self,
device: &ash::Device, device: &ash::Device,
counters: &Counters, counters: &Counters,
buffers: bool, (seconds, buffers): (bool, bool),
) -> Result<Arrays, Error> { ) -> Result<Arrays, Error> {
let sampled = sampled_images(seconds);
let bindings = buffer_bindings(); let bindings = buffer_bindings();
let first = vk::DescriptorSetLayoutCreateInfo::default().bindings(if buffers { let first = vk::DescriptorSetLayoutCreateInfo::default().bindings(if buffers {
&bindings[..] &bindings[..]
@@ -1010,7 +1011,7 @@ impl Made {
// SAFETY: the device is live, with the update-after-bind features of each binding's type // SAFETY: the device is live, with the update-after-bind features of each binding's type
// (the floor's). // (the floor's).
let layout = unsafe { let layout = unsafe {
with_arrays_layout(layout_counts(), |info| { with_arrays_layout(layout_counts(seconds), |info| {
supported(device, info, 1)?; supported(device, info, 1)?;
device device
.create_descriptor_set_layout(info, None) .create_descriptor_set_layout(info, None)
@@ -1021,7 +1022,7 @@ impl Made {
let sizes = [ let sizes = [
vk::DescriptorPoolSize { vk::DescriptorPoolSize {
ty: vk::DescriptorType::SAMPLED_IMAGE, ty: vk::DescriptorType::SAMPLED_IMAGE,
descriptor_count: SAMPLED_ELEMENTS, descriptor_count: sampled,
}, },
vk::DescriptorPoolSize { vk::DescriptorPoolSize {
ty: vk::DescriptorType::STORAGE_IMAGE, ty: vk::DescriptorType::STORAGE_IMAGE,
@@ -1077,7 +1078,7 @@ impl Made {
let compare = default(true)?; let compare = default(true)?;
self.compare = Some(compare); self.compare = Some(compare);
// SAFETY: the set is the device's and no command buffer uses it yet. // SAFETY: the set is the device's and no command buffer uses it yet.
unsafe { fill(device, set, plain, compare) }; unsafe { fill(device, set, sampled, plain, compare) };
Ok(Arrays { Ok(Arrays {
first, first,
layout, layout,
@@ -1085,6 +1086,7 @@ impl Made {
set, set,
plain, plain,
compare, compare,
seconds,
grants: Mutex::new(Grants::new()), grants: Mutex::new(Grants::new()),
samplers: Mutex::new( samplers: Mutex::new(
vec![[plain, compare, plain]; SAMPLER_ELEMENTS as usize].into_boxed_slice(), vec![[plain, compare, plain]; SAMPLER_ELEMENTS as usize].into_boxed_slice(),
@@ -1177,12 +1179,12 @@ pub(crate) unsafe fn supported(
} }
/// The elements of each binding of set 1's layout, by [`BINDINGS`]: theirs, the sampled-texture /// The elements of each binding of set 1's layout, by [`BINDINGS`]: theirs, the sampled-texture
/// array's [`SAMPLED_ELEMENTS`], the storage-texture array's level elements past its textures, /// array's [`sampled_images`], the storage-texture array's level elements past its textures, and
/// each sampler array's [`SAMPLER_ELEMENTS`], its variant elements past the [`SAMPLERS`] a /// each sampler array's [`SAMPLER_ELEMENTS`], its variant elements past the [`SAMPLERS`] a
/// pipeline's layout names. /// pipeline's layout names.
pub(crate) fn layout_counts() -> [u32; 7] { pub(crate) fn layout_counts(seconds: bool) -> [u32; 7] {
let mut counts = BINDINGS.map(|(_, _, count)| count); let mut counts = BINDINGS.map(|(_, _, count)| count);
counts[SAMPLED_BINDING as usize] = SAMPLED_ELEMENTS; counts[SAMPLED_BINDING as usize] = sampled_images(seconds);
counts[STORAGE_BINDING as usize] = TEXTURES + LEVEL_ELEMENTS; counts[STORAGE_BINDING as usize] = TEXTURES + LEVEL_ELEMENTS;
for array in 0..SAMPLER_ARRAYS { for array in 0..SAMPLER_ARRAYS {
counts[(FIRST_SAMPLER_BINDING + array) as usize] = SAMPLER_ELEMENTS; counts[(FIRST_SAMPLER_BINDING + array) as usize] = SAMPLER_ELEMENTS;
@@ -1190,25 +1192,34 @@ pub(crate) fn layout_counts() -> [u32; 7] {
counts counts
} }
/// The elements of the sampled-texture array: [`TEXTURES`], twice that with the second elements.
pub(crate) fn sampled_images(seconds: bool) -> u32 {
match seconds {
true => 2 * TEXTURES,
false => TEXTURES,
}
}
/// Writes every element of `set` its default: a null descriptor in each texture and texel-buffer /// Writes every element of `set` its default: a null descriptor in each texture and texel-buffer
/// array, the sampled-texture array's second elements and the storage-texture array's level /// array, the sampled-texture array's `sampled` elements and the storage-texture array's level
/// elements among them, `plain` in the plain and integer-texture sampler arrays and `compare` in /// elements among them, `plain` in the plain and
/// the comparison array. /// integer-texture sampler arrays and `compare` in the comparison array.
/// ///
/// # Safety /// # Safety
/// ///
/// `set` is set 1 of `device`, `nullDescriptor` is enabled, and no other thread writes an element /// `set` is set 1 of `device`, of `sampled` sampled-texture elements, `nullDescriptor` is enabled,
/// of it meanwhile. /// and no other thread writes an element of it meanwhile.
unsafe fn fill( unsafe fn fill(
device: &ash::Device, device: &ash::Device,
set: vk::DescriptorSet, set: vk::DescriptorSet,
sampled: u32,
plain: vk::Sampler, plain: vk::Sampler,
compare: vk::Sampler, compare: vk::Sampler,
) { ) {
let sampled = vec![ let sampled = vec![
vk::DescriptorImageInfo::default() vk::DescriptorImageInfo::default()
.image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL); .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL);
SAMPLED_ELEMENTS as usize sampled as usize
]; ];
let storage = vec![ let storage = vec![
vk::DescriptorImageInfo::default().image_layout(vk::ImageLayout::GENERAL); vk::DescriptorImageInfo::default().image_layout(vk::ImageLayout::GENERAL);
+5 -14
View File
@@ -43,7 +43,7 @@ use crate::copy_out;
use crate::counters::Metric; use crate::counters::Metric;
use crate::device::Core; use crate::device::Core;
use crate::encoder::Resource; use crate::encoder::Resource;
use crate::error::{ChromaPairsGap, Error, Gap, Refusal, TextureBytesCause}; use crate::error::{Error, Gap, Refusal, TextureBytesCause};
use crate::fence::Fence; use crate::fence::Fence;
use crate::hazard::Access; use crate::hazard::Access;
use crate::indirect::{reset_regions, IndirectCommandBuffer}; use crate::indirect::{reset_regions, IndirectCommandBuffer};
@@ -1892,15 +1892,12 @@ impl BufferCopy {
/// ///
/// Metal's validation stops an offset or a row stride of a format of single texels that is no /// Metal's validation stops an offset or a row stride of a format of single texels that is no
/// whole number of its texels, rows or images closer than the region's, and a region past the /// whole number of its texels, rows or images closer than the region's, and a region past the
/// buffer's end ([`Refusal::BufferCopyLayout`]), but takes a `GBGR422` or `BGRG422` region's rows /// buffer's end ([`Refusal::BufferCopyLayout`]). A copy command in the floor further takes an
/// closer than the region's (the conformance case `chroma-pair-copies`, an Apple M3 Max), which /// offset of whole texel blocks, a multiple of 4 for a depth or stencil aspect, for each image,
/// is a gap ([`Gap::ChromaPairsUse`] of [`ChromaPairsGap::CloseRows`]). A copy command in the /// and a row stride of whole blocks ([`Gap::BufferCopyAlignment`]).
/// floor further takes an offset of whole texel blocks, a multiple of 4 for a depth or stencil
/// aspect, for each image, and a row stride of whole blocks ([`Gap::BufferCopyAlignment`]).
/// ///
/// Err: [`Gap::TextureBytes`]; [`Refusal::TextureRegion`]; /// Err: [`Gap::TextureBytes`]; [`Refusal::TextureRegion`];
/// [`Refusal::BufferCopyLayout`]; [`Gap::ChromaPairsUse`]; [`Gap::BufferCopyAlignment`]; /// [`Refusal::BufferCopyLayout`]; [`Gap::BufferCopyAlignment`]; [`Refusal::AliasingCopy`].
/// [`Refusal::AliasingCopy`].
pub(crate) fn buffer_copy( pub(crate) fn buffer_copy(
texture: &Side<'_>, texture: &Side<'_>,
at: TexturePlace, at: TexturePlace,
@@ -1964,14 +1961,8 @@ pub(crate) fn buffer_copy(
if single && (offset % bytes != 0 || (rows > 1 && bytes_per_row % bytes != 0)) { if single && (offset % bytes != 0 || (rows > 1 && bytes_per_row % bytes != 0)) {
return Err(refused()); return Err(refused());
} }
let pairs = matches!(pixel_format, PixelFormat::GBGR422 | PixelFormat::BGRG422);
let image_span = match rows { let image_span = match rows {
1 => Some(row), 1 => Some(row),
_ if bytes_per_row < row && pairs => {
return Err(Error::Unsupported(Gap::ChromaPairsUse {
cause: ChromaPairsGap::CloseRows,
}));
}
_ if bytes_per_row < row => return Err(refused()), _ if bytes_per_row < row => return Err(refused()),
_ => (rows - 1) _ => (rows - 1)
.checked_mul(bytes_per_row) .checked_mul(bytes_per_row)
+6
View File
@@ -59,6 +59,12 @@ impl Block {
Block { claim } Block { claim }
} }
/// Returns capture/replay address metadata for this block (if supported).
pub fn capture_info(&self) -> Option<memory::BlockCaptureInfo> {
let (core, block) = self.held().ok()?;
core.pool.capture_info(&block.memory)
}
/// Whether the block is of `core`'s device. /// Whether the block is of `core`'s device.
pub(crate) fn is_of(&self, core: &Arc<Core>) -> bool { pub(crate) fn is_of(&self, core: &Arc<Core>) -> bool {
Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core) Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core)
+5 -10
View File
@@ -353,10 +353,6 @@ pub(crate) struct Gpu {
/// A texture over a Managed buffer's device copy in an image of its own is kept: the submit /// A texture over a Managed buffer's device copy in an image of its own is kept: the submit
/// thread looks for the copies in it owes (`crate::over::ManagedOvers`). /// thread looks for the copies in it owes (`crate::over::ManagedOvers`).
pub(crate) managed: bool, pub(crate) managed: bool,
/// It has nothing for the GPU ([`is_empty`](Self::is_empty)) and took a Managed buffer's
/// copy-in (`crate::capture`), which is then its submission: set by the submit thread as its
/// group goes. The copy's GPU run is the runtime's own, so its stages count none ([`retire`]).
pub(crate) copy_in_only: bool,
/// The images of released textures whose copies back the commands make, kept until the /// The images of released textures whose copies back the commands make, kept until the
/// command buffer retires. /// command buffer retires.
pub(crate) images: Vec<Arc<Image>>, pub(crate) images: Vec<Arc<Image>>,
@@ -508,7 +504,6 @@ impl CommandBuffer {
kept, kept,
ring: Writes::default(), ring: Writes::default(),
managed: false, managed: false,
copy_in_only: false,
images: Vec::new(), images: Vec::new(),
fences: Fences::default(), fences: Fences::default(),
executed: Vec::new(), executed: Vec::new(),
@@ -1634,6 +1629,10 @@ impl Building {
self.tally.count(metric); self.tally.count(metric);
} }
pub(crate) fn count_by(&mut self, metric: Metric, count: u64) {
self.tally.count_by(metric, count);
}
/// Copies `bytes` into the parameter ring, returning their address. /// Copies `bytes` into the parameter ring, returning their address.
pub(crate) fn write_ring(&mut self, bytes: &[u8]) -> Result<u64, Error> { pub(crate) fn write_ring(&mut self, bytes: &[u8]) -> Result<u64, Error> {
Ok(self.write_ring_placed(bytes)?.address) Ok(self.write_ring_placed(bytes)?.address)
@@ -2125,10 +2124,7 @@ pub(crate) fn retire(
state.times.gpu_end = end; state.times.gpu_end = end;
inner.queue.last_end.fetch_max(end, Relaxed); inner.queue.last_end.fetch_max(end, Relaxed);
} }
// One whose submission was a copy-in it took counts no stages: the copy's GPU run is the let stages = (gpu_times.filter(|_| error.is_none()))
// runtime's own (`Metrics::runtime_command_buffer_gpu_nanos`), and its handlers wait for
// that run, not for a GPU end of its own.
let stages = (gpu_times.filter(|_| error.is_none() && !gpu.copy_in_only))
.map(|(start, end)| (state.times.kernel_end, start, end)); .map(|(start, end)| (state.times.kernel_end, start, end));
state.status = match error { state.status = match error {
Some(_) => CommandBufferStatus::Error, Some(_) => CommandBufferStatus::Error,
@@ -2145,7 +2141,6 @@ pub(crate) fn retire(
mut kept, mut kept,
ring, ring,
managed: _, managed: _,
copy_in_only: _,
images, images,
fences, fences,
executed, executed,
+13 -24
View File
@@ -170,47 +170,36 @@ impl Done {
/// Waits until the progress semaphore reaches `value`, a value [`Work::flush`] gave: once /// Waits until the progress semaphore reaches `value`, a value [`Work::flush`] gave: once
/// what that batch carries has completed. /// what that batch carries has completed.
/// ///
/// `vkWaitSemaphores` fails with `VK_ERROR_DEVICE_LOST`, or for want of memory or with
/// `VK_ERROR_UNKNOWN`, which say nothing of the batch: it stays pending, and what it carries
/// may still write after the call returns. Such a call is made again ([`wait_through`]) until
/// it succeeds or the device is lost, so no caller returns while that batch may still run on
/// a live device: a restoring make's write-back of the host's bytes among them
/// (`crate::texture`). A lasting failure on a live device so waits.
///
/// Err: [`Error::Vulkan`] (`VK_ERROR_DEVICE_LOST`) where the device is lost first. /// Err: [`Error::Vulkan`] (`VK_ERROR_DEVICE_LOST`) where the device is lost first.
/// ///
/// [`Work::flush`]: crate::submit::Work::flush /// [`Work::flush`]: crate::submit::Work::flush
pub(crate) fn wait(&self, core: &Core, value: u64) -> Result<(), Error> { pub(crate) fn wait(&self, core: &Core, value: u64) -> Result<(), Error> {
let lost = Error::Vulkan {
call: "vkWaitSemaphores",
result: vk::Result::ERROR_DEVICE_LOST,
};
let semaphores = [self.progress]; let semaphores = [self.progress];
let values = [value]; let values = [value];
let wait = vk::SemaphoreWaitInfo::default() let wait = vk::SemaphoreWaitInfo::default()
.semaphores(&semaphores) .semaphores(&semaphores)
.values(&values); .values(&values);
let mut reached = false; loop {
wait_through(core, || loop {
// SAFETY: the progress semaphore is the device's, live while the core is. // SAFETY: the progress semaphore is the device's, live while the core is.
match unsafe { match unsafe {
core.device core.device
.wait_semaphores(&wait, LOSS_POLL.as_nanos() as u64) .wait_semaphores(&wait, LOSS_POLL.as_nanos() as u64)
} { } {
Ok(()) => { Ok(()) => return Ok(()),
reached = true;
return Ok(());
}
// A lost device's pending batches never signal: the work side ends them. // A lost device's pending batches never signal: the work side ends them.
Err(vk::Result::TIMEOUT) if core.work.lock().lost() => { Err(vk::Result::TIMEOUT) if core.work.lock().lost() => return Err(lost),
return Err(vk::Result::ERROR_DEVICE_LOST)
}
Err(vk::Result::TIMEOUT) => {} Err(vk::Result::TIMEOUT) => {}
Err(result) => return Err(result), Err(result) => {
return Err(Error::Vulkan {
call: "vkWaitSemaphores",
result,
})
}
} }
});
match reached {
true => Ok(()),
false => Err(Error::Vulkan {
call: "vkWaitSemaphores",
result: vk::Result::ERROR_DEVICE_LOST,
}),
} }
} }
+43 -188
View File
@@ -4,7 +4,6 @@
//! to its own; nothing turns them on or off. //! to its own; nothing turns them on or off.
use crate::pipeline::DispatchVariant; use crate::pipeline::DispatchVariant;
use crate::shadow::Copied;
use crate::{MemoryClass, PixelFormat, TextureUsage}; use crate::{MemoryClass, PixelFormat, TextureUsage};
use std::collections::VecDeque; use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
@@ -278,8 +277,6 @@ pub(crate) enum Metric {
RenderRecordsStale, RenderRecordsStale,
/// [`Metrics::word_contents`]. /// [`Metrics::word_contents`].
WordContents, WordContents,
/// [`Metrics::depth_range_twins`].
DepthRangeTwins,
/// [`Metrics::creations_before_seed`]. /// [`Metrics::creations_before_seed`].
CreationsBeforeSeed, CreationsBeforeSeed,
/// [`Metrics::cache_writes_dropped`]. /// [`Metrics::cache_writes_dropped`].
@@ -292,6 +289,10 @@ pub(crate) enum Metric {
PipelineCacheWritesSkipped, PipelineCacheWritesSkipped,
/// [`Metrics::ring_writes`]. /// [`Metrics::ring_writes`].
RingWrites, RingWrites,
/// [`Metrics::multi_draw_calls`].
MultiDrawCalls,
/// [`Metrics::multi_draw_items`].
MultiDrawItems,
/// [`Metrics::pushes`]. /// [`Metrics::pushes`].
Pushes, Pushes,
/// [`Metrics::pushes_held`]. /// [`Metrics::pushes_held`].
@@ -336,10 +337,6 @@ pub(crate) enum Metric {
SurfacesCopied, SurfacesCopied,
/// [`Metrics::textures_in_place_over_imports`]. /// [`Metrics::textures_in_place_over_imports`].
TexturesInPlaceOverImports, TexturesInPlaceOverImports,
/// [`Metrics::chroma_contents`].
ChromaContents,
/// [`Metrics::chroma_launches`].
ChromaLaunches,
/// [`Metrics::exported_blocks_addressed`]. /// [`Metrics::exported_blocks_addressed`].
ExportedBlocksAddressed, ExportedBlocksAddressed,
/// [`Metrics::texture_clear_barriers`]. /// [`Metrics::texture_clear_barriers`].
@@ -372,18 +369,10 @@ pub(crate) enum Metric {
SampleInterpolatingStates, SampleInterpolatingStates,
/// [`Metrics::rendering_interrupts`]. /// [`Metrics::rendering_interrupts`].
RenderingInterrupts, RenderingInterrupts,
/// [`Metrics::mesh_threadgroups_past_device`].
MeshThreadgroupsPastDevice,
/// [`Metrics::mesh_draws_launched`].
MeshDrawsLaunched,
/// [`Metrics::mesh_object_grids_whole`].
MeshObjectGridsWhole,
/// [`Metrics::mesh_object_grids_in_pieces`].
MeshObjectGridsInPieces,
} }
/// The number of [`Metric`]s. /// The number of [`Metric`]s.
const METRICS: usize = Metric::MeshObjectGridsInPieces as usize + 1; const METRICS: usize = Metric::RenderingInterrupts as usize + 1;
/// Every [`Metric`], in its order: each at its own index. /// Every [`Metric`], in its order: each at its own index.
const METRIC_ORDER: [Metric; METRICS] = [ const METRIC_ORDER: [Metric; METRICS] = [
@@ -420,13 +409,14 @@ const METRIC_ORDER: [Metric; METRICS] = [
Metric::RenderRecordsRead, Metric::RenderRecordsRead,
Metric::RenderRecordsStale, Metric::RenderRecordsStale,
Metric::WordContents, Metric::WordContents,
Metric::DepthRangeTwins,
Metric::CreationsBeforeSeed, Metric::CreationsBeforeSeed,
Metric::CacheWritesDropped, Metric::CacheWritesDropped,
Metric::PipelineCachesReplaced, Metric::PipelineCachesReplaced,
Metric::KernelMakesDropped, Metric::KernelMakesDropped,
Metric::PipelineCacheWritesSkipped, Metric::PipelineCacheWritesSkipped,
Metric::RingWrites, Metric::RingWrites,
Metric::MultiDrawCalls,
Metric::MultiDrawItems,
Metric::Pushes, Metric::Pushes,
Metric::PushesHeld, Metric::PushesHeld,
Metric::BoundDispatches, Metric::BoundDispatches,
@@ -449,8 +439,6 @@ const METRIC_ORDER: [Metric; METRICS] = [
Metric::SurfacesInPlace, Metric::SurfacesInPlace,
Metric::SurfacesCopied, Metric::SurfacesCopied,
Metric::TexturesInPlaceOverImports, Metric::TexturesInPlaceOverImports,
Metric::ChromaContents,
Metric::ChromaLaunches,
Metric::ExportedBlocksAddressed, Metric::ExportedBlocksAddressed,
Metric::TextureClearBarriers, Metric::TextureClearBarriers,
Metric::AttachmentLoopReads, Metric::AttachmentLoopReads,
@@ -467,10 +455,6 @@ const METRIC_ORDER: [Metric; METRICS] = [
Metric::SampleCopies, Metric::SampleCopies,
Metric::SampleInterpolatingStates, Metric::SampleInterpolatingStates,
Metric::RenderingInterrupts, Metric::RenderingInterrupts,
Metric::MeshThreadgroupsPastDevice,
Metric::MeshDrawsLaunched,
Metric::MeshObjectGridsWhole,
Metric::MeshObjectGridsInPieces,
]; ];
// Each metric of the order is at its own index. // Each metric of the order is at its own index.
@@ -506,7 +490,11 @@ impl Default for Tally {
impl Tally { impl Tally {
/// Counts one more of `metric`. /// Counts one more of `metric`.
pub(crate) fn count(&mut self, metric: Metric) { pub(crate) fn count(&mut self, metric: Metric) {
self.counts[metric as usize] += 1; self.count_by(metric, 1);
}
pub(crate) fn count_by(&mut self, metric: Metric, count: u64) {
self.counts[metric as usize] += count;
self.counted |= 1 << metric as usize; self.counted |= 1 << metric as usize;
} }
} }
@@ -538,8 +526,6 @@ pub(crate) enum Gauge {
WordPipelines, WordPipelines,
/// [`Gauges::word_texture_buffers`]. /// [`Gauges::word_texture_buffers`].
WordTextureBuffers, WordTextureBuffers,
/// [`Gauges::chroma_textures`].
ChromaTextures,
/// [`Gauges::kernel_entries`]. /// [`Gauges::kernel_entries`].
KernelEntries, KernelEntries,
/// [`Gauges::render_contents`]. /// [`Gauges::render_contents`].
@@ -886,7 +872,6 @@ struct Atomics {
partial_variant_whole_grids: AtomicU64, partial_variant_whole_grids: AtomicU64,
partial_variant_ragged_grids: AtomicU64, partial_variant_ragged_grids: AtomicU64,
translations_at_encode: AtomicU64, translations_at_encode: AtomicU64,
translation_at_encode_nanos: AtomicU64,
translation_at_encode_max_nanos: AtomicU64, translation_at_encode_max_nanos: AtomicU64,
extended_view_dispatches: AtomicU64, extended_view_dispatches: AtomicU64,
level_field_commands: AtomicU64, level_field_commands: AtomicU64,
@@ -902,7 +887,6 @@ struct Atomics {
render_records_read: AtomicU64, render_records_read: AtomicU64,
render_records_stale: AtomicU64, render_records_stale: AtomicU64,
word_contents: AtomicU64, word_contents: AtomicU64,
depth_range_twins: AtomicU64,
creations_before_seed: AtomicU64, creations_before_seed: AtomicU64,
pipeline_cache_looks_skipped: AtomicU64, pipeline_cache_looks_skipped: AtomicU64,
pipeline_cache_lock_waits: AtomicU64, pipeline_cache_lock_waits: AtomicU64,
@@ -913,6 +897,8 @@ struct Atomics {
kernel_makes_dropped: AtomicU64, kernel_makes_dropped: AtomicU64,
pipeline_cache_writes_skipped: AtomicU64, pipeline_cache_writes_skipped: AtomicU64,
ring_writes: AtomicU64, ring_writes: AtomicU64,
multi_draw_calls: AtomicU64,
multi_draw_items: AtomicU64,
pushes: AtomicU64, pushes: AtomicU64,
pushes_held: AtomicU64, pushes_held: AtomicU64,
bound_dispatches: AtomicU64, bound_dispatches: AtomicU64,
@@ -939,11 +925,6 @@ struct Atomics {
over_unkept_by_cause: [AtomicU64; OVER_CAUSES], over_unkept_by_cause: [AtomicU64; OVER_CAUSES],
attachment_read_copies: AtomicU64, attachment_read_copies: AtomicU64,
attachment_read_copy_bytes: AtomicU64, attachment_read_copy_bytes: AtomicU64,
attachment_read_copy_bytes_own_pixel: AtomicU64,
attachment_read_copy_bytes_whole_texture: AtomicU64,
attachment_read_copy_bytes_first_in_pass: AtomicU64,
attachment_read_copy_bytes_after_barrier: AtomicU64,
attachment_read_copy_bytes_beyond_held: AtomicU64,
resolve_copies: AtomicU64, resolve_copies: AtomicU64,
resolve_copy_bytes: AtomicU64, resolve_copy_bytes: AtomicU64,
plane_copies_in: AtomicU64, plane_copies_in: AtomicU64,
@@ -976,8 +957,6 @@ struct Atomics {
surfaces_in_place: AtomicU64, surfaces_in_place: AtomicU64,
surfaces_copied: AtomicU64, surfaces_copied: AtomicU64,
textures_in_place_over_imports: AtomicU64, textures_in_place_over_imports: AtomicU64,
chroma_contents: AtomicU64,
chroma_launches: AtomicU64,
exported_blocks_addressed: AtomicU64, exported_blocks_addressed: AtomicU64,
surface_waits: AtomicU64, surface_waits: AtomicU64,
surface_wait_nanos: AtomicU64, surface_wait_nanos: AtomicU64,
@@ -1003,10 +982,6 @@ struct Atomics {
sample_copies: AtomicU64, sample_copies: AtomicU64,
sample_interpolating_states: AtomicU64, sample_interpolating_states: AtomicU64,
rendering_interrupts: AtomicU64, rendering_interrupts: AtomicU64,
mesh_threadgroups_past_device: AtomicU64,
mesh_draws_launched: AtomicU64,
mesh_object_grids_whole: AtomicU64,
mesh_object_grids_in_pieces: AtomicU64,
/// Each [`Part`]'s calls, at its index: their count, bytes, total and longest nanoseconds, /// Each [`Part`]'s calls, at its index: their count, bytes, total and longest nanoseconds,
/// and those over each of [`OVER_NANOS`]. /// and those over each of [`OVER_NANOS`].
parts: [[AtomicU64; 7]; PARTS], parts: [[AtomicU64; 7]; PARTS],
@@ -1023,7 +998,6 @@ struct Atomics {
kernel_variants: AtomicU64, kernel_variants: AtomicU64,
word_pipelines: AtomicU64, word_pipelines: AtomicU64,
word_texture_buffers: AtomicU64, word_texture_buffers: AtomicU64,
chroma_textures: AtomicU64,
kernel_entries: AtomicU64, kernel_entries: AtomicU64,
render_contents: AtomicU64, render_contents: AtomicU64,
attachment_views: AtomicU64, attachment_views: AtomicU64,
@@ -1187,13 +1161,14 @@ impl Counters {
Metric::RenderRecordsRead => &a.render_records_read, Metric::RenderRecordsRead => &a.render_records_read,
Metric::RenderRecordsStale => &a.render_records_stale, Metric::RenderRecordsStale => &a.render_records_stale,
Metric::WordContents => &a.word_contents, Metric::WordContents => &a.word_contents,
Metric::DepthRangeTwins => &a.depth_range_twins,
Metric::CreationsBeforeSeed => &a.creations_before_seed, Metric::CreationsBeforeSeed => &a.creations_before_seed,
Metric::CacheWritesDropped => &a.cache_writes_dropped, Metric::CacheWritesDropped => &a.cache_writes_dropped,
Metric::PipelineCachesReplaced => &a.pipeline_caches_replaced, Metric::PipelineCachesReplaced => &a.pipeline_caches_replaced,
Metric::KernelMakesDropped => &a.kernel_makes_dropped, Metric::KernelMakesDropped => &a.kernel_makes_dropped,
Metric::PipelineCacheWritesSkipped => &a.pipeline_cache_writes_skipped, Metric::PipelineCacheWritesSkipped => &a.pipeline_cache_writes_skipped,
Metric::RingWrites => &a.ring_writes, Metric::RingWrites => &a.ring_writes,
Metric::MultiDrawCalls => &a.multi_draw_calls,
Metric::MultiDrawItems => &a.multi_draw_items,
Metric::Pushes => &a.pushes, Metric::Pushes => &a.pushes,
Metric::PushesHeld => &a.pushes_held, Metric::PushesHeld => &a.pushes_held,
Metric::BoundDispatches => &a.bound_dispatches, Metric::BoundDispatches => &a.bound_dispatches,
@@ -1216,8 +1191,6 @@ impl Counters {
Metric::SurfacesInPlace => &a.surfaces_in_place, Metric::SurfacesInPlace => &a.surfaces_in_place,
Metric::SurfacesCopied => &a.surfaces_copied, Metric::SurfacesCopied => &a.surfaces_copied,
Metric::TexturesInPlaceOverImports => &a.textures_in_place_over_imports, Metric::TexturesInPlaceOverImports => &a.textures_in_place_over_imports,
Metric::ChromaContents => &a.chroma_contents,
Metric::ChromaLaunches => &a.chroma_launches,
Metric::ExportedBlocksAddressed => &a.exported_blocks_addressed, Metric::ExportedBlocksAddressed => &a.exported_blocks_addressed,
Metric::TextureClearBarriers => &a.texture_clear_barriers, Metric::TextureClearBarriers => &a.texture_clear_barriers,
Metric::AttachmentLoopReads => &a.attachment_loop_reads, Metric::AttachmentLoopReads => &a.attachment_loop_reads,
@@ -1234,10 +1207,6 @@ impl Counters {
Metric::SampleCopies => &a.sample_copies, Metric::SampleCopies => &a.sample_copies,
Metric::SampleInterpolatingStates => &a.sample_interpolating_states, Metric::SampleInterpolatingStates => &a.sample_interpolating_states,
Metric::RenderingInterrupts => &a.rendering_interrupts, Metric::RenderingInterrupts => &a.rendering_interrupts,
Metric::MeshThreadgroupsPastDevice => &a.mesh_threadgroups_past_device,
Metric::MeshDrawsLaunched => &a.mesh_draws_launched,
Metric::MeshObjectGridsWhole => &a.mesh_object_grids_whole,
Metric::MeshObjectGridsInPieces => &a.mesh_object_grids_in_pieces,
} }
} }
@@ -1661,12 +1630,10 @@ impl Counters {
answer answer
} }
/// A make at encode that took `nanos` nanoseconds ([`Metrics::translations_at_encode`], /// A make at encode that took `nanos` nanoseconds ([`Metrics::translations_at_encode`]).
/// [`Metrics::translation_at_encode_nanos`]).
pub(crate) fn translation_at_encode(&self, nanos: u64) { pub(crate) fn translation_at_encode(&self, nanos: u64) {
let a = &self.atomics; let a = &self.atomics;
a.translations_at_encode.fetch_add(1, Relaxed); a.translations_at_encode.fetch_add(1, Relaxed);
a.translation_at_encode_nanos.fetch_add(nanos, Relaxed);
a.translation_at_encode_max_nanos.fetch_max(nanos, Relaxed); a.translation_at_encode_max_nanos.fetch_max(nanos, Relaxed);
} }
@@ -1781,26 +1748,14 @@ impl Counters {
kinds.get(from..).unwrap_or_default().to_vec() kinds.get(from..).unwrap_or_default().to_vec()
} }
/// `copies` more copies of attachments' images into their shadows, of `copied`'s bytes /// `copies` more copies of attachments' images into their shadows, of `bytes`
/// ([`Metrics::attachment_read_copies`], [`Metrics::attachment_read_copy_bytes`]), which /// ([`Metrics::attachment_read_copies`], [`Metrics::attachment_read_copy_bytes`]), which
/// count in [`Metrics::bytes_copied`] too, and parted by read and by when they came /// count in [`Metrics::bytes_copied`] too.
/// ([`Metrics::attachment_read_copy_bytes_own_pixel`] and the fields beside it). pub(crate) fn attachment_read_copied(&self, copies: u64, bytes: u64) {
pub(crate) fn attachment_read_copied(&self, copies: u64, copied: &Copied) {
let a = &self.atomics; let a = &self.atomics;
let bytes = copied.bytes();
a.attachment_read_copies.fetch_add(copies, Relaxed); a.attachment_read_copies.fetch_add(copies, Relaxed);
a.attachment_read_copy_bytes.fetch_add(bytes, Relaxed); a.attachment_read_copy_bytes.fetch_add(bytes, Relaxed);
a.bytes_copied.fetch_add(bytes, Relaxed); a.bytes_copied.fetch_add(bytes, Relaxed);
a.attachment_read_copy_bytes_own_pixel
.fetch_add(copied.own_pixel, Relaxed);
a.attachment_read_copy_bytes_whole_texture
.fetch_add(copied.whole_texture, Relaxed);
a.attachment_read_copy_bytes_first_in_pass
.fetch_add(copied.first_in_pass, Relaxed);
a.attachment_read_copy_bytes_after_barrier
.fetch_add(copied.after_barrier, Relaxed);
a.attachment_read_copy_bytes_beyond_held
.fetch_add(copied.beyond_held, Relaxed);
} }
/// A copy between a marked surface plane and its stand-in, of `bytes`, into the stand-in /// A copy between a marked surface plane and its stand-in, of `bytes`, into the stand-in
@@ -2056,7 +2011,6 @@ impl Counters {
Gauge::KernelVariants => &a.kernel_variants, Gauge::KernelVariants => &a.kernel_variants,
Gauge::WordPipelines => &a.word_pipelines, Gauge::WordPipelines => &a.word_pipelines,
Gauge::WordTextureBuffers => &a.word_texture_buffers, Gauge::WordTextureBuffers => &a.word_texture_buffers,
Gauge::ChromaTextures => &a.chroma_textures,
Gauge::KernelEntries => &a.kernel_entries, Gauge::KernelEntries => &a.kernel_entries,
Gauge::RenderContents => &a.render_contents, Gauge::RenderContents => &a.render_contents,
Gauge::AttachmentViews => &a.attachment_views, Gauge::AttachmentViews => &a.attachment_views,
@@ -2318,7 +2272,6 @@ impl Counters {
partial_variant_whole_grids: a.partial_variant_whole_grids.load(Relaxed), partial_variant_whole_grids: a.partial_variant_whole_grids.load(Relaxed),
partial_variant_ragged_grids: a.partial_variant_ragged_grids.load(Relaxed), partial_variant_ragged_grids: a.partial_variant_ragged_grids.load(Relaxed),
translations_at_encode: a.translations_at_encode.load(Relaxed), translations_at_encode: a.translations_at_encode.load(Relaxed),
translation_at_encode_nanos: a.translation_at_encode_nanos.load(Relaxed),
translation_at_encode_max_nanos: a.translation_at_encode_max_nanos.load(Relaxed), translation_at_encode_max_nanos: a.translation_at_encode_max_nanos.load(Relaxed),
extended_view_dispatches: a.extended_view_dispatches.load(Relaxed), extended_view_dispatches: a.extended_view_dispatches.load(Relaxed),
level_field_commands: a.level_field_commands.load(Relaxed), level_field_commands: a.level_field_commands.load(Relaxed),
@@ -2329,7 +2282,6 @@ impl Counters {
render_records_read: a.render_records_read.load(Relaxed), render_records_read: a.render_records_read.load(Relaxed),
render_records_stale: a.render_records_stale.load(Relaxed), render_records_stale: a.render_records_stale.load(Relaxed),
word_contents: a.word_contents.load(Relaxed), word_contents: a.word_contents.load(Relaxed),
depth_range_twins: a.depth_range_twins.load(Relaxed),
creations_before_seed: a.creations_before_seed.load(Relaxed), creations_before_seed: a.creations_before_seed.load(Relaxed),
pipeline_cache_looks_skipped: a.pipeline_cache_looks_skipped.load(Relaxed), pipeline_cache_looks_skipped: a.pipeline_cache_looks_skipped.load(Relaxed),
pipeline_cache_lock_waits: a.pipeline_cache_lock_waits.load(Relaxed), pipeline_cache_lock_waits: a.pipeline_cache_lock_waits.load(Relaxed),
@@ -2341,6 +2293,8 @@ impl Counters {
pipeline_cache_writes_skipped: a.pipeline_cache_writes_skipped.load(Relaxed), pipeline_cache_writes_skipped: a.pipeline_cache_writes_skipped.load(Relaxed),
cache_bytes_written: a.cache_bytes_written.load(Relaxed), cache_bytes_written: a.cache_bytes_written.load(Relaxed),
ring_writes: a.ring_writes.load(Relaxed), ring_writes: a.ring_writes.load(Relaxed),
multi_draw_calls: a.multi_draw_calls.load(Relaxed),
multi_draw_items: a.multi_draw_items.load(Relaxed),
pushes: a.pushes.load(Relaxed), pushes: a.pushes.load(Relaxed),
pushes_held: a.pushes_held.load(Relaxed), pushes_held: a.pushes_held.load(Relaxed),
bound_dispatches: a.bound_dispatches.load(Relaxed), bound_dispatches: a.bound_dispatches.load(Relaxed),
@@ -2403,21 +2357,6 @@ impl Counters {
over_copies_unkept_kind_image_memory: unkept(OverCause::ImageMemory), over_copies_unkept_kind_image_memory: unkept(OverCause::ImageMemory),
attachment_read_copies: a.attachment_read_copies.load(Relaxed), attachment_read_copies: a.attachment_read_copies.load(Relaxed),
attachment_read_copy_bytes: a.attachment_read_copy_bytes.load(Relaxed), attachment_read_copy_bytes: a.attachment_read_copy_bytes.load(Relaxed),
attachment_read_copy_bytes_own_pixel: a
.attachment_read_copy_bytes_own_pixel
.load(Relaxed),
attachment_read_copy_bytes_whole_texture: a
.attachment_read_copy_bytes_whole_texture
.load(Relaxed),
attachment_read_copy_bytes_first_in_pass: a
.attachment_read_copy_bytes_first_in_pass
.load(Relaxed),
attachment_read_copy_bytes_after_barrier: a
.attachment_read_copy_bytes_after_barrier
.load(Relaxed),
attachment_read_copy_bytes_beyond_held: a
.attachment_read_copy_bytes_beyond_held
.load(Relaxed),
resolve_copies: a.resolve_copies.load(Relaxed), resolve_copies: a.resolve_copies.load(Relaxed),
resolve_copy_bytes: a.resolve_copy_bytes.load(Relaxed), resolve_copy_bytes: a.resolve_copy_bytes.load(Relaxed),
plane_copies_in: a.plane_copies_in.load(Relaxed), plane_copies_in: a.plane_copies_in.load(Relaxed),
@@ -2450,8 +2389,6 @@ impl Counters {
surfaces_in_place: a.surfaces_in_place.load(Relaxed), surfaces_in_place: a.surfaces_in_place.load(Relaxed),
surfaces_copied: a.surfaces_copied.load(Relaxed), surfaces_copied: a.surfaces_copied.load(Relaxed),
textures_in_place_over_imports: a.textures_in_place_over_imports.load(Relaxed), textures_in_place_over_imports: a.textures_in_place_over_imports.load(Relaxed),
chroma_contents: a.chroma_contents.load(Relaxed),
chroma_launches: a.chroma_launches.load(Relaxed),
exported_blocks_addressed: a.exported_blocks_addressed.load(Relaxed), exported_blocks_addressed: a.exported_blocks_addressed.load(Relaxed),
surface_waits: a.surface_waits.load(Relaxed), surface_waits: a.surface_waits.load(Relaxed),
surface_wait_nanos: a.surface_wait_nanos.load(Relaxed), surface_wait_nanos: a.surface_wait_nanos.load(Relaxed),
@@ -2479,10 +2416,6 @@ impl Counters {
sample_copies: a.sample_copies.load(Relaxed), sample_copies: a.sample_copies.load(Relaxed),
sample_interpolating_states: a.sample_interpolating_states.load(Relaxed), sample_interpolating_states: a.sample_interpolating_states.load(Relaxed),
rendering_interrupts: a.rendering_interrupts.load(Relaxed), rendering_interrupts: a.rendering_interrupts.load(Relaxed),
mesh_threadgroups_past_device: a.mesh_threadgroups_past_device.load(Relaxed),
mesh_draws_launched: a.mesh_draws_launched.load(Relaxed),
mesh_object_grids_whole: a.mesh_object_grids_whole.load(Relaxed),
mesh_object_grids_in_pieces: a.mesh_object_grids_in_pieces.load(Relaxed),
takes: part(Part::Take), takes: part(Part::Take),
take_lock_waits: part(Part::TakeLock), take_lock_waits: part(Part::TakeLock),
take_makes: part(Part::TakeMake), take_makes: part(Part::TakeMake),
@@ -2537,7 +2470,6 @@ impl Counters {
kernel_variants: a.kernel_variants.load(Relaxed), kernel_variants: a.kernel_variants.load(Relaxed),
word_pipelines: a.word_pipelines.load(Relaxed), word_pipelines: a.word_pipelines.load(Relaxed),
word_texture_buffers: a.word_texture_buffers.load(Relaxed), word_texture_buffers: a.word_texture_buffers.load(Relaxed),
chroma_textures: a.chroma_textures.load(Relaxed),
kernel_entries: a.kernel_entries.load(Relaxed), kernel_entries: a.kernel_entries.load(Relaxed),
render_contents: a.render_contents.load(Relaxed), render_contents: a.render_contents.load(Relaxed),
attachment_views: a.attachment_views.load(Relaxed), attachment_views: a.attachment_views.load(Relaxed),
@@ -2717,11 +2649,7 @@ pub struct Metrics {
/// [`commit_to_scheduled`](Self::commit_to_scheduled); 0 where the GPU start is placed before /// [`commit_to_scheduled`](Self::commit_to_scheduled); 0 where the GPU start is placed before
/// the kernel end, as for one that presents, scheduled once its call returned. Counted on the /// the kernel end, as for one that presents, scheduled once its call returned. Counted on the
/// completion thread as each retires, before its handlers run; one that ends with an error, /// completion thread as each retires, before its handlers run; one that ends with an error,
/// or completes without GPU times, counts none here or in the two below, and nor does one /// or completes without GPU times, counts none here or in the two below.
/// with nothing for the GPU whose submission is a Managed buffer's copy-in: the copy's GPU run
/// is the runtime's own
/// ([`runtime_command_buffer_gpu_nanos`](Self::runtime_command_buffer_gpu_nanos)), and its
/// handlers wait for it.
pub scheduled_to_gpu_start: [u64; STAGE_BUCKETS], pub scheduled_to_gpu_start: [u64; STAGE_BUCKETS],
/// The spans [`scheduled_to_gpu_start`](Self::scheduled_to_gpu_start) counts, summed, in /// The spans [`scheduled_to_gpu_start`](Self::scheduled_to_gpu_start) counts, summed, in
/// nanoseconds. /// nanoseconds.
@@ -2971,8 +2899,7 @@ pub struct Metrics {
/// nanoseconds; a maximum since the device was made. /// nanoseconds; a maximum since the device was made.
pub first_use_variant_wait_max_nanos: u64, pub first_use_variant_wait_max_nanos: u64,
/// Of the [`first_use_waits`](Self::first_use_waits), those for a render content's /// Of the [`first_use_waits`](Self::first_use_waits), those for a render content's
/// line-class pipeline: its first draw of lines, which made it, and each draw of lines that /// line-class pipeline, made by its first draw of lines.
/// met that make in flight on another thread and waited for it.
pub first_use_line_waits: u64, pub first_use_line_waits: u64,
/// The nanoseconds of the [`first_use_line_waits`](Self::first_use_line_waits), in total. /// The nanoseconds of the [`first_use_line_waits`](Self::first_use_line_waits), in total.
pub first_use_line_wait_nanos: u64, pub first_use_line_wait_nanos: u64,
@@ -2980,8 +2907,7 @@ pub struct Metrics {
/// a maximum since the device was made. /// a maximum since the device was made.
pub first_use_line_wait_max_nanos: u64, pub first_use_line_wait_max_nanos: u64,
/// Of the [`first_use_waits`](Self::first_use_waits), those for a render content's /// Of the [`first_use_waits`](Self::first_use_waits), those for a render content's
/// point-class pipeline: its first draw of points, which made it, and each draw of points that /// point-class pipeline, made by its first draw of points.
/// met that make in flight on another thread and waited for it.
pub first_use_point_waits: u64, pub first_use_point_waits: u64,
/// The nanoseconds of the [`first_use_point_waits`](Self::first_use_point_waits), in total. /// The nanoseconds of the [`first_use_point_waits`](Self::first_use_point_waits), in total.
pub first_use_point_wait_nanos: u64, pub first_use_point_wait_nanos: u64,
@@ -2989,9 +2915,8 @@ pub struct Metrics {
/// nanoseconds; a maximum since the device was made. /// nanoseconds; a maximum since the device was made.
pub first_use_point_wait_max_nanos: u64, pub first_use_point_wait_max_nanos: u64,
/// Of the [`first_use_waits`](Self::first_use_waits), those for a render content's pipeline /// Of the [`first_use_waits`](Self::first_use_waits), those for a render content's pipeline
/// under the depth clip mode `Clamp` or the triangle fill mode `Lines`: its first draw under /// under the depth clip mode `Clamp` or the triangle fill mode `Lines`, made by its first draw
/// them, which made it, and each draw under them that met that make in flight on another /// under them.
/// thread and waited for it.
pub first_use_raster_waits: u64, pub first_use_raster_waits: u64,
/// The nanoseconds of the [`first_use_raster_waits`](Self::first_use_raster_waits), in total. /// The nanoseconds of the [`first_use_raster_waits`](Self::first_use_raster_waits), in total.
pub first_use_raster_wait_nanos: u64, pub first_use_raster_wait_nanos: u64,
@@ -3125,34 +3050,22 @@ pub struct Metrics {
/// Translations made at encode, on the encoding thread, which the draw or dispatch that needs /// Translations made at encode, on the encoding thread, which the draw or dispatch that needs
/// one waits for: each the make of a module or content the state's creation did not make, /// one waits for: each the make of a module or content the state's creation did not make,
/// whether the translator lowers it or the cache directory holds its lowering, and whether it /// whether the translator lowers it or the cache directory holds its lowering, and whether it
/// is made or refused. Six makes count: an observing kernel's partial-threadgroups variant /// is made or refused. Four makes count: an observing kernel's partial-threadgroups variant
/// on emulated SIMD groups (`KernelVariant::EmulatedPartialThreadgroups`) that a dispatch /// on emulated SIMD groups (`KernelVariant::EmulatedPartialThreadgroups`) that a dispatch
/// lowers because no /// lowers because no
/// [`ComputePipelineState::prepare_dispatch`](crate::ComputePipelineState::prepare_dispatch) /// [`ComputePipelineState::prepare_dispatch`](crate::ComputePipelineState::prepare_dispatch)
/// of its shape lowered it first; a compute state's content for a dispatch's buffers bound /// of its shape lowered it first; a compute state's content for a dispatch's buffers bound
/// at a multiple of 4 below their alignment or its 8-bit sRGB textures' UNORM twins; a /// at a multiple of 4 below their alignment or its 8-bit sRGB textures' UNORM twins; a
/// render state's content for a draw's buffers bound at a multiple of 4 below their /// render state's content for a draw's buffers bound at a multiple of 4 below their
/// alignment or its 8-bit sRGB textures' UNORM twins; a render state's content for a pass it /// alignment or its 8-bit sRGB textures' UNORM twins; and a render state's content for a pass it does not render into as made (a
/// does not render into as made (a colour attachment the pass lacks, or a fetched colour in a /// colour attachment the pass lacks, or a fetched colour in a 2D array). Each is made once and
/// 2D array); a compute or render state's content for the 4:2:2 textures a dispatch or draw /// kept in the device's map of contents, or with its content, so a reuse counts nothing; a
/// reaches ([`chroma_contents`](Self::chroma_contents)); and a render content's depth range /// content the map forgot counts again when it is made again. A consumer whose pre-pass
/// twin, for a draw under a viewport depth range past `[0, 1]` that reads the depth /// prepares every dispatch reads none of the first kind; the other three have no pre-pass.
/// ([`depth_range_twins`](Self::depth_range_twins)). Each is made once and kept in the
/// device's map of contents, or with its content, so a reuse counts nothing; a content the map
/// forgot counts again when it is made again. A consumer whose pre-pass prepares every
/// dispatch reads none of the first kind; the other five have no pre-pass.
/// No Metal counterpart: Metal compiles a state whole when it is made. /// No Metal counterpart: Metal compiles a state whole when it is made.
pub translations_at_encode: u64, pub translations_at_encode: u64,
/// The nanoseconds of [`host_time`](crate::host_time) the /// The longest of those makes, in nanoseconds of [`host_time`](crate::host_time); a maximum
/// [`translations_at_encode`](Self::translations_at_encode) took, in total, each from its /// since the device was made, so the difference of two reads does not apply to it.
/// start to its end on the encoding thread that made it, made or refused. A sum, so unlike
/// [`translation_at_encode_max_nanos`](Self::translation_at_encode_max_nanos) the difference
/// of two reads is the time of the makes between them. No Metal counterpart: Metal compiles a
/// state whole when it is made.
pub translation_at_encode_nanos: u64,
/// The longest of the [`translations_at_encode`](Self::translations_at_encode), in nanoseconds
/// of [`host_time`](crate::host_time); a maximum since the device was made, so the difference
/// of two reads does not apply to it.
pub translation_at_encode_max_nanos: u64, pub translation_at_encode_max_nanos: u64,
/// `vkAllocateMemory` and `vkFreeMemory` calls made ahead of need, off the consumer's calls: /// `vkAllocateMemory` and `vkFreeMemory` calls made ahead of need, off the consumer's calls:
/// the block-maker thread's (the runtime's fixed-size internals, the pool's units, and the /// the block-maker thread's (the runtime's fixed-size internals, the pool's units, and the
@@ -3264,11 +3177,6 @@ pub struct Metrics {
/// ([`Gauges::word_pipelines`]). Only a device that holds some format's texture buffer as words /// ([`Gauges::word_pipelines`]). Only a device that holds some format's texture buffer as words
/// makes them. /// makes them.
pub word_contents: u64, pub word_contents: u64,
/// Depth range twins made: render contents lowered again with the vertex function folding
/// the viewport's depth range into its position, for draws under a range past `[0, 1]` that
/// reads the depth (`RenderCommandEncoder::set_viewport`), each at the first such draw of
/// its content, its time in [`translations_at_encode`](Self::translations_at_encode).
pub depth_range_twins: u64,
/// `VkPipeline` creations that went through the device's empty pipeline cache while the /// `VkPipeline` creations that went through the device's empty pipeline cache while the
/// reaper read and took in the device's blob ([`DeviceOptions::pipeline_cache_dir`]): each /// reaper read and took in the device's blob ([`DeviceOptions::pipeline_cache_dir`]): each
/// compiled without the blob's data, and those pipelines are not in this run's blob, so a /// compiled without the blob's data, and those pipelines are not in this run's blob, so a
@@ -3328,6 +3236,10 @@ pub struct Metrics {
/// its dispatch region at 256 bytes, more than 8 at 128), and each `set_bytes` copy, a render /// its dispatch region at 256 bytes, more than 8 at 128), and each `set_bytes` copy, a render
/// encoder's too. /// encoder's too.
pub ring_writes: u64, pub ring_writes: u64,
/// Recorded multi-draw indirect calls.
pub multi_draw_calls: u64,
/// Metal draws submitted by those indirect calls, excluding the direct heads.
pub multi_draw_items: u64,
/// `vkCmdPushConstants` recorded: a draw's or a dispatch's push bytes, where the command /// `vkCmdPushConstants` recorded: a draw's or a dispatch's push bytes, where the command
/// buffer did not already hold them. /// buffer did not already hold them.
pub pushes: u64, pub pushes: u64,
@@ -3384,32 +3296,6 @@ pub struct Metrics {
pub attachment_read_copies: u64, pub attachment_read_copies: u64,
/// The bytes of those copies, which count in [`bytes_copied`](Self::bytes_copied) too. /// The bytes of those copies, which count in [`bytes_copied`](Self::bytes_copied) too.
pub attachment_read_copy_bytes: u64, pub attachment_read_copy_bytes: u64,
/// No Metal counterpart, as Metal makes no such copy (a cost of the copy form a device
/// without the attachment feedback loop takes): the part of
/// [`attachment_read_copy_bytes`](Self::attachment_read_copy_bytes) copied for reads at the
/// fragment's own pixel, through a slot the fragment function reads only there or a colour
/// attachment it fetches (`[[color(n)]]`), each the draw's scissor a pixel wider each way.
/// With [`attachment_read_copy_bytes_whole_texture`](Self::attachment_read_copy_bytes_whole_texture)
/// it sums to `attachment_read_copy_bytes`.
pub attachment_read_copy_bytes_own_pixel: u64,
/// No Metal counterpart, likewise: the part of
/// [`attachment_read_copy_bytes`](Self::attachment_read_copy_bytes) copied for reads through
/// any other slot, each of every level and layer its texture reaches.
pub attachment_read_copy_bytes_whole_texture: u64,
/// No Metal counterpart, likewise: the part of
/// [`attachment_read_copy_bytes`](Self::attachment_read_copy_bytes) a draw copied into a
/// shadow that had held nothing since its pass began: the pass's first copy into it. With
/// [`attachment_read_copy_bytes_after_barrier`](Self::attachment_read_copy_bytes_after_barrier)
/// and [`attachment_read_copy_bytes_beyond_held`](Self::attachment_read_copy_bytes_beyond_held)
/// it sums to `attachment_read_copy_bytes`.
pub attachment_read_copy_bytes_first_in_pass: u64,
/// No Metal counterpart, likewise: the part a draw copied into a shadow that a memory barrier
/// after draws, or a draw that reads a colour attachment at its own pixel after draws, left
/// holding nothing: all the draw reads of its image.
pub attachment_read_copy_bytes_after_barrier: u64,
/// No Metal counterpart, likewise: the part a draw copied into a shadow that held something,
/// of what it reads that the shadow did not hold.
pub attachment_read_copy_bytes_beyond_held: u64,
/// Copies of what a pass resolved into a texture's resolve image, which Metal does not make: /// Copies of what a pass resolved into a texture's resolve image, which Metal does not make:
/// one for each resolve into a texture in place over a buffer whose linear image takes no /// one for each resolve into a texture in place over a buffer whose linear image takes no
/// attachment usage, of the pass's render area into the buffer's bytes at the texture's pitch /// attachment usage, of the pass's render area into the buffer's bytes at the texture's pitch
@@ -3622,8 +3508,10 @@ pub struct Metrics {
/// while it was inside one, or inside the driver as one began. Its frees are an idle /// while it was inside one, or inside the driver as one began. Its frees are an idle
/// allocation's, an imported or exported block's given back, a texture's allocation of its /// allocation's, an imported or exported block's given back, a texture's allocation of its
/// own, a surface plane's import, a copy's staging buffer of its own, and one it made and /// own, a surface plane's import, a copy's staging buffer of its own, and one it made and
/// could not use. A driver may hold such a call until the free returns. A call made during a /// could not use. A driver may hold such a call until the free returns: on the NVIDIA cards
/// free is counted as it enters the driver, one that a free began beside as it returns. /// measured in Thunderbolt enclosures, about 1.1 ms per MiB of host-visible memory. A call
/// made during a free is counted as it enters the driver, one that a free began beside as it
/// returns.
pub submissions_during_frees: u64, pub submissions_during_frees: u64,
/// The nanoseconds of [`host_time`](crate::host_time) those calls took, from each call to its /// The nanoseconds of [`host_time`](crate::host_time) those calls took, from each call to its
/// return, in total: the time the driver may have held them behind the frees, with their own /// return, in total: the time the driver may have held them behind the frees, with their own
@@ -3773,17 +3661,6 @@ pub struct Metrics {
/// copies in [`over_copies_host_memory_restore`](Self::over_copies_host_memory_restore). No /// copies in [`over_copies_host_memory_restore`](Self::over_copies_host_memory_restore). No
/// Metal counterpart: Metal's texture over a no-copy buffer is its bytes, with no move. /// Metal counterpart: Metal's texture over a no-copy buffer is its bytes, with no move.
pub textures_in_place_over_imports: u64, pub textures_in_place_over_imports: u64,
/// Contents lowered for a 4:2:2 texture (`GBGR422`, `BGRG422`): a compute or render state's
/// content made at the first dispatch or draw that binds one at a slot its functions read, or
/// that may reach one through a handle while one lives on the device
/// (`LoweringInputs::chroma_pairs`, `LoweringInputs::chroma_handles`), each a translation
/// and its pipelines' compiles at encode, counted also in
/// [`translations_at_encode`](Self::translations_at_encode). No Metal counterpart: Metal's
/// functions read the format's texels directly.
pub chroma_contents: u64,
/// Dispatches and draws that ran a content lowered for a 4:2:2 texture
/// ([`chroma_contents`](Self::chroma_contents)). No Metal counterpart.
pub chroma_launches: u64,
/// Exported blocks a public call handed out a device address of, each counted at the first: /// Exported blocks a public call handed out a device address of, each counted at the first:
/// [`Buffer::gpu_address`](crate::Buffer::gpu_address) answering an address in one, and a /// [`Buffer::gpu_address`](crate::Buffer::gpu_address) answering an address in one, and a
/// texture buffer's storage element at an index over its bytes; the block's own handle states /// texture buffer's storage element at an index over its bytes; the block's own handle states
@@ -3935,23 +3812,6 @@ pub struct Metrics {
/// moves of attachments to the feedback layout or of heap textures, and an execution's count /// moves of attachments to the feedback layout or of heap textures, and an execution's count
/// kernel. No Metal counterpart: a Metal render encoder is one pass. /// kernel. No Metal counterpart: a Metal render encoder is one pass.
pub rendering_interrupts: u64, pub rendering_interrupts: u64,
/// Mesh draws refused because an object or mesh threadgroup was within Metal's maximum for its
/// stage and past the state's on this device, which the stage's Vulkan limits hold
/// ([`Limit::MeshThreadgroupThreads`](crate::Limit::MeshThreadgroupThreads)): draws the guest
/// asked for that did not run. No Metal counterpart.
pub mesh_threadgroups_past_device: u64,
/// Mesh draws recorded of a state without an object function: each one task workgroup of the
/// state's launcher, which emits the mesh grid (`drawMeshThreadgroups:`, `drawMeshThreads:` and
/// `drawMeshThreadgroupsWithIndirectBuffer:`). A draw of an empty grid records nothing and is
/// not counted. No Metal counterpart.
pub mesh_draws_launched: u64,
/// Mesh draws recorded of a state with an object function whose object grid lay within the
/// device's task limits: one `vkCmdDrawMeshTasksEXT` of its counts. No Metal counterpart.
pub mesh_object_grids_whole: u64,
/// Mesh draws recorded of a state with an object function whose object grid was past the
/// device's task limits: one `vkCmdDrawMeshTasksIndirectEXT` of its pieces' records. No Metal
/// counterpart.
pub mesh_object_grids_in_pieces: u64,
/// Takes from the pool on the consumer's threads, each whole: a block of /// Takes from the pool on the consumer's threads, each whole: a block of
/// [`Device::take_block`](crate::Device::take_block) and a texture block, carved from a free /// [`Device::take_block`](crate::Device::take_block) and a texture block, carved from a free
/// range or from an allocation the take made ([`take_makes`](Self::take_makes)); their bytes /// range or from an allocation the take made ([`take_makes`](Self::take_makes)); their bytes
@@ -4189,11 +4049,6 @@ pub struct Gauges {
/// texture buffer through a handle runs its words twin /// texture buffer through a handle runs its words twin
/// ([`word_pipelines`](Self::word_pipelines)). /// ([`word_pipelines`](Self::word_pipelines)).
pub word_texture_buffers: u64, pub word_texture_buffers: u64,
/// Textures of `GBGR422` or `BGRG422`, held as their bytes: while any lives, a draw or
/// dispatch of a stage that reaches a `float` colour texture through a handle
/// (`PipelineInterface::handle_float_images`) runs the content lowered under
/// `LoweringInputs::chroma_handles`.
pub chroma_textures: u64,
/// Entries of the device's map of compiled contents, compute and render, which holds at most /// Entries of the device's map of compiled contents, compute and render, which holds at most
/// 1,024 and forgets the least recently used past them. /// 1,024 and forgets the least recently used past them.
pub kernel_entries: u64, pub kernel_entries: u64,
+31 -33
View File
@@ -87,19 +87,16 @@ impl Device {
/// while its texture lives. /// while its texture lives.
/// ///
/// **The image is the texture Direct3D 11 made.** Its usage is what the texture's /// **The image is the texture Direct3D 11 made.** Its usage is what the texture's
/// [`bind_flags`](D3d11Plane::bind_flags) give, and nothing more, on every device: copied from /// [`bind_flags`](D3d11Plane::bind_flags) give, and nothing more: copied from and into, as
/// and into, as Direct3D 11 copies any texture of default usage; sampled for /// Direct3D 11 copies any texture of default usage; sampled for `D3D11_BIND_SHADER_RESOURCE`,
/// `D3D11_BIND_SHADER_RESOURCE`, rendered for `D3D11_BIND_RENDER_TARGET` and storage for /// rendered for `D3D11_BIND_RENDER_TARGET` and storage for `D3D11_BIND_UNORDERED_ACCESS`; each
/// `D3D11_BIND_UNORDERED_ACCESS`; each where the descriptor's format holds it and the import /// where the descriptor's format holds it and the import query
/// query (`vkGetPhysicalDeviceImageFormatProperties2`) offers it, the handle importable and /// (`vkGetPhysicalDeviceImageFormatProperties2`) offers it. The one usage beside them, which
/// among the image's compatible handle types. Vulkan's import of memory /// the description has no counterpart for, is the attachment feedback loop's, taken where the
/// another API made states no rule for an image of other usage or flags than the texture's; /// descriptor's texture is a render target a draw may read in its own pass and the import
/// its rules for an import of Vulkan's own export ask the same image /// offers it with the rest. Vulkan's import of memory another API made states no rule for an image of other usage or
/// (`VUID-VkMemoryDedicatedAllocateInfo-image-01876`). So the image never takes the attachment /// flags than the texture's; its rules for an import of Vulkan's own export ask the same
/// feedback loop's usage, which the description has no counterpart for: a draw that reads a /// image (`VUID-VkMemoryDedicatedAllocateInfo-image-01876`).
/// plane as an attachment of its own pass reads it through a copy into the plane's shadow, on
/// a device with the loop as on one without it, a copy Metal does not make
/// ([`Metrics::attachment_read_copies`](crate::Metrics::attachment_read_copies)).
/// ///
/// **Views of another format.** The image is mutable where it lists more than its own /// **Views of another format.** The image is mutable where it lists more than its own
/// format, and lists at most two more, the two places it asks beyond the texture Direct3D 11 /// format, and lists at most two more, the two places it asks beyond the texture Direct3D 11
@@ -169,8 +166,7 @@ impl Device {
/// the descriptor's differ in their texel's bytes or Metal's view class; [`Limit::NoImport`] /// the descriptor's differ in their texel's bytes or Metal's view class; [`Limit::NoImport`]
/// of [`ImportHandle::D3d11Texture`] where the device does not enable /// of [`ImportHandle::D3d11Texture`] where the device does not enable
/// `VK_KHR_external_memory_win32` or its optimal images of the plane's formats and usage do /// `VK_KHR_external_memory_win32` or its optimal images of the plane's formats and usage do
/// not import the handle (`vkGetPhysicalDeviceImageFormatProperties2`: the handle not /// not import the handle (`vkGetPhysicalDeviceImageFormatProperties2`); [`Gap::SurfaceUsage`]
/// importable, or not among the image's compatible handle types); [`Gap::SurfaceUsage`]
/// for a usage the descriptor asks that the texture's bind flags do not give or the import /// for a usage the descriptor asks that the texture's bind flags do not give or the import
/// does not offer (`ShaderWrite` on a texture made without `D3D11_BIND_UNORDERED_ACCESS`); /// does not offer (`ShaderWrite` on a texture made without `D3D11_BIND_UNORDERED_ACCESS`);
/// [`Limit::TextureSize`] where a plane's extent is past the `maxExtent` the image format /// [`Limit::TextureSize`] where a plane's extent is past the `maxExtent` the image format
@@ -277,7 +273,9 @@ impl Device {
held.contains(feature) held.contains(feature)
}; };
let imports = |usage: vk::ImageUsageFlags, list: &[vk::Format]| { let imports = |usage: vk::ImageUsageFlags, list: &[vk::Format]| {
(import_query(core, format, usage, list)).is_ok_and(|(external, _)| takes(&external)) (import_query(core, format, usage, list)).is_ok_and(|(features, _)| {
features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE)
})
}; };
// The usage the texture's bind flags give, no other. // The usage the texture's bind flags give, no other.
let wanted = bound_usage(plane.bind_flags); let wanted = bound_usage(plane.bind_flags);
@@ -288,9 +286,15 @@ impl Device {
if usage.is_empty() || !imports(usage, &pair) { if usage.is_empty() || !imports(usage, &pair) {
return Err(Error::Limit(Limit::NoImport { handle })); return Err(Error::Limit(Limit::NoImport { handle }));
} }
// No feedback usage, which Direct3D 11's description has no counterpart for: a draw // With the feedback usage where the plane asks it and the import offers it with the
// reads the plane as an attachment of its own pass through its shadow // rest, so a draw reads it as an attachment of its own pass through the loop; else
// (`Device::surface_texture`). // through its shadow. The one usage Direct3D 11's description has no counterpart for,
// taken only where the plane's descriptor asks it.
let looped = usage | vk::ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT;
let usage = match plan.looped && imports(looped, &pair) {
true => looped,
false => usage,
};
let missing = plan.usage & !usage; let missing = plan.usage & !usage;
if !missing.is_empty() { if !missing.is_empty() {
return Err(Error::Unsupported(Gap::SurfaceUsage { return Err(Error::Unsupported(Gap::SurfaceUsage {
@@ -454,26 +458,17 @@ impl Device {
} }
} }
/// Whether an image whose import query answers `external` imports a Direct3D 11 texture's handle:
/// the handle is importable, and among the handle types the image may be made with
/// (`compatibleHandleTypes`, which `VUID-VkImageCreateInfo-pNext-00990` asks of the handle types
/// the image is made with).
fn takes(external: &vk::ExternalMemoryProperties) -> bool {
(external.external_memory_features).contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE)
&& (external.compatible_handle_types).contains(HANDLE)
}
/// What `vkGetPhysicalDeviceImageFormatProperties2` answers of an optimal 2D image of `format` /// What `vkGetPhysicalDeviceImageFormatProperties2` answers of an optimal 2D image of `format`
/// and `usage` imported from a Direct3D 11 texture, mutable and listing `list` where it is not /// and `usage` imported from a Direct3D 11 texture, mutable and listing `list` where it is not
/// empty: the handle's external memory properties (its features and the compatible handle types) /// empty: the handle's external memory features and the image's properties with the handle
/// and the image's properties with the handle (its `maxExtent` the limit of such an image's /// (its `maxExtent` the limit of such an image's extent, `VUID-VkImageCreateInfo-extent-02252`),
/// extent, `VUID-VkImageCreateInfo-extent-02252`), or the query's error. /// or the query's error.
pub(crate) fn import_query( pub(crate) fn import_query(
core: &Core, core: &Core,
format: vk::Format, format: vk::Format,
usage: vk::ImageUsageFlags, usage: vk::ImageUsageFlags,
list: &[vk::Format], list: &[vk::Format],
) -> Result<(vk::ExternalMemoryProperties, vk::ImageFormatProperties), vk::Result> { ) -> Result<(vk::ExternalMemoryFeatureFlags, vk::ImageFormatProperties), vk::Result> {
let (instance, physical) = (core.instance.vk(), core.physical); let (instance, physical) = (core.instance.vk(), core.physical);
let mut external = vk::PhysicalDeviceExternalImageFormatInfo::default().handle_type(HANDLE); let mut external = vk::PhysicalDeviceExternalImageFormatInfo::default().handle_type(HANDLE);
let mut listed = vk::ImageFormatListCreateInfo::default().view_formats(list); let mut listed = vk::ImageFormatListCreateInfo::default().view_formats(list);
@@ -494,5 +489,8 @@ pub(crate) fn import_query(
// the device's `VK_KHR_external_memory_win32`). // the device's `VK_KHR_external_memory_win32`).
unsafe { instance.get_physical_device_image_format_properties2(physical, &info, &mut out) }?; unsafe { instance.get_physical_device_image_format_properties2(physical, &info, &mut out) }?;
let properties = out.image_format_properties; let properties = out.image_format_properties;
Ok((external_out.external_memory_properties, properties)) let features = external_out
.external_memory_properties
.external_memory_features;
Ok((features, properties))
} }
+65 -14
View File
@@ -275,16 +275,20 @@ pub(crate) struct Core {
/// pipeline of a state whose functions can read a texture, which takes the loop's colour flag /// pipeline of a state whose functions can read a texture, which takes the loop's colour flag
/// at the state's make (`crate::render::Draws::reads_textures`). /// at the state's make (`crate::render::Draws::reads_textures`).
pub(crate) feedback_loop: bool, pub(crate) feedback_loop: bool,
pub(crate) capture_replay: bool,
/// `VK_EXT_device_fault`'s command, where device creation enabled it (where the device lists /// `VK_EXT_device_fault`'s command, where device creation enabled it (where the device lists
/// it): a lost device's fault report, read once, at its first loss (`crate::fault`). /// it): a lost device's fault report, read once, at its first loss (`crate::fault`).
pub(crate) fault: Option<ash::ext::device_fault::Device>, pub(crate) fault: Option<ash::ext::device_fault::Device>,
/// `VK_EXT_mesh_shader`'s draw commands, where device creation enabled it with its stages
/// (`floor::MESH_EXTENSIONS`): a mesh render pipeline state's draws record them.
pub(crate) mesh: Option<ash::ext::mesh_shader::Device>,
/// `VK_EXT_device_generated_commands`' entry points, limits and the indirect command buffers' /// `VK_EXT_device_generated_commands`' entry points, limits and the indirect command buffers'
/// caches, where device creation enabled it (`floor::Capabilities::indirect_commands`); an /// caches, where device creation enabled it (`floor::Capabilities::indirect_commands`); an
/// indirect command buffer is refused without them. /// indirect command buffer is refused without them.
pub(crate) indirect: Option<crate::indirect::Indirect>, pub(crate) indirect: Option<crate::indirect::Indirect>,
draw_indirect_limit: u32,
pub(crate) draw_indirect_first_instance: bool,
/// A draw may read an attachment of its own pass through a texture
/// (`floor::Capabilities::attachment_reads`): through the feedback loop where `feedback_loop`
/// holds, else through a copy of the image into its shadow (`crate::shadow`).
pub(crate) attachment_reads: bool,
/// Device creation enabled `linearColorAttachment` (`VK_NV_linear_color_attachment`, where /// Device creation enabled `linearColorAttachment` (`VK_NV_linear_color_attachment`, where
/// the device lists it): an opaque handle's surface plane whose format's `LINEAR` tiling /// the device lists it): an opaque handle's surface plane whose format's `LINEAR` tiling
/// renders through `VK_FORMAT_FEATURE_2_LINEAR_COLOR_ATTACHMENT_BIT_NV` alone lies in place /// renders through `VK_FORMAT_FEATURE_2_LINEAR_COLOR_ATTACHMENT_BIT_NV` alone lies in place
@@ -323,8 +327,7 @@ pub(crate) struct Core {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fail_wakes: std::sync::atomic::AtomicU32, pub(crate) fail_wakes: std::sync::atomic::AtomicU32,
/// For the device tests: how many more host waits on what the GPU has pending (the device's /// For the device tests: how many more host waits on what the GPU has pending (the device's
/// idle wait, an import's bind wait, a wait for a batch's progress value) fail as out of host /// idle wait, an import's bind wait) fail as out of host memory, before the driver is called.
/// memory, before the driver is called.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fail_waits: std::sync::atomic::AtomicU32, pub(crate) fail_waits: std::sync::atomic::AtomicU32,
/// For the device tests: where nonzero, the private arena's budget in place of the device's /// For the device tests: where nonzero, the private arena's budget in place of the device's
@@ -465,6 +468,9 @@ pub(crate) struct Queues {
#[non_exhaustive] #[non_exhaustive]
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct DeviceOptions { pub struct DeviceOptions {
/// No Metal counterpart. Opt in to combining draws into a Vulkan indirect draw command
/// where the logical device enables `multiDrawIndirect`.
pub multi_draw_indirect: bool,
/// The consumer's hooks around each allocation of the pool: its map before any of its blocks /// The consumer's hooks around each allocation of the pool: its map before any of its blocks
/// goes out, and its unmap before the allocation is freed. `None` where the consumer keeps no /// goes out, and its unmap before the allocation is freed. `None` where the consumer keeps no
/// mapping of its own. /// mapping of its own.
@@ -648,7 +654,6 @@ impl Device {
mut maintenance8, mut maintenance8,
mut pipeline_robustness, mut pipeline_robustness,
mut extended_dynamic_state, mut extended_dynamic_state,
mut mesh,
} = enabled_features; } = enabled_features;
// `sparseBinding` for imports over several dma-bufs (`Device::import_dma_bufs`), only where // `sparseBinding` for imports over several dma-bufs (`Device::import_dma_bufs`), only where
// the device's queries offer that import: it changes no other path, as only that import // the device's queries offer that import: it changes no other path, as only that import
@@ -724,9 +729,6 @@ impl Device {
if enabled(ash::ext::extended_dynamic_state::NAME) { if enabled(ash::ext::extended_dynamic_state::NAME) {
features = features.push_next(&mut extended_dynamic_state); features = features.push_next(&mut extended_dynamic_state);
} }
if enabled(ash::ext::mesh_shader::NAME) {
features = features.push_next(&mut mesh);
}
// SAFETY: as for the floor check. // SAFETY: as for the floor check.
let listed = unsafe { vk_instance.enumerate_device_extension_properties(raw) } let listed = unsafe { vk_instance.enumerate_device_extension_properties(raw) }
.map_err(Error::vulkan("vkEnumerateDeviceExtensionProperties"))?; .map_err(Error::vulkan("vkEnumerateDeviceExtensionProperties"))?;
@@ -833,9 +835,6 @@ impl Device {
.extensions .extensions
.contains(&ash::ext::device_fault::NAME)) .contains(&ash::ext::device_fault::NAME))
.then(|| ash::ext::device_fault::Device::new(vk_instance, &device)); .then(|| ash::ext::device_fault::Device::new(vk_instance, &device));
let mesh = (capabilities.extensions)
.contains(&ash::ext::mesh_shader::NAME)
.then(|| ash::ext::mesh_shader::Device::new(vk_instance, &device));
let sample_locations = (capabilities.extensions) let sample_locations = (capabilities.extensions)
.contains(&ash::ext::sample_locations::NAME) .contains(&ash::ext::sample_locations::NAME)
.then(|| { .then(|| {
@@ -933,9 +932,13 @@ impl Device {
ticks, ticks,
calibrated, calibrated,
feedback_loop: capabilities.feedback_loop, feedback_loop: capabilities.feedback_loop,
capture_replay: capabilities.buffer_device_address_capture_replay,
fault, fault,
mesh,
indirect, indirect,
draw_indirect_limit: capabilities.draw_indirect_limit(options.multi_draw_indirect),
draw_indirect_first_instance: capabilities.features.core.draw_indirect_first_instance
== vk::TRUE,
attachment_reads: capabilities.attachment_reads,
linear_attachments: (capabilities.features.linear_attachment).linear_color_attachment linear_attachments: (capabilities.features.linear_attachment).linear_color_attachment
== vk::TRUE, == vk::TRUE,
resolve_modes, resolve_modes,
@@ -1238,6 +1241,42 @@ impl Device {
complete::lose(&self.shared.core, loss); complete::lose(&self.shared.core, loss);
} }
/// Whether Vulkan `bufferDeviceAddressCaptureReplay` is enabled on this device.
pub fn buffer_device_address_capture_replay(&self) -> bool {
self.shared.core.capture_replay
}
/// Waits non-destructively until all in-flight GPU work has completed and retired.
pub fn wait_idle(&self) -> Result<(), Error> {
let core = &self.shared.core;
if core.closed() {
return Err(Error::Quiesced);
}
// Wait for submitted command buffers to retire on the completion thread.
let deadline = Instant::now() + Duration::from_secs(10);
while core.pool.in_flight() > 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(1));
}
// SAFETY: `device` is live and wait_idle synchronizes all host queues.
let _q = lock(&core.queues.runtime);
unsafe { core.device.device_wait_idle() }.map_err(Error::vulkan("vkDeviceWaitIdle"))?;
Ok(())
}
/// Replays a previously captured block at its exact Vulkan device address.
pub fn take_block_replayed(&self, capture: memory::BlockCaptureInfo) -> Result<Block, Error> {
let core = &self.shared.core;
if core.closed() {
return Err(Error::Quiesced);
}
let memory =
core.pool
.take_replayed(core, capture, crate::counters::Site::take(capture.class))?;
let info = memory.info();
let block = memory::Block::new(memory, Arc::clone(core));
Ok(Block::claim(core, info, block))
}
/// No Metal counterpart: takes a block of `class` memory of `len` bytes rounded up to 64 KiB /// No Metal counterpart: takes a block of `class` memory of `len` bytes rounded up to 64 KiB
/// (to the device's `bufferImageGranularity` where that is larger), for the consumer to place /// (to the device's `bufferImageGranularity` where that is larger), for the consumer to place
/// buffers in: a handle ([`Block`]) whose last drop gives it back. A block is a range of one /// buffers in: a handle ([`Block`]) whose last drop gives it back. A block is a range of one
@@ -1359,6 +1398,12 @@ impl Device {
&self.shared.core &self.shared.core
} }
/// No Metal counterpart. The maximum number of draws in one Vulkan indirect draw command
/// with batching enabled, or zero when batching is unavailable or disabled.
pub fn draw_indirect_limit(&self) -> u32 {
self.core().draw_indirect_limit()
}
/// Gives up this handle where it is not the last, which ends nothing; the last comes back, /// Gives up this handle where it is not the last, which ends nothing; the last comes back,
/// for the caller to drop once it holds no lock, which ends the device on its thread. A call /// for the caller to drop once it holds no lock, which ends the device on its thread. A call
/// that holds a handle while another thread may drop the consumer's last one gives its own up /// that holds a handle while another thread may drop the consumer's last one gives its own up
@@ -1684,7 +1729,9 @@ unsafe fn objects(
// SAFETY: the device is live. // SAFETY: the device is live.
let made = unsafe { Done::new(device) }.and_then(|mut done| { let made = unsafe { Done::new(device) }.and_then(|mut done| {
// SAFETY: the device is live, with the floor's features. // SAFETY: the device is live, with the floor's features.
let arrays = match unsafe { Arrays::new(device, counters, buffers) } { let arrays = match unsafe {
Arrays::new(device, counters, (capabilities.attachment_reads, buffers))
} {
Ok(arrays) => arrays, Ok(arrays) => arrays,
Err(error) => { Err(error) => {
// SAFETY: the completion objects are unused. // SAFETY: the completion objects are unused.
@@ -1742,6 +1789,10 @@ pub(crate) struct EncoderLimits {
} }
impl Core { impl Core {
pub(crate) fn draw_indirect_limit(&self) -> u32 {
self.draw_indirect_limit
}
/// A digest of what the device enabled: its extensions, the consumer's features and the /// A digest of what the device enabled: its extensions, the consumer's features and the
/// translator's profile of the device (its features, properties and limits). Two devices of /// translator's profile of the device (its features, properties and limits). Two devices of
/// one physical device opened with the same [`DeviceOptions`] have one; the stage keys and a /// one physical device opened with the same [`DeviceOptions`] have one; the stage keys and a
+18 -64
View File
@@ -6,18 +6,15 @@ use crate::bound::{Descriptor, NULL};
use crate::buffer::{Buffer, BufferInner, BufferObject}; use crate::buffer::{Buffer, BufferInner, BufferObject};
use crate::coherence::Range; use crate::coherence::Range;
use crate::command::{Building, CommandBuffer, Owed}; use crate::command::{Building, CommandBuffer, Owed};
use crate::counters::{Gauge, Metric}; use crate::counters::Metric;
use crate::device::Core; use crate::device::Core;
use crate::error::{ use crate::error::{Error, Gap, Limit, PartialThreadgroupsSite, Refusal, StageInKind};
ChromaPairsGap, Error, Gap, Limit, PartialThreadgroupsSite, Refusal, StageInKind,
};
use crate::fence::Fence; use crate::fence::Fence;
use crate::floor; use crate::floor;
use crate::function_table::VisibleFunctionTable; use crate::function_table::VisibleFunctionTable;
use crate::hazard::{Access, Dependency}; use crate::hazard::{Access, Dependency};
use crate::indirect::IndirectCommandBuffer; use crate::indirect::IndirectCommandBuffer;
use crate::kept::{Handle, Lent, Uncounted}; use crate::kept::{Handle, Lent, Uncounted};
use crate::kernel_map::Chroma;
use crate::memory::BlockId; use crate::memory::BlockId;
use crate::over::{self, Reached, Span}; use crate::over::{self, Reached, Span};
use crate::pipeline::{ use crate::pipeline::{
@@ -352,10 +349,6 @@ struct DispatchFacts {
/// buffer slot at a multiple of 4 below its argument's alignment ([`check_alignments`]), /// buffer slot at a multiple of 4 below its argument's alignment ([`check_alignments`]),
/// found with the alignments. /// found with the alignments.
variant: Option<Arc<Compiled>>, variant: Option<Arc<Compiled>>,
/// Where the kernel reads a 4:2:2 texture, which the variant is lowered for
/// ([`Chroma`]): its slots bound to one, found with the alignments, and whether it may reach
/// one through a handle while one lives on the device, which each dispatch looks at again.
chroma: Chroma,
} }
/// Which of its state's modules a dispatch runs. /// Which of its state's modules a dispatch runs.
@@ -1245,13 +1238,6 @@ impl ComputeCommandEncoder {
let inner = &state.compiled; let inner = &state.compiled;
let max = inner.whole.interface.max_total_threads; let max = inner.whole.interface.max_total_threads;
size_checked(&inner.whole.interface, size)?; size_checked(&inner.whole.interface, size)?;
// A kernel that may reach a 4:2:2 texture through a handle runs its content for one while
// one lives on the device: a change of that decides the content again.
let handles = inner.whole.interface.handle_float_images
&& self.core.counters.live(Gauge::ChromaTextures) > 0;
if handles != self.facts.chroma.handles {
self.facts.aligned = false;
}
// Every module of a state is the same function, with the same arguments and alignments, // Every module of a state is the same function, with the same arguments and alignments,
// so the whole module answers this check and the next, once after each change; a buffer // so the whole module answers this check and the next, once after each change; a buffer
// bound at a multiple of 4 below its argument's alignment is the variant's below. // bound at a multiple of 4 below its argument's alignment is the variant's below.
@@ -1332,51 +1318,25 @@ impl ComputeCommandEncoder {
return Err(element(slot, gap)); return Err(element(slot, gap));
} }
} }
// The texture slots bound to a 4:2:2 texture, which only a content lowered for it reads
// as Metal's texels.
let mut slots = 0u128;
for &(slot, _) in &interface.textures {
if matches!(self.textures.get(slot as usize), Some(Some(t)) if t.chroma_pairs()) {
slots |= 1 << slot;
}
}
let chroma = Chroma {
slots: [slots, 0],
handles,
};
self.facts.chroma = chroma;
// The variant of those slots and of the buffers bound at a multiple of 4 below their // The variant of those slots and of the buffers bound at a multiple of 4 below their
// argument's alignment, which holds each to what its accesses need, as it checks. A // argument's alignment, which holds each to what its accesses need, as it checks. A
// kernel the consumer compiled has none: its own module refuses such a buffer, and a // kernel the consumer compiled has none: its own module refuses such a buffer.
// 4:2:2 texture it would read. self.facts.variant = match (first, words) {
self.facts.variant = match (first, words, chroma.any()) { (None, 0) => None,
(None, 0, false) => None, (first, words) => match state.variant(first.map_or(0, |_| srgb), words) {
(first, words, _) => { Some(variant) => {
match state.variant(first.map_or(0, |_| srgb), words, chroma) { let variant = variant?;
Some(variant) => { check_alignments(&self.core, &self.slots, &variant.whole.interface, false)?;
let variant = variant?; Some(variant)
check_alignments( }
&self.core, None => {
&self.slots, check_alignments(&self.core, &self.slots, interface, false)?;
&variant.whole.interface, match first {
false, Some((slot, gap)) => return Err(element(slot, gap)),
)?; None => None,
Some(variant)
}
None => {
check_alignments(&self.core, &self.slots, interface, false)?;
if chroma.any() {
return Err(Error::Unsupported(Gap::ChromaPairsUse {
cause: ChromaPairsGap::CompiledFunction,
}));
}
match first {
Some((slot, gap)) => return Err(element(slot, gap)),
None => None,
}
} }
} }
} },
}; };
// A texture declared written with no storage element, which the kernel may reach // A texture declared written with no storage element, which the kernel may reach
// through its storage image beyond its slots. // through its storage image beyond its slots.
@@ -1425,10 +1385,6 @@ impl ComputeCommandEncoder {
recording(&mut self.building).count(Metric::DispatchesWithoutEffects); recording(&mut self.building).count(Metric::DispatchesWithoutEffects);
return Ok(()); return Ok(());
} }
// A dispatch of a content lowered for a 4:2:2 texture.
if variant.is_some() && self.facts.chroma.any() {
recording(&mut self.building).count(Metric::ChromaLaunches);
}
// What a kernel reads of a stage-in region the encoder never set is not established. // What a kernel reads of a stage-in region the encoder never set is not established.
if inner.whole.interface.stage_in_region && self.stage_in_region.is_none() { if inner.whole.interface.stage_in_region && self.stage_in_region.is_none() {
return Err(Error::Unsupported(Gap::NoStageInRegion)); return Err(Error::Unsupported(Gap::NoStageInRegion));
@@ -2156,11 +2112,9 @@ impl Parameters {
| FieldValue::FetchedColor(_) | FieldValue::FetchedColor(_)
| FieldValue::RenderTargetArrayLength | FieldValue::RenderTargetArrayLength
| FieldValue::ViewportCount | FieldValue::ViewportCount
| FieldValue::DepthRangeFold
| FieldValue::IndirectRange | FieldValue::IndirectRange
| FieldValue::IndirectSequence | FieldValue::IndirectSequence
| FieldValue::IndirectBase | FieldValue::IndirectBase => {}
| FieldValue::GroupCounts => {}
} }
} }
self.block_address = (interface.block_len > 0).then_some(interface.block_address); self.block_address = (interface.block_len > 0).then_some(interface.block_address);
+32 -210
View File
@@ -357,18 +357,6 @@ pub enum Refusal {
/// pipeline that is not a tessellation one, its validation off; Metal's validation stops a /// pipeline that is not a tessellation one, its validation off; Metal's validation stops a
/// draw of primitives with a tessellation pipeline). /// draw of primitives with a tessellation pipeline).
PatchDraw, PatchDraw,
/// A draw of primitives or patches, or an execution of an indirect command buffer's commands,
/// with a mesh render pipeline state
/// ([`Device::new_mesh_render_pipeline_state`](crate::Device::new_mesh_render_pipeline_state)),
/// whose functions only a mesh draw runs: Vulkan's vertex draws take no pipeline with a task or
/// mesh stage (`VUID-vkCmdDraw-stage-06481`); or a mesh draw
/// ([`RenderCommandEncoder::draw_mesh_threadgroups`](crate::RenderCommandEncoder::draw_mesh_threadgroups),
/// [`draw_mesh_threads`](crate::RenderCommandEncoder::draw_mesh_threads)) with a state of a
/// vertex function, which Vulkan's mesh draws take no pipeline of
/// (`VUID-vkCmdDrawMeshTasksEXT-stage-06480`).
///
/// Basis: ours (Metal's answer to such a draw is not measured).
MeshDraw,
/// A draw of patches while the encoder has no tessellation factor buffer /// A draw of patches while the encoder has no tessellation factor buffer
/// (`setTessellationFactorBuffer:offset:instanceStride:`). /// (`setTessellationFactorBuffer:offset:instanceStride:`).
/// ///
@@ -462,20 +450,14 @@ pub enum Refusal {
}, },
/// A threadgroup of no threads, or of more than Metal's `maxTotalThreadsPerThreadgroup` for /// A threadgroup of no threads, or of more than Metal's `maxTotalThreadsPerThreadgroup` for
/// the kernel (a required size's threads, where the descriptor requires one). One within it /// the kernel (a required size's threads, where the descriptor requires one). One within it
/// and past the state's on this device is the device's [`Limit::ThreadgroupThreads`]. A mesh /// and past the state's on this device is the device's [`Limit::ThreadgroupThreads`].
/// draw's object or mesh threadgroup likewise, of more than Metal's maximum for its stage
/// (`GraphicsState::max_total_threads_per_object_threadgroup` and its mesh sibling in the
/// translator: Metal's rule); one within it and past the state's on this device is
/// [`Limit::MeshThreadgroupThreads`].
/// ///
/// Basis: metal-documented (a threadgroup's threads total at most the state's /// Basis: metal-documented (a threadgroup's threads total at most the state's
/// `maxTotalThreadsPerThreadgroup`, an object or mesh threadgroup's at most the state's /// `maxTotalThreadsPerThreadgroup`).
/// `maxTotalThreadsPerObjectThreadgroup` or `maxTotalThreadsPerMeshThreadgroup`).
ThreadgroupSize { ThreadgroupSize {
/// The threadgroup size asked for. /// The threadgroup size asked for.
size: [u32; 3], size: [u32; 3],
/// The state's `maxTotalThreadsPerThreadgroup`, or for a mesh draw its stage's maximum on /// The state's `maxTotalThreadsPerThreadgroup`.
/// this device.
max: u32, max: u32,
}, },
/// An imageblock size /// An imageblock size
@@ -828,21 +810,6 @@ pub enum Refusal {
/// The texture's pixel format. /// The texture's pixel format.
pixel_format: PixelFormat, pixel_format: PixelFormat,
}, },
/// A texture of `GBGR422` or `BGRG422` that breaks one of Metal's rules for the format, `rule`
/// naming which: a type other than 2D, an odd width, more than one level, or a view of one.
///
/// Basis: metal-measured (our probe on an Apple M3 Max, macOS 27.0.1: plain Metal asserts
/// "MTLPixelFormat422 requires even width", "MTLTextureDescriptor requests 4 mipmap levels,
/// but the MTLPixelFormat422 pixel format does not support mipmaps", and for a view "source
/// texture pixelFormat (MTLPixelFormatGBGR422) not castable"; the SDK's `MTLPixelFormat.h`:
/// "422 textures must have a width that is a multiple of 2, and can only be used for 2D
/// non-mipmap textures").
ChromaPairs {
/// The texture's pixel format.
pixel_format: PixelFormat,
/// The rule it breaks.
rule: ChromaPairsRule,
},
/// [`BlitCommandEncoder::copy_from_texture`](crate::BlitCommandEncoder::copy_from_texture) /// [`BlitCommandEncoder::copy_from_texture`](crate::BlitCommandEncoder::copy_from_texture)
/// between textures of two pixel formats, or of two sample counts. /// between textures of two pixel formats, or of two sample counts.
/// ///
@@ -1468,19 +1435,6 @@ pub enum Gap {
/// The pixel format asked for. /// The pixel format asked for.
pixel_format: PixelFormat, pixel_format: PixelFormat,
}, },
/// A texture of `GBGR422` or `BGRG422` asked for a use the runtime does not build, `cause`
/// naming it. Its image holds the texture's bytes as `R8G8_UNORM`, which only the functions
/// the runtime lowers for it read as Metal's texels (`LoweringInputs::chroma_pairs`): a
/// shader's write, a render pass's store and a swizzle would read or store the bytes
/// themselves, and a function compiled outside the runtime is not lowered for the texture.
///
/// Basis: ours (Metal's render pipelines refuse the formats as colour attachments, and the
/// runtime builds reads, samples, gathers and copies of them, but for a copy of rows closer
/// than the region's, `ChromaPairsGap::CloseRows`).
ChromaPairsUse {
/// The use not built.
cause: ChromaPairsGap,
},
/// [`BlitCommandEncoder::generate_mipmaps`](crate::BlitCommandEncoder::generate_mipmaps) of a /// [`BlitCommandEncoder::generate_mipmaps`](crate::BlitCommandEncoder::generate_mipmaps) of a
/// texture whose image the device's blits do not filter: its format query lacks blits from /// texture whose image the device's blits do not filter: its format query lacks blits from
/// or to the image's format, or its linear filtering, or the image holds the pixel format /// or to the image's format, or its linear filtering, or the image holds the pixel format
@@ -1492,6 +1446,13 @@ pub enum Gap {
/// The texture's pixel format. /// The texture's pixel format.
pixel_format: PixelFormat, pixel_format: PixelFormat,
}, },
/// A sampler state whose minification or magnification filter is cubic. Not raised:
/// [`Device::new_sampler_state`](crate::Device::new_sampler_state) makes a `Cubic` filter
/// (`MTLSamplerMinMagFilterCubic`, Metal's undeclared raw value 2) and filters it as nearest.
/// The variant stays because a consumer names it.
///
/// Basis: ours (the runtime's choice of nearest for a value Metal does not document).
CubicSampler,
/// [`Texture::replace_region`](crate::Texture::replace_region), /// [`Texture::replace_region`](crate::Texture::replace_region),
/// [`Texture::get_bytes`](crate::Texture::get_bytes), a Managed texture's places or a blit /// [`Texture::get_bytes`](crate::Texture::get_bytes), a Managed texture's places or a blit
/// copy between a buffer and a texture /// copy between a buffer and a texture
@@ -1885,12 +1846,8 @@ pub enum IndirectCommandsKind {
/// Command types other than plain draws alone (`MTLIndirectCommandTypeDraw`), indexed draws /// Command types other than plain draws alone (`MTLIndirectCommandTypeDraw`), indexed draws
/// alone (`MTLIndirectCommandTypeDrawIndexed`), patch draws alone /// alone (`MTLIndirectCommandTypeDrawIndexed`), patch draws alone
/// (`MTLIndirectCommandTypeDrawPatches`) or indexed patch draws alone /// (`MTLIndirectCommandTypeDrawPatches`) or indexed patch draws alone
/// (`MTLIndirectCommandTypeDrawIndexedPatches`): mesh draws /// (`MTLIndirectCommandTypeDrawIndexedPatches`): mesh draws, or dispatches, which take other
/// (`MTLIndirectCommandTypeDrawMeshThreadgroups`, `MTLIndirectCommandTypeDrawMeshThreads`), /// command layouts; or two draw kinds in one buffer, as a command layout takes
/// which wait on commands that set their own pipeline state
/// ([`CommandPipelines`](Self::CommandPipelines)) and commands the CPU encodes, and then take a
/// command layout of their own; dispatches, which take another command layout; or two draw
/// kinds in one buffer, as a command layout takes
/// one draw token (`VUID-VkIndirectCommandsLayoutCreateInfoEXT-pTokens-11100`) and no form /// one draw token (`VUID-VkIndirectCommandsLayoutCreateInfoEXT-pTokens-11100`) and no form
/// found draws both kinds in command order at a bounded cost: two executions over the same /// found draws both kinds in command order at a bounded cost: two executions over the same
/// records reorder the commands, an execution of each command costs two a command, and indices /// records reorder the commands, an execution of each command costs two a command, and indices
@@ -1990,7 +1947,7 @@ pub enum DrawInputCause {
/// a layer index the translator's variant drops (`RuntimeFact::RenderTargetArrayLength` with /// a layer index the translator's variant drops (`RuntimeFact::RenderTargetArrayLength` with
/// `layer_dropped`). Metal's counterpart is the draw's state the fact stands for. /// `layer_dropped`). Metal's counterpart is the draw's state the fact stands for.
RuntimeFact { RuntimeFact {
/// The fact's name (`RuntimeFact::name`), such as `"FlatGrid"`. /// The fact's name (`RuntimeFact::name`), such as `"ResourcePresence"`.
fact: &'static str, fact: &'static str,
}, },
/// An argument slot the encoder does not bind: a visible or intersection function table at a /// An argument slot the encoder does not bind: a visible or intersection function table at a
@@ -2013,6 +1970,9 @@ pub enum DrawInputCause {
/// one whose use the translator states no device sampler for. Metal's counterpart is the /// one whose use the translator states no device sampler for. Metal's counterpart is the
/// sampler the function's source declares. /// sampler the function's source declares.
ConstexprSampler, ConstexprSampler,
/// A `constexpr sampler` of unnormalized coordinates (`coord::pixel`). Metal's counterpart is
/// the sampler the function's source declares.
UnnormalizedSampler,
/// A function's parameter block longer than one chunk of the runtime's parameter ring /// A function's parameter block longer than one chunk of the runtime's parameter ring
/// (64 KiB). Metal's counterpart is the function's arguments, which Metal binds however many /// (64 KiB). Metal's counterpart is the function's arguments, which Metal binds however many
/// there are. /// there are.
@@ -2043,12 +2003,12 @@ pub enum KernelInputKind {
/// counterpart: it states no subgroup control. /// counterpart: it states no subgroup control.
StageFlags, StageFlags,
/// A fact of the module the encoder does not supply: a `RuntimeFact` the runtime does not /// A fact of the module the encoder does not supply: a `RuntimeFact` the runtime does not
/// name, or an address alignment of a slot that is not a kernel's buffer or that is not a power /// name, such as a resource's presence or a sampler's coordinates, or an address alignment of
/// of two, at the state's make. /// a slot that is not a kernel's buffer or that is not a power of two, at the state's make.
/// Metal's counterpart is the dispatch's state the fact stands for: the bound resource's own /// Metal's counterpart is the dispatch's state the fact stands for: the bound resource's own
/// state. /// state.
RuntimeFact { RuntimeFact {
/// The fact's name (`RuntimeFact::name`), such as `"FlatGrid"`. /// The fact's name (`RuntimeFact::name`), such as `"ResourcePresence"`.
fact: &'static str, fact: &'static str,
}, },
/// An argument slot the encoder does not bind: an intersection function table at a buffer /// An argument slot the encoder does not bind: an intersection function table at a buffer
@@ -2135,12 +2095,8 @@ pub enum DrawKind {
/// mirrors the draw), or bounds past the device's viewport limits (`maxViewportDimensions`, /// mirrors the draw), or bounds past the device's viewport limits (`maxViewportDimensions`,
/// `viewportBoundsRange`), refused where it is set; or, at a draw, a depth range past /// `viewportBoundsRange`), refused where it is set; or, at a draw, a depth range past
/// `[0, 1]` where the draw's pass has a depth attachment or its fragment function may read /// `[0, 1]` where the draw's pass has a depth attachment or its fragment function may read
/// `[[position]]`'s z or w, and no depth range twin draws it: under the `Clamp` depth clip /// `[[position]]`'s z or w. No Vulkan viewport maps clip space as it does. One that covers no
/// mode, for a vertex function that writes `[[viewport_array_index]]` while the viewports set /// pixel draws nothing, as Metal's.
/// have different ranges, for a vertex function the consumer compiled, or for a mesh draw
/// ([`RenderCommandEncoder::set_viewport`](crate::RenderCommandEncoder::set_viewport)). No
/// Vulkan viewport maps clip space as it does. One that covers no pixel draws nothing, as
/// Metal's.
Viewport, Viewport,
/// A pipeline state whose colour, depth or stencil formats are not its pass's attachments', /// A pipeline state whose colour, depth or stencil formats are not its pass's attachments',
/// or whose `rasterSampleCount` is not their sample count: Metal's validation stops such /// or whose `rasterSampleCount` is not their sample count: Metal's validation stops such
@@ -2153,12 +2109,13 @@ pub enum DrawKind {
/// ([`RenderCommandEncoder::set_render_pipeline_state`](crate::RenderCommandEncoder::set_render_pipeline_state)). /// ([`RenderCommandEncoder::set_render_pipeline_state`](crate::RenderCommandEncoder::set_render_pipeline_state)).
AttachmentFormats, AttachmentFormats,
/// A draw that binds a texture whose image the pass renders, where neither the attachment /// A draw that binds a texture whose image the pass renders, where neither the attachment
/// feedback loop nor a copy into the image's shadow reads it: from the vertex function at the /// feedback loop nor a copy into the image's shadow reads it: on a device without the
/// attachment reads (`floor::Capabilities::attachment_reads`), from the vertex function at the
/// rendered level and layer, written, of a depth or stencil attachment, of an image the device /// rendered level and layer, written, of a depth or stencil attachment, of an image the device
/// takes neither the feedback usage nor a shadow for (its format's image, or in place over a /// takes neither the feedback usage nor a shadow for (its format's image, or in place over a
/// buffer its linear image), or of an image two attachments of the pass render; through a /// buffer its linear image), or of an image two attachments of the pass render; through a shadow, which holds
/// shadow, which holds one layer, an attachment of a layered pass or a 3D texture's depth /// one layer, an attachment of a layered pass or a 3D texture's depth plane; and on any
/// plane; and a surface plane the pass renders in its stand-in, an optimal image of the /// device, a surface plane the pass renders in its stand-in, an optimal image of the
/// runtime's that holds what the pass renders until its end copies it into the plane (a plane /// runtime's that holds what the pass renders until its end copies it into the plane (a plane
/// whose format the device's `LINEAR` tiling renders only beside other such planes, in a pass /// whose format the device's `LINEAR` tiling renders only beside other such planes, in a pass
/// that sets another attachment beside it or resolves into it). /// that sets another attachment beside it or resolves into it).
@@ -2213,16 +2170,6 @@ pub enum DrawKind {
/// (`VUID-VkGraphicsPipelineCreateInfo-sampleLocationsEnable-01524`). Metal interpolates such a /// (`VUID-VkGraphicsPipelineCreateInfo-sampleLocationsEnable-01524`). Metal interpolates such a
/// varying at the sample's own position. /// varying at the sample's own position.
SamplePositions, SamplePositions,
/// `drawMeshThreadgroupsWithIndirectBuffer:` through a mesh render pipeline state with an
/// object function
/// ([`RenderCommandEncoder::draw_mesh_threadgroups_indirect`](crate::RenderCommandEncoder::draw_mesh_threadgroups_indirect)):
/// its object grid is the GPU's to read, and one past the device's task limits
/// (`maxTaskWorkGroupCount` along an axis, `maxTaskWorkGroupTotalCount` in all) runs in pieces
/// whose number only the counts decide, which the runtime never reads on the host and no
/// command inside the pass can write. Metal draws it. The same grid drawn directly runs, and
/// so does an indirect draw of a state without an object function, whose launcher reads the
/// counts on the GPU.
IndirectObjectGrid,
} }
/// What a render pass asks that the runtime does not build ([`Gap::RenderPass`]). /// What a render pass asks that the runtime does not build ([`Gap::RenderPass`]).
@@ -2243,9 +2190,8 @@ pub enum RenderPassKind {
/// A resolve the runtime does not build: into a resolve texture of another pixel format than /// A resolve the runtime does not build: into a resolve texture of another pixel format than
/// its attachment's (the format's sRGB twin among them), of more than one sample, or whose /// its attachment's (the format's sRGB twin among them), of more than one sample, or whose
/// level is not the attachment level's width and height; of an attachment of one sample; of /// level is not the attachment level's width and height; of an attachment of one sample; of
/// an extended-range color attachment but `BGR10_XR` and `BGRA10_XR` (whose codes average as /// an extended-range, bfloat or YCbCr color attachment, whose image Vulkan's average would
/// their values do), or a bfloat or YCbCr one, whose image Vulkan's average would read in its /// read in its own encoding; or of a depth and a stencil attachment into two views
/// own encoding; or of a depth and a stencil attachment into two views
/// (VUID-VkRenderingInfo-pDepthAttachment-06086). /// (VUID-VkRenderingInfo-pDepthAttachment-06086).
Resolve, Resolve,
/// A resolve into a texture made without `RenderTarget` usage (and not of Metal's unknown /// A resolve into a texture made without `RenderTarget` usage (and not of Metal's unknown
@@ -2329,8 +2275,7 @@ pub enum RenderPassKind {
/// `setColorStoreAction:atIndex:` family. /// `setColorStoreAction:atIndex:` family.
StoreAction, StoreAction,
/// A `Clear` load action on an attachment whose format the runtime clears only through a /// A `Clear` load action on an attachment whose format the runtime clears only through a
/// shader: an extended-range format but `BGR10_XR` and `BGRA10_XR`, or a bfloat or YCbCr /// shader: an extended-range, bfloat or YCbCr format.
/// format.
ClearFormat, ClearFormat,
/// A pass with no attachment wider or taller than the device's `maxFramebufferWidth` or /// A pass with no attachment wider or taller than the device's `maxFramebufferWidth` or
/// `maxFramebufferHeight`: Vulkan's rendering covers at most that /// `maxFramebufferHeight`: Vulkan's rendering covers at most that
@@ -2373,43 +2318,6 @@ pub enum TextureViewKind {
TextureBuffer, TextureBuffer,
} }
/// Which of Metal's rules for a `GBGR422` or `BGRG422` texture a descriptor or a view breaks
/// ([`Refusal::ChromaPairs`]).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChromaPairsRule {
/// A texture type other than `Type2D`.
TextureType,
/// An odd width.
OddWidth,
/// More than one mipmap level.
Levels,
/// A view of the texture, of any format, type or range.
View,
}
/// What use of a `GBGR422` or `BGRG422` texture the runtime does not build
/// ([`Gap::ChromaPairsUse`]).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChromaPairsGap {
/// `ShaderWrite` usage, or Metal's unknown usage, which the runtime takes as every usage.
ShaderWrite,
/// `RenderTarget` usage.
RenderTarget,
/// A swizzle other than each channel from itself.
Swizzle,
/// A draw or dispatch binds the texture at a slot a function compiled outside the runtime
/// reads, or, while one lives on the device, runs such a function that may reach a `float`
/// colour texture through a handle: no lowering for the texture made that function.
CompiledFunction,
/// A copy between a buffer and the texture of more than one row whose buffer rows are closer
/// together than the region's rows are long, which Metal takes (the source's rows then
/// overlap); one Vulkan copy region takes no row stride below its width
/// (`VUID-VkBufferImageCopy-bufferRowLength-09101`), and a region a row would express it.
CloseRows,
}
/// Why an observing kernel's partial-threadgroups variant does not run a grid that ends in /// Why an observing kernel's partial-threadgroups variant does not run a grid that ends in
/// partial threadgroups ([`Gap::PartialThreadgroups`]). Metal has no counterpart: Metal runs every /// partial threadgroups ([`Gap::PartialThreadgroups`]). Metal has no counterpart: Metal runs every
/// partial threadgroup. /// partial threadgroup.
@@ -2493,32 +2401,6 @@ pub enum TextureBacking {
Drawable, Drawable,
} }
/// A Vulkan limit on a task or a mesh workgroup ([`Limit::MeshThreadgroupThreads`]), of the
/// stage the limit names: the task stage's for an object function, the mesh stage's for a mesh
/// function. No Metal counterpart.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WorkGroupLimit {
/// `maxTaskWorkGroupInvocations` or `maxMeshWorkGroupInvocations`.
Invocations,
/// `maxTaskWorkGroupSize[0]` or `maxMeshWorkGroupSize[0]`: the stage's workgroup runs its
/// threads in one row.
Width,
}
impl WorkGroupLimit {
/// The limit's name in `VkPhysicalDeviceMeshShaderPropertiesEXT` for `stage`'s workgroup:
/// the task stage's for [`Stage::Object`], the mesh stage's otherwise.
pub fn vulkan_name(self, stage: Stage) -> &'static str {
match (stage, self) {
(Stage::Object, WorkGroupLimit::Invocations) => "maxTaskWorkGroupInvocations",
(Stage::Object, WorkGroupLimit::Width) => "maxTaskWorkGroupSize[0]",
(_, WorkGroupLimit::Invocations) => "maxMeshWorkGroupInvocations",
(_, WorkGroupLimit::Width) => "maxMeshWorkGroupSize[0]",
}
}
}
/// No Metal counterpart: a limit of the device or of the runtime a call ran into, with what it was /// No Metal counterpart: a limit of the device or of the runtime a call ran into, with what it was
/// asked. /// asked.
#[non_exhaustive] #[non_exhaustive]
@@ -2571,41 +2453,6 @@ pub enum Limit {
/// The state's `maxTotalThreadsPerThreadgroup` on this device. /// The state's `maxTotalThreadsPerThreadgroup` on this device.
max: u32, max: u32,
}, },
/// A mesh draw whose object or mesh threadgroup is within Metal's maximum for its stage and
/// past the mesh render pipeline state's on this device
/// ([`RenderPipelineState::max_total_threads_per_object_threadgroup`](crate::RenderPipelineState::max_total_threads_per_object_threadgroup),
/// [`max_total_threads_per_mesh_threadgroup`](crate::RenderPipelineState::max_total_threads_per_mesh_threadgroup)):
/// the state answers the least of Metal's maximum and the stage's Vulkan limits, and `limit`
/// is the one that holds it, `device` its value on this device. Metal runs the threadgroup; one
/// past Metal's own maximum is [`Refusal::ThreadgroupSize`]. Each is counted in
/// [`Metrics::mesh_threadgroups_past_device`](crate::Metrics::mesh_threadgroups_past_device).
///
/// Basis: device (the device's task and mesh work-group limits).
MeshThreadgroupThreads {
/// The stage: [`Stage::Object`] or [`Stage::Mesh`].
stage: Stage,
/// The threadgroup size the draw asked for.
size: [u32; 3],
/// The state's maximum for the stage on this device.
max: u32,
/// The Vulkan limit that holds the state's maximum there.
limit: WorkGroupLimit,
/// That limit's value on this device.
device: u32,
},
/// A mesh draw of an object function over more object threadgroups than one draw launches on
/// this device: a grid past the device's task limits (`maxTaskWorkGroupCount`,
/// `maxTaskWorkGroupTotalCount`) runs in pieces of one multi-draw, whose records lie in one
/// parameter ring chunk, so `max` is those records' count times the threadgroups of a piece.
/// Metal states no limit on an object grid.
///
/// Basis: ours (a ring chunk is 64 KiB).
ObjectThreadgroups {
/// The object threadgroups the draw asked for.
groups: [u32; 3],
/// The most one draw launches on this device.
max: u64,
},
/// `setBytes` data longer than one parameter ring chunk. Metal documents the call for data /// `setBytes` data longer than one parameter ring chunk. Metal documents the call for data
/// under 4 KB. /// under 4 KB.
/// ///
@@ -3083,10 +2930,6 @@ impl fmt::Display for Refusal {
"patches are drawn with a post-tessellation vertex function's pipeline state, and \ "patches are drawn with a post-tessellation vertex function's pipeline state, and \
only with one", only with one",
), ),
Refusal::MeshDraw => f.write_str(
"a mesh render pipeline state draws only mesh draws, not primitives, patches or \
an indirect command buffer's commands",
),
Refusal::NoTessellationFactorBuffer => { Refusal::NoTessellationFactorBuffer => {
f.write_str("a draw of patches needs a tessellation factor buffer") f.write_str("a draw of patches needs a tessellation factor buffer")
} }
@@ -3197,10 +3040,6 @@ impl fmt::Display for Refusal {
Refusal::TextureSwizzleWithWrites => { Refusal::TextureSwizzleWithWrites => {
f.write_str("a swizzled texture takes no shader-write or render-target usage") f.write_str("a swizzled texture takes no shader-write or render-target usage")
} }
Refusal::ChromaPairs { pixel_format, rule } => write!(
f,
"a {pixel_format:?} texture breaks Metal's rule of the format: {rule:?}"
),
Refusal::TextureBytesPrivate => { Refusal::TextureBytesPrivate => {
f.write_str("the CPU reaches no Private or Memoryless texture") f.write_str("the CPU reaches no Private or Memoryless texture")
} }
@@ -3479,6 +3318,9 @@ impl fmt::Display for Gap {
"a grid of {threads_per_grid:?} threads in threadgroups of {threads_per_threadgroup:?} ends in partial threadgroups, which this kernel's variant does not run" "a grid of {threads_per_grid:?} threads in threadgroups of {threads_per_threadgroup:?} ends in partial threadgroups, which this kernel's variant does not run"
), ),
Gap::MemorylessTexture => f.write_str("Memoryless textures are not built"), Gap::MemorylessTexture => f.write_str("Memoryless textures are not built"),
Gap::CubicSampler => {
f.write_str("a cubic sampler filter, which the runtime makes as nearest")
}
Gap::TextureBufferSwizzle { pixel_format } => write!( Gap::TextureBufferSwizzle { pixel_format } => write!(
f, f,
"a swizzled texture buffer of {pixel_format:?} is not built" "a swizzled texture buffer of {pixel_format:?} is not built"
@@ -3487,9 +3329,6 @@ impl fmt::Display for Gap {
f, f,
"no texture of {pixel_format:?} is made on this device for the usage" "no texture of {pixel_format:?} is made on this device for the usage"
), ),
Gap::ChromaPairsUse { cause } => {
write!(f, "a 4:2:2 texture's {cause:?} is not built")
}
Gap::MipmapFilter { pixel_format } => write!( Gap::MipmapFilter { pixel_format } => write!(
f, f,
"mipmaps of a {pixel_format:?} texture, whose image this device's blits do not filter" "mipmaps of a {pixel_format:?} texture, whose image this device's blits do not filter"
@@ -3623,23 +3462,6 @@ impl fmt::Display for Limit {
"a threadgroup of {size:?} threads is within Metal's limit for the kernel and past \ "a threadgroup of {size:?} threads is within Metal's limit for the kernel and past \
this device's {max}" this device's {max}"
), ),
Limit::MeshThreadgroupThreads {
stage,
size,
max,
limit,
device,
} => write!(
f,
"a mesh draw's {stage:?} threadgroup of {size:?} threads is within Metal's limit \
and past this device's {max}, which its {} of {device} holds",
limit.vulkan_name(*stage)
),
Limit::ObjectThreadgroups { groups, max } => write!(
f,
"a mesh draw of {groups:?} object threadgroups is past the {max} one draw \
launches on this device"
),
Limit::BytesLength { len, max } => { Limit::BytesLength { len, max } => {
write!(f, "{len} bytes are past the most one call takes, {max}") write!(f, "{len} bytes are past the most one call takes, {max}")
} }
@@ -31,7 +31,6 @@ impl Refusal {
Refusal::NoPipeline => RefusalBasis::MetalDocumented, Refusal::NoPipeline => RefusalBasis::MetalDocumented,
Refusal::CommandRange => RefusalBasis::MetalDocumented, Refusal::CommandRange => RefusalBasis::MetalDocumented,
Refusal::PatchDraw => RefusalBasis::MetalMeasured, Refusal::PatchDraw => RefusalBasis::MetalMeasured,
Refusal::MeshDraw => RefusalBasis::Ours,
Refusal::NoTessellationFactorBuffer => RefusalBasis::MetalMeasured, Refusal::NoTessellationFactorBuffer => RefusalBasis::MetalMeasured,
Refusal::IndexedPatchDrawWithoutIndexType => RefusalBasis::MetalMeasured, Refusal::IndexedPatchDrawWithoutIndexType => RefusalBasis::MetalMeasured,
Refusal::PatchDrawWithIndexType { .. } => RefusalBasis::MetalMeasured, Refusal::PatchDrawWithIndexType { .. } => RefusalBasis::MetalMeasured,
@@ -68,7 +67,6 @@ impl Refusal {
Refusal::TextureViewSlices { .. } => RefusalBasis::MetalDocumented, Refusal::TextureViewSlices { .. } => RefusalBasis::MetalDocumented,
Refusal::TextureViewFormat { .. } => RefusalBasis::MetalMeasured, Refusal::TextureViewFormat { .. } => RefusalBasis::MetalMeasured,
Refusal::MipmapFormat { .. } => RefusalBasis::MetalMeasured, Refusal::MipmapFormat { .. } => RefusalBasis::MetalMeasured,
Refusal::ChromaPairs { .. } => RefusalBasis::MetalMeasured,
Refusal::TextureCopyMismatch { .. } => RefusalBasis::MetalDocumented, Refusal::TextureCopyMismatch { .. } => RefusalBasis::MetalDocumented,
Refusal::AliasingCopy { .. } => RefusalBasis::MetalMeasured, Refusal::AliasingCopy { .. } => RefusalBasis::MetalMeasured,
Refusal::ManagedTextureBytes { .. } => RefusalBasis::Ours, Refusal::ManagedTextureBytes { .. } => RefusalBasis::Ours,
@@ -119,8 +117,6 @@ impl Limit {
Limit::BlockIds => RefusalBasis::Ours, Limit::BlockIds => RefusalBasis::Ours,
Limit::ThreadgroupMemory { .. } => RefusalBasis::Device, Limit::ThreadgroupMemory { .. } => RefusalBasis::Device,
Limit::ThreadgroupThreads { .. } => RefusalBasis::Device, Limit::ThreadgroupThreads { .. } => RefusalBasis::Device,
Limit::MeshThreadgroupThreads { .. } => RefusalBasis::Device,
Limit::ObjectThreadgroups { .. } => RefusalBasis::Ours,
Limit::BytesLength { .. } => RefusalBasis::Ours, Limit::BytesLength { .. } => RefusalBasis::Ours,
Limit::IndexRange { .. } => RefusalBasis::Ours, Limit::IndexRange { .. } => RefusalBasis::Ours,
Limit::TextureSize { .. } => RefusalBasis::Device, Limit::TextureSize { .. } => RefusalBasis::Device,
@@ -158,8 +154,8 @@ impl Gap {
Gap::MemorylessTexture => RefusalBasis::Ours, Gap::MemorylessTexture => RefusalBasis::Ours,
Gap::TextureBufferSwizzle { .. } => RefusalBasis::Ours, Gap::TextureBufferSwizzle { .. } => RefusalBasis::Ours,
Gap::TextureFormat { .. } => RefusalBasis::Ours, Gap::TextureFormat { .. } => RefusalBasis::Ours,
Gap::ChromaPairsUse { .. } => RefusalBasis::Ours,
Gap::MipmapFilter { .. } => RefusalBasis::Ours, Gap::MipmapFilter { .. } => RefusalBasis::Ours,
Gap::CubicSampler => RefusalBasis::Ours,
Gap::TextureBytes { .. } => RefusalBasis::Ours, Gap::TextureBytes { .. } => RefusalBasis::Ours,
Gap::TextureCopy { .. } => RefusalBasis::Ours, Gap::TextureCopy { .. } => RefusalBasis::Ours,
Gap::OverlappingCopy { .. } => RefusalBasis::Ours, Gap::OverlappingCopy { .. } => RefusalBasis::Ours,
+32 -13
View File
@@ -165,15 +165,10 @@ impl Event {
} }
} }
impl SharedEvent { impl Event {
/// `signaledValue`: the higher of the value of the signal the semaphore's count reached and the /// Reads the Metal timeline value for checkpointing.
/// host's floor, that count being one a host wait confirmed: a counter read finds it, and a
/// wait with a timeout of 0 confirms it where it is above the count last confirmed. Where the
/// value rose since the host last saw it, the Shared memory command buffers in flight may
/// write is flushed and invalidated first (`crate::coherence`), so the host reads what the GPU
/// wrote before its signal.
pub fn signaled_value(&self) -> u64 { pub fn signaled_value(&self) -> u64 {
let inner = &self.event.inner; let inner = &self.inner;
let (signalled, floor) = { let (signalled, floor) = {
let state = lock(&inner.state); let state = lock(&inner.state);
// A lost device answers with what was seen before the loss. // A lost device answers with what was seen before the loss.
@@ -188,11 +183,16 @@ impl SharedEvent {
signalled.max(floor) signalled.max(floor)
} }
/// `setSignaledValue:`: raises the host's floor to `value`; a value not above it changes /// Restores the Metal timeline value on a freshly created event.
/// nothing. The semaphore is never signalled from the host. Segments the submit thread holds pub fn restore_signaled_value(&self, value: u64) -> Result<(), Error> {
/// and host waits that the new value meets go on, and listeners it reaches run. // The Vulkan semaphore counts submissions, independently of the Metal value.
pub fn set_signaled_value(&self, value: u64) { // Raising the host floor also satisfies waits on the restored value.
let inner = &self.event.inner; self.set_floor(value);
Ok(())
}
fn set_floor(&self, value: u64) {
let inner = &self.inner;
let reached = { let reached = {
let mut state = lock(&inner.state); let mut state = lock(&inner.state);
if value <= state.floor { if value <= state.floor {
@@ -208,6 +208,25 @@ impl SharedEvent {
core.done.fire(core, Arc::clone(inner)); core.done.fire(core, Arc::clone(inner));
} }
} }
}
impl SharedEvent {
/// `signaledValue`: the higher of the value of the signal the semaphore's count reached and the
/// host's floor, that count being one a host wait confirmed: a counter read finds it, and a
/// wait with a timeout of 0 confirms it where it is above the count last confirmed. Where the
/// value rose since the host last saw it, the Shared memory command buffers in flight may
/// write is flushed and invalidated first (`crate::coherence`), so the host reads what the GPU
/// wrote before its signal.
pub fn signaled_value(&self) -> u64 {
self.event.signaled_value()
}
/// `setSignaledValue:`: raises the host's floor to `value`; a value not above it changes
/// nothing. The semaphore is never signalled from the host. Segments the submit thread holds
/// and host waits that the new value meets go on, and listeners it reaches run.
pub fn set_signaled_value(&self, value: u64) {
self.event.set_floor(value);
}
/// `waitUntilSignaledValue:timeoutMS:`: true once [`signaled_value`](Self::signaled_value) /// `waitUntilSignaledValue:timeoutMS:`: true once [`signaled_value`](Self::signaled_value)
/// reaches `value`, false when `timeout` passes first. /// reaches `value`, false when `timeout` passes first.
+67 -81
View File
@@ -146,9 +146,10 @@ const _: () = {
/// The device extension of the attachment feedback loop (`VK_EXT_attachment_feedback_loop_layout`), /// The device extension of the attachment feedback loop (`VK_EXT_attachment_feedback_loop_layout`),
/// through which a draw reads, through a texture, an attachment its own pass renders (Metal's /// through which a draw reads, through a texture, an attachment its own pass renders (Metal's
/// texture read of a render target): its layout, its image usage and its pipeline flag, which every /// texture read of a render target): its layout, its image usage and its pipeline flag, which every
/// render pipeline takes. Device creation enables it, with its feature, where the device lists it /// render pipeline takes. Device creation enables it, with its feature, where the device reads
/// and reports the feature, and not otherwise. A device without it reads attachments through a /// attachments (`Capabilities::attachment_reads`), lists it and reports the feature, and not
/// copy of the image (`Capabilities::feedback_loop`). /// otherwise. A device that reads attachments without it reads through a copy of the image
/// (`Capabilities::feedback_loop`).
pub const ATTACHMENT_READ_EXTENSIONS: &[&CStr] = &[ash::ext::attachment_feedback_loop_layout::NAME]; pub const ATTACHMENT_READ_EXTENSIONS: &[&CStr] = &[ash::ext::attachment_feedback_loop_layout::NAME];
/// The device extension of a sampler's border colour through a view's component mapping /// The device extension of a sampler's border colour through a view's component mapping
@@ -174,14 +175,6 @@ pub const BORDER_SWIZZLE_EXTENSIONS: &[&CStr] = &[
/// otherwise, so [`Device::extensions`](crate::Device::extensions) names it only with its feature. /// otherwise, so [`Device::extensions`](crate::Device::extensions) names it only with its feature.
pub const BARYCENTRIC_EXTENSIONS: &[&CStr] = &[ash::khr::fragment_shader_barycentric::NAME]; pub const BARYCENTRIC_EXTENSIONS: &[&CStr] = &[ash::khr::fragment_shader_barycentric::NAME];
/// The device extension of Metal's object and mesh functions (`VK_EXT_mesh_shader`): device
/// creation enables it, with three features (`taskShader`, `meshShader` and `multiDrawIndirect`),
/// where the device lists it and reports all three, and none of them otherwise, so
/// [`Device::extensions`](crate::Device::extensions) names it only with its stages. A device
/// without them refuses every mesh render pipeline state (the translator's
/// `Unsupported{MeshShading}`, naming what the device lacks).
pub const MESH_EXTENSIONS: &[&CStr] = &[ash::ext::mesh_shader::NAME];
/// The device extensions of Metal's indirect command buffers of draws /// The device extensions of Metal's indirect command buffers of draws
/// (`VK_EXT_device_generated_commands`) and of the one structure its preprocess memory takes /// (`VK_EXT_device_generated_commands`) and of the one structure its preprocess memory takes
/// beside it (`VkBufferUsageFlags2CreateInfoKHR`, for `VK_BUFFER_USAGE_2_PREPROCESS_BUFFER_BIT_EXT`), /// beside it (`VkBufferUsageFlags2CreateInfoKHR`, for `VK_BUFFER_USAGE_2_PREPROCESS_BUFFER_BIT_EXT`),
@@ -259,8 +252,6 @@ pub(crate) fn shader_extension(name: &CStr) -> Option<VkExtension> {
Some(VkExtension::ExtExtendedDynamicState) Some(VkExtension::ExtExtendedDynamicState)
} else if name == ash::ext::sample_locations::NAME { } else if name == ash::ext::sample_locations::NAME {
Some(VkExtension::ExtSampleLocations) Some(VkExtension::ExtSampleLocations)
} else if name == ash::ext::mesh_shader::NAME {
Some(VkExtension::ExtMeshShader)
} else { } else {
None None
} }
@@ -299,14 +290,6 @@ pub(crate) const SAMPLER_ELEMENTS: u32 = SAMPLERS + SAMPLER_VARIANTS;
/// Sampler arrays: one per use of a sampler (plain, depth comparison, integer texture). /// Sampler arrays: one per use of a sampler (plain, depth comparison, integer texture).
pub(crate) const SAMPLER_ARRAYS: u32 = 3; pub(crate) const SAMPLER_ARRAYS: u32 = 3;
/// The sampler descriptors of set 1: each array's [`SAMPLER_ELEMENTS`] (`crate::arrays`).
pub(crate) const SAMPLER_DESCRIPTORS: u32 = SAMPLER_ARRAYS * SAMPLER_ELEMENTS;
/// The sampled images of set 1 against the descriptor limits: the sampled-texture array's
/// textures and second elements (`crate::arrays::SAMPLED_ELEMENTS`), and the uniform texel
/// buffers, which count as sampled images.
const SAMPLED_IMAGES: u32 = crate::arrays::SAMPLED_ELEMENTS + TEXTURES;
/// Threads in one compute workgroup: Metal's most threads per threadgroup. /// Threads in one compute workgroup: Metal's most threads per threadgroup.
pub(crate) const WORKGROUP_INVOCATIONS: u32 = 1024; pub(crate) const WORKGROUP_INVOCATIONS: u32 = 1024;
@@ -469,10 +452,6 @@ pub struct Features {
/// `VkPhysicalDeviceExtendedDynamicStateFeaturesEXT`, of `VK_EXT_extended_dynamic_state`: read /// `VkPhysicalDeviceExtendedDynamicStateFeaturesEXT`, of `VK_EXT_extended_dynamic_state`: read
/// and enabled only where the device lists it ([`OPTIONAL_EXTENSIONS`]). /// and enabled only where the device lists it ([`OPTIONAL_EXTENSIONS`]).
pub extended_dynamic_state: vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT<'static>, pub extended_dynamic_state: vk::PhysicalDeviceExtendedDynamicStateFeaturesEXT<'static>,
/// `VkPhysicalDeviceMeshShaderFeaturesEXT`, of `VK_EXT_mesh_shader`: read where the device
/// lists it, and `taskShader` and `meshShader` enabled with `multiDrawIndirect`
/// ([`MESH_EXTENSIONS`]); none of its other features.
pub mesh: vk::PhysicalDeviceMeshShaderFeaturesEXT<'static>,
} }
/// One feature: the Vulkan structure that reports it, its member as ash spells it, the member, and /// One feature: the Vulkan structure that reports it, its member as ash spells it, the member, and
@@ -551,9 +530,6 @@ macro_rules! feature {
(@structure extended_dynamic_state) => { (@structure extended_dynamic_state) => {
"VkPhysicalDeviceExtendedDynamicStateFeaturesEXT" "VkPhysicalDeviceExtendedDynamicStateFeaturesEXT"
}; };
(@structure mesh) => {
"VkPhysicalDeviceMeshShaderFeaturesEXT"
};
(@translator) => { (@translator) => {
None None
}; };
@@ -781,6 +757,7 @@ pub(crate) const OPTIONAL: &[Feature] = &[
// the device offers it, else a branch over the offset's values, each with its value as // the device offers it, else a branch over the offset's values, each with its value as
// `ConstOffset` (Vulkan 1.0's). // `ConstOffset` (Vulkan 1.0's).
feature!(maintenance8.maintenance8 => Maintenance8), feature!(maintenance8.maintenance8 => Maintenance8),
feature!(core.multi_draw_indirect),
]; ];
/// The feature of the attachment feedback loop ([`ATTACHMENT_READ_EXTENSIONS`]): enabled where the /// The feature of the attachment feedback loop ([`ATTACHMENT_READ_EXTENSIONS`]): enabled where the
@@ -894,16 +871,6 @@ pub(crate) const PIPELINE_ROBUSTNESS: &[Feature] =
/// epilog lookup calls through a null pointer. /// epilog lookup calls through a null pointer.
pub(crate) const EXTENDED_DYNAMIC_STATE: &[Feature] = pub(crate) const EXTENDED_DYNAMIC_STATE: &[Feature] =
&[feature!(extended_dynamic_state.extended_dynamic_state => ExtendedDynamicState)]; &[feature!(extended_dynamic_state.extended_dynamic_state => ExtendedDynamicState)];
/// The features of Metal's object and mesh functions ([`MESH_EXTENSIONS`]): enabled together where
/// the device lists `VK_EXT_mesh_shader` and reports all three, and none otherwise. An object
/// function is a task shader and a mesh function a mesh shader, and an object grid past the task
/// limits runs in pieces of one multi-draw (`multiDrawIndirect`), so a device that lacks any one
/// of them takes no mesh render pipeline state. No answer chooses a second form.
pub(crate) const MESH_STAGES: &[Feature] = &[
feature!(mesh.task_shader => TaskShader),
feature!(mesh.mesh_shader => MeshShader),
feature!(core.multi_draw_indirect => MultiDrawIndirect),
];
/// The features of [`INDIRECT_COMMANDS`]: enabled together where the device offers indirect /// The features of [`INDIRECT_COMMANDS`]: enabled together where the device offers indirect
/// command buffers ([`IndirectCommandLimits`]), and neither otherwise. The translator is told of /// command buffers ([`IndirectCommandLimits`]), and neither otherwise. The translator is told of
@@ -938,7 +905,6 @@ pub(crate) const ENABLED: &[&[Feature]] = &[
PIPELINE_ROBUSTNESS, PIPELINE_ROBUSTNESS,
EXTENDED_DYNAMIC_STATE, EXTENDED_DYNAMIC_STATE,
INDIRECT_COMMAND_FEATURES, INDIRECT_COMMAND_FEATURES,
MESH_STAGES,
]; ];
/// Each feature of a table device creation enables ([`ENABLED`]) that the translator names, with /// Each feature of a table device creation enables ([`ENABLED`]) that the translator names, with
@@ -956,7 +922,6 @@ pub(crate) fn creation_extensions() -> impl Iterator<Item = &'static CStr> {
.chain(BORDER_SWIZZLE_EXTENSIONS) .chain(BORDER_SWIZZLE_EXTENSIONS)
.chain(BARYCENTRIC_EXTENSIONS) .chain(BARYCENTRIC_EXTENSIONS)
.chain(INDIRECT_COMMANDS) .chain(INDIRECT_COMMANDS)
.chain(MESH_EXTENSIONS)
.copied() .copied()
} }
@@ -1167,23 +1132,23 @@ pub struct Capabilities {
/// takes the offset as its own `Offset` operand. Where it is false, the sample branches over /// takes the offset as its own `Offset` operand. Where it is false, the sample branches over
/// the offset's values, each branch with its value as `ConstOffset`. /// the offset's values, each branch with its value as `ConstOffset`.
pub texel_offset_operand: bool, pub texel_offset_operand: bool,
/// Always true: the floor's descriptor limits hold the sampled-texture array's second /// The device's descriptor limits hold the sampled-texture array's second elements beside the
/// elements, so a draw may read, through a texture, an attachment its own pass renders on /// floor's arrays: a draw may read, through a texture, an attachment its own pass renders, as
/// every device, as Metal reads a render target. It reads through the attachment feedback loop /// Metal reads a render target. It reads through the attachment feedback loop where
/// where [`feedback_loop`](Self::feedback_loop) holds, and through a copy of the image /// [`feedback_loop`](Self::feedback_loop) holds, and through a copy of the image otherwise.
/// otherwise. Kept for the consumers that report it; the runtime reads it nowhere.
pub attachment_reads: bool, pub attachment_reads: bool,
/// The attachment-read feature holds, with /// The attachment reads hold, and so does the attachment-read feature, with
/// [`ATTACHMENT_READ_EXTENSIONS`]: a draw reads an attachment through the attachment feedback /// [`ATTACHMENT_READ_EXTENSIONS`]: a draw reads an attachment through the attachment feedback
/// loop, the feedback layout its image moves to and the colour flag the pipelines of a state /// loop, the feedback layout its image moves to and the colour flag the pipelines of a state
/// whose functions can read a texture take. /// whose functions can read a texture take.
pub feedback_loop: bool, pub feedback_loop: bool,
/// Whether `bufferDeviceAddressCaptureReplay` is enabled for checkpoint/restore.
pub buffer_device_address_capture_replay: bool,
/// The features device creation enables: every one the floor requires, each of the optional, /// The features device creation enables: every one the floor requires, each of the optional,
/// step-rate, min-LOD, fill-mode, alpha-to-one, quad-control, pixel-interlock, linear-attachment /// step-rate, min-LOD, fill-mode, alpha-to-one, quad-control, pixel-interlock, linear-attachment
/// and fault-report ones the device reports, the attachment-read ones where /// and fault-report ones the device reports, the attachment-read ones where
/// [`feedback_loop`](Self::feedback_loop) holds, the border-swizzle ones where the device reports /// [`feedback_loop`](Self::feedback_loop) holds, the border-swizzle ones where the device reports
/// both, the barycentric one where the device lists its extension and reports it, and the /// both, and the barycentric one where the device lists its extension and reports it.
/// mesh stages' three where the device lists `VK_EXT_mesh_shader` and reports all three.
pub features: Features, pub features: Features,
/// The device extensions device creation enables: [`DEVICE_EXTENSIONS`], then each of /// The device extensions device creation enables: [`DEVICE_EXTENSIONS`], then each of
/// [`OPTIONAL_EXTENSIONS`] the device lists, then [`ATTACHMENT_READ_EXTENSIONS`] where /// [`OPTIONAL_EXTENSIONS`] the device lists, then [`ATTACHMENT_READ_EXTENSIONS`] where
@@ -1191,9 +1156,7 @@ pub struct Capabilities {
/// device lists them and reports both the border swizzle's features, then /// device lists them and reports both the border swizzle's features, then
/// [`BARYCENTRIC_EXTENSIONS`] where the device lists it and reports its feature, then /// [`BARYCENTRIC_EXTENSIONS`] where the device lists it and reports its feature, then
/// [`INDIRECT_COMMANDS`] where the device lists both and reports their features /// [`INDIRECT_COMMANDS`] where the device lists both and reports their features
/// ([`indirect_commands`](Self::indirect_commands)), then [`MESH_EXTENSIONS`] where the device /// ([`indirect_commands`](Self::indirect_commands)).
/// lists it and reports its three features (`taskShader`, `meshShader` and
/// `multiDrawIndirect`).
pub extensions: Vec<&'static CStr>, pub extensions: Vec<&'static CStr>,
/// The first queue family with graphics and compute, whose timestamps the floor checked. /// The first queue family with graphics and compute, whose timestamps the floor checked.
pub queue_family: u32, pub queue_family: u32,
@@ -1202,6 +1165,19 @@ pub struct Capabilities {
/// What an indirect command buffer's execution may take, where device creation enables /// What an indirect command buffer's execution may take, where device creation enables
/// [`INDIRECT_COMMANDS`]; `None` on a device without them. /// [`INDIRECT_COMMANDS`]; `None` on a device without them.
pub indirect_commands: Option<IndirectCommandLimits>, pub indirect_commands: Option<IndirectCommandLimits>,
/// The physical limit for draws in one Vulkan indirect draw command.
pub max_draw_indirect_count: u32,
}
impl Capabilities {
/// The effective multi-draw limit when the runtime opts in and device creation enables it.
pub(crate) fn draw_indirect_limit(&self, enabled: bool) -> u32 {
if enabled && self.features.core.multi_draw_indirect == vk::TRUE {
self.max_draw_indirect_count
} else {
0
}
}
} }
impl std::fmt::Debug for Capabilities { impl std::fmt::Debug for Capabilities {
@@ -1226,6 +1202,7 @@ impl std::fmt::Debug for Capabilities {
.field("extensions", &self.extensions) .field("extensions", &self.extensions)
.field("queue_family", &self.queue_family) .field("queue_family", &self.queue_family)
.field("indirect_commands", &self.indirect_commands) .field("indirect_commands", &self.indirect_commands)
.field("max_draw_indirect_count", &self.max_draw_indirect_count)
.finish_non_exhaustive() .finish_non_exhaustive()
} }
} }
@@ -1343,7 +1320,6 @@ unsafe fn query(
let maintenance8_listed = listed(MAINTENANCE8); let maintenance8_listed = listed(MAINTENANCE8);
let pipeline_robustness_listed = listed(ash::ext::pipeline_robustness::NAME); let pipeline_robustness_listed = listed(ash::ext::pipeline_robustness::NAME);
let extended_dynamic_state_listed = listed(ash::ext::extended_dynamic_state::NAME); let extended_dynamic_state_listed = listed(ash::ext::extended_dynamic_state::NAME);
let mesh_listed = listed(ash::ext::mesh_shader::NAME);
let Features { let Features {
core, core,
@@ -1368,7 +1344,6 @@ unsafe fn query(
maintenance8, maintenance8,
pipeline_robustness, pipeline_robustness,
extended_dynamic_state, extended_dynamic_state,
mesh,
} = &mut queried.features; } = &mut queried.features;
let mut features = vk::PhysicalDeviceFeatures2::default() let mut features = vk::PhysicalDeviceFeatures2::default()
.push_next(&mut *vulkan11) .push_next(&mut *vulkan11)
@@ -1428,9 +1403,6 @@ unsafe fn query(
if extended_dynamic_state_listed { if extended_dynamic_state_listed {
features = features.push_next(&mut *extended_dynamic_state); features = features.push_next(&mut *extended_dynamic_state);
} }
if mesh_listed {
features = features.push_next(&mut *mesh);
}
instance.get_physical_device_features2(physical, &mut features); instance.get_physical_device_features2(physical, &mut features);
*core = features.features; *core = features.features;
vulkan11.p_next = std::ptr::null_mut(); vulkan11.p_next = std::ptr::null_mut();
@@ -1454,7 +1426,6 @@ unsafe fn query(
maintenance8.p_next = std::ptr::null_mut(); maintenance8.p_next = std::ptr::null_mut();
pipeline_robustness.p_next = std::ptr::null_mut(); pipeline_robustness.p_next = std::ptr::null_mut();
extended_dynamic_state.p_next = std::ptr::null_mut(); extended_dynamic_state.p_next = std::ptr::null_mut();
mesh.p_next = std::ptr::null_mut();
queried.families = instance.get_physical_device_queue_family_properties(physical); queried.families = instance.get_physical_device_queue_family_properties(physical);
queried.memory = instance.get_physical_device_memory_properties(physical); queried.memory = instance.get_physical_device_memory_properties(physical);
@@ -1539,6 +1510,10 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
let Some((queue_family, _)) = family.filter(|_| missing.is_empty()) else { let Some((queue_family, _)) = family.filter(|_| missing.is_empty()) else {
return Err(BelowFloor { missing }); return Err(BelowFloor { missing });
}; };
let capture_replay = reported.vulkan12.buffer_device_address_capture_replay == vk::TRUE;
if capture_replay {
features.vulkan12.buffer_device_address_capture_replay = vk::TRUE;
}
for feature in (OPTIONAL.iter().chain(PORTABILITY_STATED)) for feature in (OPTIONAL.iter().chain(PORTABILITY_STATED))
.chain(STEP_RATES) .chain(STEP_RATES)
.chain(MIN_LOD_CLAMPS) .chain(MIN_LOD_CLAMPS)
@@ -1551,10 +1526,9 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
} }
let listed = let listed =
|extension: &CStr| (device.extensions.iter()).any(|name| name.as_c_str() == extension); |extension: &CStr| (device.extensions.iter()).any(|name| name.as_c_str() == extension);
// The floor's limits hold the sampled-texture array's second elements let attachment_reads = second_elements_fit(device);
// (`arrays::SAMPLED_ELEMENTS`): every device that meets it reads attachments. let feedback_loop = attachment_reads
let attachment_reads = true; && ATTACHMENT_READ_EXTENSIONS.iter().all(|&name| listed(name))
let feedback_loop = ATTACHMENT_READ_EXTENSIONS.iter().all(|&name| listed(name))
&& (ATTACHMENT_READS.iter()).all(|feature| *(feature.field)(&mut reported) == vk::TRUE); && (ATTACHMENT_READS.iter()).all(|feature| *(feature.field)(&mut reported) == vk::TRUE);
if feedback_loop { if feedback_loop {
for feature in ATTACHMENT_READS { for feature in ATTACHMENT_READS {
@@ -1585,7 +1559,7 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
*(feature.field)(&mut features) = *(feature.field)(&mut reported); *(feature.field)(&mut features) = *(feature.field)(&mut reported);
} }
} }
if listed(ash::ext::pipeline_robustness::NAME) && kernel_buffers_fit(device) { if listed(ash::ext::pipeline_robustness::NAME) && kernel_buffers_fit(device, attachment_reads) {
for feature in PIPELINE_ROBUSTNESS { for feature in PIPELINE_ROBUSTNESS {
*(feature.field)(&mut features) = *(feature.field)(&mut reported); *(feature.field)(&mut features) = *(feature.field)(&mut reported);
} }
@@ -1596,13 +1570,6 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
} }
} }
let indirect_commands = indirect_commands(device, &mut features); let indirect_commands = indirect_commands(device, &mut features);
let mesh = MESH_EXTENSIONS.iter().all(|&name| listed(name))
&& (MESH_STAGES.iter()).all(|feature| *(feature.field)(&mut reported) == vk::TRUE);
if mesh {
for feature in MESH_STAGES {
*(feature.field)(&mut features) = vk::TRUE;
}
}
Ok(Capabilities { Ok(Capabilities {
float16: features.vulkan12.shader_float16 == vk::TRUE, float16: features.vulkan12.shader_float16 == vk::TRUE,
storage_read_without_format: features.core.shader_storage_image_read_without_format storage_read_without_format: features.core.shader_storage_image_read_without_format
@@ -1619,6 +1586,7 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE, texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE,
attachment_reads, attachment_reads,
feedback_loop, feedback_loop,
buffer_device_address_capture_replay: capture_replay,
features, features,
extensions: DEVICE_EXTENSIONS extensions: DEVICE_EXTENSIONS
.iter() .iter()
@@ -1635,12 +1603,12 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
.iter() .iter()
.filter(|_| indirect_commands.is_some()), .filter(|_| indirect_commands.is_some()),
) )
.chain(MESH_EXTENSIONS.iter().filter(|_| mesh))
.copied() .copied()
.collect(), .collect(),
queue_family, queue_family,
memory: device.memory, memory: device.memory,
indirect_commands, indirect_commands,
max_draw_indirect_count: device.limits.max_draw_indirect_count,
}) })
} }
@@ -1788,16 +1756,34 @@ pub(crate) fn flag_names(flags: vk::MemoryPropertyFlags) -> String {
.join(" | ") .join(" | ")
} }
/// Whether the device's descriptor limits hold the sampled-texture array's second elements
/// (`arrays::sampled_images`) beside the floor's arrays: what the attachment reads take beyond
/// [`limits`]. A uniform texel buffer counts as a sampled image, and a storage one as a storage
/// image.
fn second_elements_fit(device: &Queried) -> bool {
let limits = &device.limits;
let descriptors = &device.vulkan12;
let sampled = 3 * TEXTURES;
let storage = 2 * TEXTURES + LEVEL_ELEMENTS;
descriptors.max_per_stage_descriptor_update_after_bind_sampled_images >= sampled
&& descriptors.max_descriptor_set_update_after_bind_sampled_images >= sampled
&& descriptors.max_per_stage_update_after_bind_resources
>= sampled + storage + limits.max_color_attachments
&& descriptors.max_update_after_bind_descriptors_in_all_pools
>= sampled + storage + SAMPLER_ARRAYS * SAMPLER_ELEMENTS
}
/// Whether `maxPerStageUpdateAfterBindResources` holds the compute stage's descriptors with set 0's /// Whether `maxPerStageUpdateAfterBindResources` holds the compute stage's descriptors with set 0's
/// kernel storage buffers (`crate::arrays::buffer_bindings`): set 1's arrays (a uniform texel /// kernel storage buffers (`crate::arrays::buffer_bindings`): set 1's arrays, `seconds` their
/// buffer counting as a sampled image, a storage one as a storage image), and /// second elements' (a uniform texel buffer counting as a sampled image, a storage one as a
/// [`KERNEL_BUFFER_BINDINGS`]. It is the one limit of that layout the /// storage image), and [`KERNEL_BUFFER_BINDINGS`]. It is the one limit of that layout the
/// translator's query (`DeviceProfile::binds_kernel_buffers`) cannot count, as set 1 is the /// translator's query (`DeviceProfile::binds_kernel_buffers`) cannot count, as set 1 is the
/// runtime's: [`PIPELINE_ROBUSTNESS`] is enabled only where it holds. /// runtime's: [`PIPELINE_ROBUSTNESS`] is enabled only where it holds.
fn kernel_buffers_fit(device: &Queried) -> bool { fn kernel_buffers_fit(device: &Queried, seconds: bool) -> bool {
let sampled = crate::arrays::sampled_images(seconds) + TEXTURES;
let storage = 2 * TEXTURES + LEVEL_ELEMENTS; let storage = 2 * TEXTURES + LEVEL_ELEMENTS;
device.vulkan12.max_per_stage_update_after_bind_resources device.vulkan12.max_per_stage_update_after_bind_resources
>= SAMPLED_IMAGES + storage + KERNEL_BUFFER_BINDINGS >= sampled + storage + KERNEL_BUFFER_BINDINGS
} }
/// Each limit the floor sets: its Vulkan name, the device's value, and the least value the runtime /// Each limit the floor sets: its Vulkan name, the device's value, and the least value the runtime
@@ -1812,12 +1798,12 @@ pub(crate) fn limits(device: &Queried) -> [(&'static str, u32, u32); 17] {
( (
"maxPerStageDescriptorUpdateAfterBindSampledImages", "maxPerStageDescriptorUpdateAfterBindSampledImages",
descriptors.max_per_stage_descriptor_update_after_bind_sampled_images, descriptors.max_per_stage_descriptor_update_after_bind_sampled_images,
SAMPLED_IMAGES, 2 * TEXTURES,
), ),
( (
"maxDescriptorSetUpdateAfterBindSampledImages", "maxDescriptorSetUpdateAfterBindSampledImages",
descriptors.max_descriptor_set_update_after_bind_sampled_images, descriptors.max_descriptor_set_update_after_bind_sampled_images,
SAMPLED_IMAGES, 2 * TEXTURES,
), ),
( (
"maxPerStageDescriptorUpdateAfterBindStorageImages", "maxPerStageDescriptorUpdateAfterBindStorageImages",
@@ -1832,12 +1818,12 @@ pub(crate) fn limits(device: &Queried) -> [(&'static str, u32, u32); 17] {
( (
"maxPerStageDescriptorUpdateAfterBindSamplers", "maxPerStageDescriptorUpdateAfterBindSamplers",
descriptors.max_per_stage_descriptor_update_after_bind_samplers, descriptors.max_per_stage_descriptor_update_after_bind_samplers,
SAMPLER_DESCRIPTORS, SAMPLER_ARRAYS * SAMPLER_ELEMENTS,
), ),
( (
"maxDescriptorSetUpdateAfterBindSamplers", "maxDescriptorSetUpdateAfterBindSamplers",
descriptors.max_descriptor_set_update_after_bind_samplers, descriptors.max_descriptor_set_update_after_bind_samplers,
SAMPLER_DESCRIPTORS, SAMPLER_ARRAYS * SAMPLER_ELEMENTS,
), ),
( (
"maxSamplerAllocationCount", "maxSamplerAllocationCount",
@@ -1848,12 +1834,12 @@ pub(crate) fn limits(device: &Queried) -> [(&'static str, u32, u32); 17] {
( (
"maxPerStageUpdateAfterBindResources", "maxPerStageUpdateAfterBindResources",
descriptors.max_per_stage_update_after_bind_resources, descriptors.max_per_stage_update_after_bind_resources,
SAMPLED_IMAGES + storage + limits.max_color_attachments, 2 * TEXTURES + storage + limits.max_color_attachments,
), ),
( (
"maxUpdateAfterBindDescriptorsInAllPools", "maxUpdateAfterBindDescriptorsInAllPools",
descriptors.max_update_after_bind_descriptors_in_all_pools, descriptors.max_update_after_bind_descriptors_in_all_pools,
SAMPLED_IMAGES + storage + SAMPLER_DESCRIPTORS, 2 * TEXTURES + storage + SAMPLER_ARRAYS * SAMPLER_ELEMENTS,
), ),
( (
"maxComputeWorkGroupInvocations", "maxComputeWorkGroupInvocations",
+2 -25
View File
@@ -34,9 +34,8 @@ pub(crate) const KERNEL_ENTRIES: usize = 1024;
/// the buffer slots bound at a multiple of 4 below their argument's alignment, bit `i` the vertex /// the buffer slots bound at a multiple of 4 below their argument's alignment, bit `i` the vertex
/// function's slot `i` and bit `32 + i` the fragment function's, and the texture slots that hold /// function's slot `i` and bit `32 + i` the fragment function's, and the texture slots that hold
/// an 8-bit sRGB texture's UNORM twin, bit `i` of `srgb`'s first the vertex function's slot `i` /// an 8-bit sRGB texture's UNORM twin, bit `i` of `srgb`'s first the vertex function's slot `i`
/// and of its second the fragment function's (`RenderPipelineState::for_draws`); and for either /// and of its second the fragment function's (`RenderPipelineState::for_draws`). Each is 0 for
/// state's content for a 4:2:2 texture, where its draws or dispatches read one ([`Chroma`]). /// every other content.
/// Each is 0 for every other content.
#[derive(Clone, PartialEq, Eq, Hash)] #[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct KernelKey { pub(crate) struct KernelKey {
pub(crate) pipeline: PipelineKey, pub(crate) pipeline: PipelineKey,
@@ -44,28 +43,6 @@ pub(crate) struct KernelKey {
pub(crate) srgb: [u128; 2], pub(crate) srgb: [u128; 2],
pub(crate) words: u64, pub(crate) words: u64,
pub(crate) arrays: u8, pub(crate) arrays: u8,
pub(crate) chroma: Chroma,
}
/// Where a content's functions read a texture of `GBGR422` or `BGRG422`, which only a function
/// lowered for it decodes: `slots`' texture slots bound to one, bit `i` slot `i`, the first a
/// kernel's or a vertex function's and the second a fragment function's
/// (`LoweringInputs::chroma_pairs`), and, in `handles`, whether one may be reached through a
/// handle, a stage reaching a `float` colour texture so while a 4:2:2 texture lives on the device
/// (`LoweringInputs::chroma_handles`). A content made for it is counted
/// ([`Metric::ChromaContents`]) and each draw or dispatch of one too
/// ([`Metric::ChromaLaunches`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub(crate) struct Chroma {
pub(crate) slots: [u128; 2],
pub(crate) handles: bool,
}
impl Chroma {
/// Whether a content is made for it: some slot, or a handle.
pub(crate) fn any(self) -> bool {
self.slots != [0; 2] || self.handles
}
} }
/// What one content compiles to. /// What one content compiles to.
+9 -10
View File
@@ -46,7 +46,6 @@ mod instance;
mod kept; mod kept;
mod kernel_map; mod kernel_map;
mod memory; mod memory;
mod mesh_draw;
mod over; mod over;
mod own; mod own;
mod pass; mod pass;
@@ -89,10 +88,10 @@ pub use depth_stencil::DepthStencilState;
pub use device::{Device, DeviceOptions, RawDevice}; pub use device::{Device, DeviceOptions, RawDevice};
pub use encoder::{ComputeCommandEncoder, Dispatch, DispatchType, Resource, ResourceUsage}; pub use encoder::{ComputeCommandEncoder, Dispatch, DispatchType, Resource, ResourceUsage};
pub use error::{ pub use error::{
ChromaPairsGap, ChromaPairsRule, DrawInputCause, DrawKind, Error, Gap, IndirectCommandsKind, DrawInputCause, DrawKind, Error, Gap, IndirectCommandsKind, KernelInputKind, Limit,
KernelInputKind, Limit, PartialThreadgroupsCause, PartialThreadgroupsSite, Refusal, PartialThreadgroupsCause, PartialThreadgroupsSite, Refusal, RefusalBasis, RenderPassKind,
RefusalBasis, RenderPassKind, RenderPipelineKind, SamplePositionsKind, StageGap, StageInKind, RenderPipelineKind, SamplePositionsKind, StageGap, StageInKind, StorageElementCase,
StorageElementCase, TextureBacking, TextureBytesCause, TextureViewKind, WorkGroupLimit, TextureBacking, TextureBytesCause, TextureViewKind,
}; };
pub use event::{Event, SharedEvent}; pub use event::{Event, SharedEvent};
pub use export::{Export, ExportHandle}; pub use export::{Export, ExportHandle};
@@ -104,7 +103,9 @@ pub use host_bytes::HostBytes;
pub use import::ImportHandle; pub use import::ImportHandle;
pub use indirect::{IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandType}; pub use indirect::{IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandType};
pub use instance::{Instance, PhysicalDevice}; pub use instance::{Instance, PhysicalDevice};
pub use memory::{AllocationId, AllocationInfo, BlockId, BlockInfo, BlockMappings, MemoryClass}; pub use memory::{
AllocationId, AllocationInfo, BlockCaptureInfo, BlockId, BlockInfo, BlockMappings, MemoryClass,
};
/// `MTLLibrary`: the translator's, read from AIR or a metallib. /// `MTLLibrary`: the translator's, read from AIR or a metallib.
/// `MTLSamplerDescriptor`: the translator's. /// `MTLSamplerDescriptor`: the translator's.
pub use metal2vulkan::bind::SamplerDescriptor; pub use metal2vulkan::bind::SamplerDescriptor;
@@ -132,8 +133,6 @@ pub use metal2vulkan::metal::{
pub use metal2vulkan::metal::{ pub use metal2vulkan::metal::{
PixelFormat, TextureSwizzle, TextureSwizzleChannels, TextureType, TextureUsage, PixelFormat, TextureSwizzle, TextureSwizzleChannels, TextureType, TextureUsage,
}; };
/// `MTLMeshRenderPipelineDescriptor`: the translator's.
pub use metal2vulkan::pipeline::MeshPipelineDescriptor;
/// A function's stage, which a render pipeline state's texture slots are asked by: the /// A function's stage, which a render pipeline state's texture slots are asked by: the
/// translator's. /// translator's.
pub use metal2vulkan::pipeline::Stage; pub use metal2vulkan::pipeline::Stage;
@@ -162,8 +161,8 @@ pub use positions::SamplePosition;
pub use queue::CommandQueue; pub use queue::CommandQueue;
pub use render::RenderPipelineState; pub use render::RenderPipelineState;
pub use render_encoder::{ pub use render_encoder::{
IndexBuffer, PatchIndexBuffers, RenderCommandEncoder, ScissorRect, Viewport, BatchStop, IndexBuffer, PatchIndexBuffers, RenderCommandEncoder, ScissorRect, VertexOffsetDraw,
VisibilityResultMode, Viewport, VisibilityResultMode,
}; };
pub use sampler::SamplerState; pub use sampler::SamplerState;
pub use stage::{serve_stage, StageBreach, StageFill, StageRequest, StageSpans}; pub use stage::{serve_stage, StageBreach, StageFill, StageRequest, StageSpans};
+251 -12
View File
@@ -64,7 +64,8 @@ const BASE_ALIGN: u64 = 2 << 20;
/// block-maker thread frees an allocation idle this long, after the consumer's unmap of it, one at /// block-maker thread frees an allocation idle this long, after the consumer's unmap of it, one at
/// a time and between the allocations it makes, so a free never runs beside its own /// a time and between the allocations it makes, so a free never runs beside its own
/// `vkAllocateMemory`; a class's reserve ([`State::whole`]) is not freed. A driver may hold a /// `vkAllocateMemory`; a class's reserve ([`State::whole`]) is not freed. A driver may hold a
/// submission made during a free for the rest of it: /// submission made during a free for the rest of it (on the NVIDIA cards measured in
/// Thunderbolt enclosures, freeing host-visible memory takes about 1.1 ms per MiB):
/// [`Metrics::submissions_during_frees`](crate::Metrics::submissions_during_frees) counts them. /// [`Metrics::submissions_during_frees`](crate::Metrics::submissions_during_frees) counts them.
pub(crate) const IDLE_AGE_NANOS: u64 = 250_000_000; pub(crate) const IDLE_AGE_NANOS: u64 = 250_000_000;
@@ -258,8 +259,28 @@ impl AllocationId {
/// device is torn down. It is a range of one allocation, whose one `VkBuffer`, with every buffer /// device is torn down. It is a range of one allocation, whose one `VkBuffer`, with every buffer
/// usage and a device address, spans it; an imported or exported block is the whole of an /// usage and a device address, spans it; an imported or exported block is the whole of an
/// allocation of its own. Only an exported block is exportable. /// allocation of its own. Only an exported block is exportable.
/// Capture/replay address metadata for restoring a block at its exact Vulkan device address.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockCaptureInfo {
/// Storage mode (`Shared` or `Private`).
pub class: MemoryClass,
/// Full parent Vulkan allocation length in bytes.
pub alloc_len: u64,
/// Offset of this block inside its parent allocation.
pub offset: u64,
/// Block length in bytes.
pub len: u64,
/// Guest-visible `VkDeviceAddress` of this block's first byte.
pub gpu_address: u64,
/// Opaque capture address of the parent `VkBuffer`.
pub opaque_buffer_address: u64,
/// Opaque capture address of the parent `VkDeviceMemory`.
pub opaque_memory_address: u64,
}
#[non_exhaustive] #[non_exhaustive]
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
/// Metadata describing an allocated GPU memory block.
pub struct BlockInfo { pub struct BlockInfo {
/// The block's number. /// The block's number.
pub id: BlockId, pub id: BlockId,
@@ -665,6 +686,10 @@ struct Allocation {
buffer: vk::Buffer, buffer: vk::Buffer,
/// The device address of its first byte. /// The device address of its first byte.
address: u64, address: u64,
/// Opaque capture address of `buffer` (0 if capture-replay unsupported).
opaque_buffer_address: u64,
/// Opaque capture address of `memory` (0 if capture-replay unsupported).
opaque_memory_address: u64,
len: u64, len: u64,
mapping: Option<Mapping>, mapping: Option<Mapping>,
device_local: bool, device_local: bool,
@@ -678,6 +703,9 @@ struct Allocation {
/// Its block out is a texture block ([`crate::places`]), which fills its allocation: a whole /// Its block out is a texture block ([`crate::places`]), which fills its allocation: a whole
/// unit, or a long allocation of its own length. False once it is idle. /// unit, or a long allocation of its own length. False once it is idle.
texture: bool, texture: bool,
/// Reserved for image placement when buffer address replay is enabled. This allocation
/// stays in the texture pool after its last block comes back.
texture_only: bool,
/// When it became idle, in nanoseconds of [`host_time`](crate::host_time): when it was made, /// When it became idle, in nanoseconds of [`host_time`](crate::host_time): when it was made,
/// or when its last live block came back. The oldest idle allocation is freed first. /// or when its last live block came back. The oldest idle allocation is freed first.
idle_since: u64, idle_since: u64,
@@ -883,6 +911,8 @@ struct State {
/// The internal the block-maker thread took up and is making ([`run`]). /// The internal the block-maker thread took up and is making ([`run`]).
making: Option<Internal>, making: Option<Internal>,
stop: bool, stop: bool,
replaying: bool,
making_ahead: bool,
next_id: u32, next_id: u32,
next_allocation: u32, next_allocation: u32,
/// The allocations [`BlockMappings::map`] accepted whose unmap has not run. /// The allocations [`BlockMappings::map`] accepted whose unmap has not run.
@@ -1012,6 +1042,8 @@ impl Pool {
asked: [true; INTERNALS], asked: [true; INTERNALS],
making: None, making: None,
stop: false, stop: false,
replaying: false,
making_ahead: false,
next_id: 1, next_id: 1,
next_allocation: 1, next_allocation: 1,
mapped: HashSet::new(), mapped: HashSet::new(),
@@ -1254,7 +1286,9 @@ impl Pool {
return Err(Error::Quiesced); return Err(Error::Quiesced);
} }
let texture = matches!(site, Site::TextureBlock); let texture = matches!(site, Site::TextureBlock);
if let Some((carve, idle_since, long, ahead)) = state.fit(class, len, align, texture) { if let Some((carve, idle_since, long, ahead)) =
state.fit(class, len, align, texture, core.capture_replay)
{
if ahead { if ahead {
self.counters.site_take_ahead(site, len); self.counters.site_take_ahead(site, len);
} }
@@ -1470,6 +1504,160 @@ impl Pool {
} }
} }
/// Returns capture/replay info for a pool block, if capture-replay is enabled.
pub(crate) fn capture_info(&self, memory: &Memory) -> Option<BlockCaptureInfo> {
if memory.own.is_some() {
return None;
}
let state = self.lock();
let alloc = state.allocations[memory.class.index()]
.iter()
.find(|a| a.memory == memory.memory && !a.texture_only)?;
Some(BlockCaptureInfo {
class: memory.class,
alloc_len: alloc.len,
offset: memory.base,
len: memory.len,
gpu_address: memory.address,
opaque_buffer_address: alloc.opaque_buffer_address,
opaque_memory_address: alloc.opaque_memory_address,
})
}
/// Replays a previously captured pool block at its exact Vulkan device address.
pub(crate) fn take_replayed(
&self,
core: &Core,
cap: BlockCaptureInfo,
site: Site,
) -> Result<Memory, Error> {
let index = cap.class.index();
// 1. Check if the parent allocation is already present (e.g. another sub-block restored it,
// or a pre-stocked idle reserve landed at the exact same address!).
{
let mut state = self.lock();
if state.stop {
return Err(Error::Quiesced);
}
let id = number(&mut state)?;
let want_base = cap.gpu_address.saturating_sub(cap.offset);
if let Some(alloc) = state.allocations[index].iter_mut().find(|a| {
!a.texture_only
&& a.address == want_base
&& a.opaque_buffer_address == cap.opaque_buffer_address
&& a.opaque_memory_address == cap.opaque_memory_address
&& a.len == cap.alloc_len
}) {
if alloc.free.take_at(cap.offset, cap.len) {
let carve = alloc.carve(cap.offset);
alloc.live += 1;
alloc.placed += cap.len;
alloc.ahead = false;
self.counters.rise_by(cap.class.placed_gauge(), cap.len);
self.settle(&mut state, cap.class);
self.changed.notify_all();
return Ok(carve.block(id, cap.class, cap.len));
}
}
}
// 2. Pause block-maker ahead allocations, wait for any in-flight ahead make,
// and purge idle reserve slabs so none collide with the target opaque VA!
let idle_allocs: Vec<Allocation> = {
let mut state = self.lock();
state.replaying = true;
while state.making_ahead {
state = self.wait(state);
}
// Re-check if an ahead allocation that just finished landed at the exact target VA!
let want_base = cap.gpu_address.saturating_sub(cap.offset);
let hit = state.allocations[index].iter_mut().find_map(|a| {
if !a.texture_only
&& a.address == want_base
&& a.opaque_buffer_address == cap.opaque_buffer_address
&& a.opaque_memory_address == cap.opaque_memory_address
&& a.len == cap.alloc_len
&& a.free.take_at(cap.offset, cap.len)
{
let carve = a.carve(cap.offset);
a.live += 1;
a.placed += cap.len;
a.ahead = false;
Some(carve)
} else {
None
}
});
if let Some(carve) = hit {
let id = number(&mut state)?;
state.replaying = false;
self.counters.rise_by(cap.class.placed_gauge(), cap.len);
self.settle(&mut state, cap.class);
self.changed.notify_all();
return Ok(carve.block(id, cap.class, cap.len));
}
let mut drained = Vec::new();
for c in MemoryClass::ALL {
let ci = c.index();
let mut kept = Vec::new();
for a in state.allocations[ci].drain(..) {
if a.live == 0 {
drained.push(a);
} else {
kept.push(a);
}
}
state.allocations[ci] = kept;
self.settle(&mut state, c);
}
drained
};
for a in idle_allocs {
free_idle(core, a);
}
// 3. Allocate at the exact captured opaque buffer + memory addresses.
let alloc_res = make_allocation_ex(
core,
cap.class,
cap.alloc_len,
Some(site),
Some((cap.opaque_buffer_address, cap.opaque_memory_address)),
);
let mut allocation = match alloc_res {
Ok(a) => a,
Err(e) => {
let mut state = self.lock();
state.replaying = false;
self.changed.notify_all();
return Err(e);
}
};
let mapped = self.map(&allocation, cap.class, true);
if !mapped {
free_allocation(core, allocation);
let mut state = self.lock();
state.replaying = false;
self.changed.notify_all();
return Err(Error::Limit(Limit::AllocationNotMapped {
class: cap.class,
len: cap.alloc_len,
}));
}
let ok = allocation.free.take_at(cap.offset, cap.len);
debug_assert!(ok, "fresh allocation must contain captured block range");
let mut state = self.lock();
let id = number(&mut state)?;
let memory = allocation.carve(cap.offset).block(id, cap.class, cap.len);
allocation.live = 1;
allocation.placed = cap.len;
state.allocations[index].push(allocation);
state.replaying = false;
self.counters.rise_by(cap.class.placed_gauge(), cap.len);
self.settle(&mut state, cap.class);
self.changed.notify_all();
Ok(memory)
}
/// Takes back a block taken with [`take`](Self::take): its bytes are a free range of its /// Takes back a block taken with [`take`](Self::take): its bytes are a free range of its
/// allocation at once. /// allocation at once.
pub(crate) fn give_back(&self, memory: Memory) { pub(crate) fn give_back(&self, memory: Memory) {
@@ -1631,8 +1819,12 @@ impl State {
/// free bytes would wait until they ran low; in return a take of up to a unit, the 16 MiB /// free bytes would wait until they ran low; in return a take of up to a unit, the 16 MiB
/// ones among them, lands in memory made ahead once the block-maker thread has made it. /// ones among them, lands in memory made ahead once the block-maker thread has made it.
fn whole(&self, class: MemoryClass) -> bool { fn whole(&self, class: MemoryClass) -> bool {
(self.allocations[class.index()].iter()) (self.allocations[class.index()].iter()).any(|allocation| {
.any(|allocation| allocation.unit() && !allocation.retiring && allocation.live == 0) allocation.unit()
&& !allocation.texture_only
&& !allocation.retiring
&& allocation.live == 0
})
} }
/// The allocation of `class` whose memory is `memory`. /// The allocation of `class` whose memory is `memory`.
@@ -1652,9 +1844,11 @@ impl State {
len: u64, len: u64,
align: u64, align: u64,
texture: bool, texture: bool,
split_textures: bool,
) -> Option<(Carve, Option<u64>, bool, bool)> { ) -> Option<(Carve, Option<u64>, bool, bool)> {
let texture_only = split_textures && texture;
let (allocation, base) = (self.allocations[class.index()].iter_mut()) let (allocation, base) = (self.allocations[class.index()].iter_mut())
.filter(|allocation| allocation.serves(len)) .filter(|allocation| allocation.texture_only == texture_only && allocation.serves(len))
.find_map(|allocation| { .find_map(|allocation| {
let base = allocation.free.take(len, align)?; let base = allocation.free.take(len, align)?;
Some((allocation, base)) Some((allocation, base))
@@ -1683,7 +1877,9 @@ impl State {
fn aging(&self, class: MemoryClass) -> (Vec<(u64, vk::DeviceMemory)>, u64) { fn aging(&self, class: MemoryClass) -> (Vec<(u64, vk::DeviceMemory)>, u64) {
let idle = (self.allocations[class.index()].iter()) let idle = (self.allocations[class.index()].iter())
.filter(|allocation| allocation.live == 0 && !allocation.retiring); .filter(|allocation| allocation.live == 0 && !allocation.retiring);
let reserve = idle.clone().rfind(|allocation| allocation.unit()); let reserve = idle
.clone()
.rfind(|allocation| allocation.unit() && !allocation.texture_only);
let mut weighed: Vec<(u64, vk::DeviceMemory)> = idle let mut weighed: Vec<(u64, vk::DeviceMemory)> = idle
.filter(|allocation| reserve.is_none_or(|reserve| reserve.memory != allocation.memory)) .filter(|allocation| reserve.is_none_or(|reserve| reserve.memory != allocation.memory))
.map(|allocation| (allocation.idle_since, allocation.memory)) .map(|allocation| (allocation.idle_since, allocation.memory))
@@ -1894,12 +2090,18 @@ pub(crate) fn run(core: Arc<Core>) {
state = pool.lock(); state = pool.lock();
continue; continue;
} }
let wanted = (MemoryClass::ALL.into_iter()) let wanted = (!state.replaying)
.find(|&class| !state.failed[class.index()] && !state.whole(class)); .then(|| {
(MemoryClass::ALL.into_iter())
.find(|&class| !state.failed[class.index()] && !state.whole(class))
})
.flatten();
if let Some(class) = wanted { if let Some(class) = wanted {
state.making_ahead = true;
drop(state); drop(state);
let made = ahead(&core, class); let made = ahead(&core, class);
state = pool.lock(); state = pool.lock();
state.making_ahead = false;
match made { match made {
// Idle from now: the reserve, which the idle rule does not weigh. // Idle from now: the reserve, which the idle rule does not weigh.
Some(mut allocation) => { Some(mut allocation) => {
@@ -2180,8 +2382,20 @@ fn make_allocation(
class: MemoryClass, class: MemoryClass,
len: u64, len: u64,
site: Option<Site>, site: Option<Site>,
) -> Result<Allocation, Error> {
make_allocation_ex(core, class, len, site, None)
}
fn make_allocation_ex(
core: &Core,
class: MemoryClass,
len: u64,
site: Option<Site>,
replay: Option<(u64, u64)>,
) -> Result<Allocation, Error> { ) -> Result<Allocation, Error> {
let device = &core.device; let device = &core.device;
let texture_only = core.capture_replay && matches!(site, Some(Site::TextureBlock));
let capture_replay = core.capture_replay && !texture_only;
let (id, freed_at) = { let (id, freed_at) = {
let mut state = core.pool.lock(); let mut state = core.pool.lock();
( (
@@ -2189,22 +2403,38 @@ fn make_allocation(
state.freed_at[class.index()], state.freed_at[class.index()],
) )
}; };
let info = vk::BufferCreateInfo::default() let mut buf_opaque = vk::BufferOpaqueCaptureAddressCreateInfo::default()
.opaque_capture_address(replay.map_or(0, |(b, _)| b));
let mut info = vk::BufferCreateInfo::default()
.size(len) .size(len)
.usage(floor::BUFFER_USAGE) .usage(floor::BUFFER_USAGE)
.sharing_mode(vk::SharingMode::EXCLUSIVE); .sharing_mode(vk::SharingMode::EXCLUSIVE);
if capture_replay {
info = info.flags(vk::BufferCreateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY);
if replay.is_some_and(|(b, _)| b != 0) {
info = info.push_next(&mut buf_opaque);
}
}
// SAFETY: the device is live, and the create info valid: `len` is at most its // SAFETY: the device is live, and the create info valid: `len` is at most its
// `maxBufferSize`. // `maxBufferSize`.
let buffer = let buffer =
unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?; unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?;
// SAFETY: the buffer is the device's. // SAFETY: the buffer is the device's.
let requirements = unsafe { device.get_buffer_memory_requirements(buffer) }; let requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
let mut flags = let mut mem_flags = vk::MemoryAllocateFlags::DEVICE_ADDRESS;
vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS); if capture_replay {
let allocate_info = vk::MemoryAllocateInfo::default() mem_flags |= vk::MemoryAllocateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY;
}
let mut flags = vk::MemoryAllocateFlagsInfo::default().flags(mem_flags);
let mut mem_opaque = vk::MemoryOpaqueCaptureAddressAllocateInfo::default()
.opaque_capture_address(replay.map_or(0, |(_, m)| m));
let mut allocate_info = vk::MemoryAllocateInfo::default()
.allocation_size(requirements.size.max(len)) .allocation_size(requirements.size.max(len))
.memory_type_index(core.memory_type(class)) .memory_type_index(core.memory_type(class))
.push_next(&mut flags); .push_next(&mut flags);
if capture_replay && replay.is_some_and(|(_, m)| m != 0) {
allocate_info = allocate_info.push_next(&mut mem_opaque);
}
let bits = requirements.memory_type_bits; let bits = requirements.memory_type_bits;
// SAFETY: the floor chose the memory type for buffers of this usage on this device, and // SAFETY: the floor chose the memory type for buffers of this usage on this device, and
// `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow. // `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow.
@@ -2223,6 +2453,8 @@ fn make_allocation(
memory, memory,
buffer, buffer,
address: 0, address: 0,
opaque_buffer_address: 0,
opaque_memory_address: 0,
len, len,
mapping: None, mapping: None,
device_local: !spilled && core.device_local & (1 << core.memory_type(class)) != 0, device_local: !spilled && core.device_local & (1 << core.memory_type(class)) != 0,
@@ -2231,6 +2463,7 @@ fn make_allocation(
live: 0, live: 0,
placed: 0, placed: 0,
texture: false, texture: false,
texture_only,
idle_since: crate::host_time(), idle_since: crate::host_time(),
made: (0, 0), made: (0, 0),
wait: Wait::Progress(0), wait: Wait::Progress(0),
@@ -2259,6 +2492,12 @@ fn make_allocation(
let of = vk::BufferDeviceAddressInfo::default().buffer(buffer); let of = vk::BufferDeviceAddressInfo::default().buffer(buffer);
// SAFETY: the buffer has device-address usage and is bound. // SAFETY: the buffer has device-address usage and is bound.
allocation.address = unsafe { device.get_buffer_device_address(&of) }; allocation.address = unsafe { device.get_buffer_device_address(&of) };
if capture_replay {
allocation.opaque_buffer_address = unsafe { device.get_buffer_opaque_capture_address(&of) };
let mof = vk::DeviceMemoryOpaqueCaptureAddressInfo::default().memory(memory);
allocation.opaque_memory_address =
unsafe { device.get_device_memory_opaque_capture_address(&mof) };
}
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
{ {
allocation.address += core.placed_past; allocation.address += core.placed_past;
@@ -1,225 +0,0 @@
//! A mesh draw's grid: what `drawMeshThreadgroups` and `drawMeshThreads` give a mesh render
//! pipeline state's stages (`crate::render`'s mesh states), checked against Metal's maxima and the
//! device's.
//!
//! Each draw writes three group counts into the parameter ring, Metal's
//! `MTLDispatchThreadgroupsIndirectArguments` layout, and pushes their address
//! (`PushField::GroupCountsAddress`): with an object function they are its object grid, which its
//! folded threadgroups read, and without one they are the mesh grid the state's launcher reads
//! (`metal2vulkan`'s `link::mesh::Launcher`) and emits where Metal draws it. Each stage's
//! `DispatchRegion` carries Metal's threadgroup size `L` of the draw, as the translator packs it
//! (`region_bytes`), and the object stage's carries Metal's threads per grid and the partial flag
//! of a `drawMeshThreads` (`nonuniform_region_bytes`); a `drawMeshThreadgroups` states no grid, so
//! the object function's is its counts times `L`. A mesh function's grid is always whole
//! threadgroups.
//!
//! An object grid within the device's task limits (`maxTaskWorkGroupCount` along each axis,
//! `maxTaskWorkGroupTotalCount` in all) is one `vkCmdDrawMeshTasksEXT` of its counts. One past
//! them runs in pieces: one `vkCmdDrawMeshTasksIndirectEXT` of as many equal records as it takes,
//! each a piece of the most workgroups the limits allow, which the folded object function numbers
//! by `DrawIndex`, a workgroup past Metal's last threadgroup returning before its body. A
//! state without an object function draws one task workgroup, its launcher's.
//!
//! An indirect draw (`drawMeshThreadgroupsWithIndirectBuffer`) pushes its arguments' address as
//! the counts' address: the launcher reads the GPU's counts there and emits the mesh grid where
//! Metal draws it, as for a direct draw. With an object function it is refused at the draw
//! (`DrawKind::IndirectObjectGrid`): an object grid past the task limits runs in pieces whose
//! number only its counts decide. Nothing here reads a GPU word, and no draw splits its pass.
use crate::error::{DrawKind, Error, Gap, Limit, Refusal};
use crate::render::MeshThreads;
use crate::ring::CHUNK;
use metal2vulkan::pipeline::{nonuniform_region_bytes, region_bytes, Stage};
/// The bytes of one record of `vkCmdDrawMeshTasksIndirectEXT`
/// (`VkDrawMeshTasksIndirectCommandEXT`: three group counts), its records' stride.
pub(crate) const RECORD: u32 = 12;
/// The most piece records one draw writes: those one ring chunk holds.
const MOST_PIECES: u64 = CHUNK / RECORD as u64;
/// A mesh draw's grid as Metal's call states it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum MeshGrid {
/// `drawMeshThreadgroups`: threadgroups per grid.
Threadgroups([u32; 3]),
/// `drawMeshThreads`: threads per grid.
Threads([u32; 3]),
/// `drawMeshThreadgroupsWithIndirectBuffer`: threadgroups per grid the GPU reads at the
/// draw's arguments, which the draw pushes as the counts' address.
Indirect,
}
/// The task workgroups a mesh draw launches.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Launch {
/// One `vkCmdDrawMeshTasksEXT` of these counts.
Direct([u32; 3]),
/// `pieces` records of `piece` in one `vkCmdDrawMeshTasksIndirectEXT`.
Pieces { piece: [u32; 3], pieces: u32 },
}
/// What a mesh draw records: the group counts it writes (an indirect draw's, the GPU's, it does
/// not), each stage's region (the object's, then the mesh's; the object's unused without an
/// object function), the task workgroups it launches, and whether it draws nothing (a grid with an
/// empty axis, which only the host's counts can be).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct MeshCall {
pub(crate) counts: [u32; 3],
pub(crate) regions: [[u8; 32]; 2],
pub(crate) launch: Launch,
pub(crate) empty: bool,
}
impl MeshCall {
/// The draw of `grid`, with `object` threads per object threadgroup and `mesh` threads per
/// mesh threadgroup, of a state whose threadgroups are `threads`: each threadgroup checked
/// ([`checked`]; an object threadgroup only where the state has an object function, whose
/// size Metal reads only there), then its counts, regions and launch.
///
/// Err: as [`checked`]; [`Limit::ObjectThreadgroups`] for an object grid past what one draw
/// launches; [`Gap::Draw`] of [`DrawKind::IndirectObjectGrid`] for an indirect draw of a state
/// with an object function.
pub(crate) fn of(
threads: &MeshThreads,
grid: MeshGrid,
object: [u32; 3],
mesh: [u32; 3],
) -> Result<MeshCall, Error> {
if threads.object.is_some() {
checked(threads, Stage::Object, object)?;
}
checked(threads, Stage::Mesh, mesh)?;
// Each axis of a checked threadgroup is 1 to 1024, which the regions pack.
let refused = |size, max| Error::Refused(Refusal::ThreadgroupSize { size, max });
let mesh_region =
region_bytes([0; 3], [0; 3], mesh).ok_or_else(|| refused(mesh, threads.mesh))?;
let (counts, object_region) = match (threads.object, grid) {
// Without an object function the counts are the mesh grid: a draw of threads rounds
// it down to whole threadgroups (Metal's measured answer).
(None, MeshGrid::Threadgroups(groups)) => (groups, [0; 32]),
(None, MeshGrid::Threads(t)) => ([0, 1, 2].map(|axis| t[axis] / mesh[axis]), [0; 32]),
// An indirect draw's counts are the GPU's, at its arguments: none is written.
(None, MeshGrid::Indirect) => ([1; 3], [0; 32]),
// A draw of threadgroups states no grid: the object function's is its counts times
// `L`.
(Some(max), MeshGrid::Threadgroups(groups)) => {
let region = region_bytes([0; 3], [0; 3], object);
(groups, region.ok_or_else(|| refused(object, max))?)
}
// An object grid the GPU reads is refused at the draw: past the task limits it runs in
// pieces whose number only its counts decide.
(Some(_), MeshGrid::Indirect) => {
return Err(Error::Unsupported(Gap::Draw {
kind: DrawKind::IndirectObjectGrid,
}));
}
// A draw of threads launches the object threadgroups they fill, rounded up, the last
// along an axis running only the threads left.
(Some(max), MeshGrid::Threads(t)) => {
let groups = [0, 1, 2].map(|axis| t[axis].div_ceil(object[axis]));
let ragged = (0..3).any(|axis| t[axis] % object[axis] != 0);
let region = match ragged {
true => nonuniform_region_bytes([0; 3], t, object),
false => region_bytes([0; 3], t, object),
};
(groups, region.ok_or_else(|| refused(object, max))?)
}
};
let empty = counts.contains(&0);
let launch = match (threads.object, empty) {
(Some(_), false) => launch(counts, threads.task_grid)?,
_ => Launch::Direct([1, 1, 1]),
};
Ok(MeshCall {
counts,
regions: [object_region, mesh_region],
launch,
empty,
})
}
}
/// A draw's threadgroup of `size` for `stage` of a state whose threadgroups are `threads`.
///
/// Err: [`Refusal::ThreadgroupSize`] for a threadgroup of no threads or past Metal's maximum for
/// the stage; [`Limit::MeshThreadgroupThreads`] for one within it and past the state's on this
/// device, naming the Vulkan limit that holds it.
pub(crate) fn checked(threads: &MeshThreads, stage: Stage, size: [u32; 3]) -> Result<(), Error> {
let at = usize::from(stage == Stage::Mesh);
let max = match stage {
Stage::Object => threads.object.unwrap_or(0),
_ => threads.mesh,
};
let total = size.iter().map(|&axis| u64::from(axis)).product::<u64>();
if total == 0 || total > u64::from(threads.metal[at]) {
return Err(Error::Refused(Refusal::ThreadgroupSize { size, max }));
}
if total > u64::from(max) {
let (limit, device) = threads.caps[at];
return Err(Error::Limit(Limit::MeshThreadgroupThreads {
stage,
size,
max,
limit,
device,
}));
}
Ok(())
}
/// The launch of an object grid of `groups` (no axis empty) on a device whose task grid is
/// `(count, total)` (`maxTaskWorkGroupCount`, `maxTaskWorkGroupTotalCount`): the counts
/// themselves where they lie within the limits, else pieces of the most workgroups the limits
/// allow, filled `x` first: one piece launched directly, more through their records.
///
/// Err: [`Limit::ObjectThreadgroups`] where the pieces are more than [`MOST_PIECES`].
pub(crate) fn launch(groups: [u32; 3], (count, total): ([u32; 3], u32)) -> Result<Launch, Error> {
let all = groups.iter().map(|&axis| u64::from(axis)).product::<u64>();
if (0..3).all(|axis| groups[axis] <= count[axis]) && all <= u64::from(total) {
return Ok(Launch::Direct(groups));
}
// Each axis of a piece takes what is left of the grid, within its own limit and the total
// left by the axes before it; every limit is at least 1 (Vulkan's minimums are far above).
let (mut piece, mut held, mut room) = ([1u32; 3], 1u64, u64::from(total.max(1)));
for axis in 0..3 {
let side = (all.div_ceil(held))
.min(u64::from(count[axis].max(1)))
.min(room)
.max(1);
// Within `count[axis]`, a `u32`.
piece[axis] = side as u32;
held *= side;
room /= side;
}
let pieces = all.div_ceil(held);
if pieces == 1 {
return Ok(Launch::Direct(piece));
}
if pieces > MOST_PIECES {
return Err(Error::Limit(Limit::ObjectThreadgroups {
groups,
max: MOST_PIECES * held,
}));
}
Ok(Launch::Pieces {
piece,
// At most `MOST_PIECES`.
pieces: pieces as u32,
})
}
/// The records of a launch in pieces: `pieces` copies of `piece`, [`RECORD`] bytes each.
pub(crate) fn records(piece: [u32; 3], pieces: u32) -> Vec<u8> {
let one: Vec<u8> = piece.iter().flat_map(|axis| axis.to_le_bytes()).collect();
one.repeat(pieces as usize)
}
/// The group counts' bytes, as the object function or the launcher reads them.
pub(crate) fn count_bytes(counts: [u32; 3]) -> [u8; 12] {
let mut out = [0; 12];
for (at, axis) in out.as_chunks_mut::<4>().0.iter_mut().zip(counts) {
*at = axis.to_le_bytes();
}
out
}
+4 -13
View File
@@ -205,9 +205,8 @@ impl ClearColor {
/// ///
/// A store action that resolves resolves into `resolve_texture` by the device's average (the /// A store action that resolves resolves into `resolve_texture` by the device's average (the
/// module's documentation). Refused, as [`Gap::RenderPass`] of [`RenderPassKind::Resolve`]: a /// module's documentation). Refused, as [`Gap::RenderPass`] of [`RenderPassKind::Resolve`]: a
/// resolve of an extended-range format but `BGR10_XR` and `BGRA10_XR` (whose codes average as their /// resolve of an extended-range, bfloat or YCbCr format, which Vulkan's average would take in the
/// values do), or of a bfloat or YCbCr format, which Vulkan's average would take in the image's /// image's own encoding. An integer format has no resolve, [`Refusal::ResolveFormat`].
/// own encoding. An integer format has no resolve, [`Refusal::ResolveFormat`].
/// ///
/// Not built: `storeActionOptions`, whose one option needs more than one sample. /// Not built: `storeActionOptions`, whose one option needs more than one sample.
/// ///
@@ -929,14 +928,11 @@ impl Pass {
if !matches!(formats::sampled_type(pf), Some(SampledType::Float)) { if !matches!(formats::sampled_type(pf), Some(SampledType::Float)) {
return Err(Error::Refused(Refusal::ResolveFormat { pixel_format: pf })); return Err(Error::Refused(Refusal::ResolveFormat { pixel_format: pf }));
} }
// `BGR10_XR`'s and `BGRA10_XR`'s codes average as their values do (the map
// is affine), the device rounding the average.
if !matches!( if !matches!(
texture.emulation(), texture.emulation(),
FormatEmulation::Direct FormatEmulation::Direct
| FormatEmulation::RotatedView | FormatEmulation::RotatedView
| FormatEmulation::AlphaInRed | FormatEmulation::AlphaInRed
| FormatEmulation::ExtendedRangeUnorm
) { ) {
return Err(gap(RenderPassKind::Resolve)); return Err(gap(RenderPassKind::Resolve));
} }
@@ -1362,19 +1358,14 @@ fn target(
/// The Vulkan clear value of `color` for a color attachment of `pf` held as `emulation`: an /// The Vulkan clear value of `color` for a color attachment of `pf` held as `emulation`: an
/// integer channel's value truncated toward zero and saturated to its range, NaN 0; any other /// integer channel's value truncated toward zero and saturated to its range, NaN 0; any other
/// channel's as a `float`, in the image's channels: a rotated format's, and `A8Unorm`'s held in /// channel's as a `float`, in the image's channels: a rotated format's, and `A8Unorm`'s held in
/// `R8_UNORM`, rotated (`to_rotated_image`), so its alpha lands in red; `BGR10_XR`'s and /// `R8_UNORM`, rotated (`to_rotated_image`), so its alpha lands in red. `None` where only a shader
/// `BGRA10_XR`'s as the UNORM codes Metal's clear stores (`metal::format::extended_unorm_clear`). /// clears the format: an extended-range, bfloat or YCbCr format.
/// `None` where only a shader clears the format: another extended-range, bfloat or YCbCr format.
pub(crate) fn clear_color( pub(crate) fn clear_color(
pf: PixelFormat, pf: PixelFormat,
emulation: FormatEmulation, emulation: FormatEmulation,
color: ClearColor, color: ClearColor,
) -> Option<vk::ClearColorValue> { ) -> Option<vk::ClearColorValue> {
let rgba = [color.red, color.green, color.blue, color.alpha]; let rgba = [color.red, color.green, color.blue, color.alpha];
if emulation == FormatEmulation::ExtendedRangeUnorm {
return formats::extended_unorm_clear(pf, rgba)
.map(|float32| vk::ClearColorValue { float32 });
}
if !matches!( if !matches!(
emulation, emulation,
FormatEmulation::Direct | FormatEmulation::RotatedView | FormatEmulation::AlphaInRed FormatEmulation::Direct | FormatEmulation::RotatedView | FormatEmulation::AlphaInRed
+18 -58
View File
@@ -67,7 +67,7 @@ use crate::encoder::{
}; };
use crate::error::{Error, Gap, IndirectCommandsKind, KernelInputKind, Refusal}; use crate::error::{Error, Gap, IndirectCommandsKind, KernelInputKind, Refusal};
use crate::hazard::Access; use crate::hazard::Access;
use crate::kernel_map::{Chroma, KernelKey}; use crate::kernel_map::KernelKey;
use crate::reaper::{Free, Job}; use crate::reaper::{Free, Job};
use crate::ring::CHUNK; use crate::ring::CHUNK;
use crate::sampler::{canonical, constexpr_notes, hold_constexpr, release_constexpr}; use crate::sampler::{canonical, constexpr_notes, hold_constexpr, release_constexpr};
@@ -89,7 +89,6 @@ use metal2vulkan::pipeline::{
StageEntries, StageSource, TextureAccess, TextureSlot, GRID_TILE_THREADS, StageEntries, StageSource, TextureAccess, TextureSlot, GRID_TILE_THREADS,
}; };
use metal2vulkan::Budget; use metal2vulkan::Budget;
use std::collections::BTreeSet;
use std::ffi::CString; use std::ffi::CString;
use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError};
@@ -821,10 +820,6 @@ pub(crate) struct Interface {
pub(crate) constexprs: Vec<(usize, CombinedSampler)>, pub(crate) constexprs: Vec<(usize, CombinedSampler)>,
/// Whether the kernel reads through an address that is not one of its bound slots. /// Whether the kernel reads through an address that is not one of its bound slots.
pub(crate) reads_unbound: bool, pub(crate) reads_unbound: bool,
/// Whether the kernel may read, sample or gather a `float` colour texture through a handle
/// (`PipelineInterface::handle_float_images`): while a 4:2:2 texture lives on the device, a
/// dispatch of it runs its content lowered under `LoweringInputs::chroma_handles`.
pub(crate) handle_float_images: bool,
/// Whether the kernel writes through an address that is not one of its bound slots. /// Whether the kernel writes through an address that is not one of its bound slots.
pub(crate) writes_unbound: bool, pub(crate) writes_unbound: bool,
/// Whether the kernel may reach a texture through its storage image through an address that /// Whether the kernel may reach a texture through its storage image through an address that
@@ -1077,10 +1072,6 @@ pub(crate) enum FieldValue {
/// past which a vertex function's `[[viewport_array_index]]` stores `ViewportIndex` 0 /// past which a vertex function's `[[viewport_array_index]]` stores `ViewportIndex` 0
/// (`PushField::ViewportCount`). /// (`PushField::ViewportCount`).
ViewportCount, ViewportCount,
/// Two `f32`s: the near depth of the encoder's first viewport and its far depth less its
/// near, which a depth range twin's vertex function folds into its position
/// (`PushField::DepthRangeFold`, `crate::RenderPipelineState::folded`).
DepthRangeFold,
/// A `u64`: the address of the execution range the vertex function of a state made for /// A `u64`: the address of the execution range the vertex function of a state made for
/// indirect command buffers tests its command against (`PushField::IndirectRange`): the /// indirect command buffers tests its command against (`PushField::IndirectRange`): the
/// ring's range of every command (`Ring::whole`) for a direct draw and an execution over a /// ring's range of every command (`Ring::whole`) for a direct draw and an execution over a
@@ -1093,10 +1084,6 @@ pub(crate) enum FieldValue {
/// A `u32`: the first command of the part of an execution the draw is /// A `u32`: the first command of the part of an execution the draw is
/// (`PushField::IndirectBase`), 0 for a direct draw; an execution pushes each part's own. /// (`PushField::IndirectBase`), 0 for a direct draw; an execution pushes each part's own.
IndirectBase, IndirectBase,
/// A `u64`: the address of a mesh draw's three threadgroup counts, Metal's
/// `MTLDispatchThreadgroupsIndirectArguments`, which a mesh render pipeline's object function,
/// or its launcher where it has none, reads (`PushField::GroupCountsAddress`).
GroupCounts,
} }
/// A `VkPipeline`'s specialization: the threadgroup size, the threadgroup memory lengths in the /// A `VkPipeline`'s specialization: the threadgroup size, the threadgroup memory lengths in the
@@ -1222,12 +1209,11 @@ impl crate::Device {
srgb: [0; 2], srgb: [0; 2],
words: 0, words: 0,
arrays: 0, arrays: 0,
chroma: Chroma::default(),
}; };
let compiled = match core.kernels.find(&key) { let compiled = match core.kernels.find(&key) {
Some(compiled) => compiled, Some(compiled) => compiled,
None => { None => {
let compiled = Arc::new(Compiled::of(core, descriptor, (0, 0, Chroma::default()))?); let compiled = Arc::new(Compiled::of(core, descriptor, (0, 0))?);
core.kernels.keep(key.clone(), compiled, &core.counters) core.kernels.keep(key.clone(), compiled, &core.counters)
} }
}; };
@@ -1244,30 +1230,16 @@ impl crate::Device {
} }
} }
/// The texture slots of `stage` that `mask` names, bit `i` slot `i`: those a content lowers for
/// a 4:2:2 texture (`LoweringInputs::chroma_pairs`).
pub(crate) fn chroma_slots(stage: Stage, mask: u128) -> BTreeSet<SlotRef> {
(0..TEXTURE_SLOTS)
.filter(|&index| mask >> index & 1 == 1)
.map(|index| SlotRef {
stage,
class: SlotClass::Texture,
index,
})
.collect()
}
impl Compiled { impl Compiled {
/// The translation of `descriptor`, every variant lowered, with the `VkPipeline`s whose key /// The translation of `descriptor`, every variant lowered, with the `VkPipeline`s whose key
/// the descriptor holds; a function kernel's under its texture slots of `srgb` (bit `i` slot /// the descriptor holds; a function kernel's under its texture slots of `srgb` (bit `i` slot
/// `i`) holding an 8-bit sRGB texture's UNORM twin (`LoweringInputs::srgb_storage`), its /// `i`) holding an 8-bit sRGB texture's UNORM twin (`LoweringInputs::srgb_storage`) and its
/// buffer slots of `words` bound at a multiple of 4 below their argument's alignment /// buffer slots of `words` bound at a multiple of 4 below their argument's alignment
/// (`LoweringInputs::word_bound_buffers`), and the 4:2:2 textures `chroma` reaches /// (`LoweringInputs::word_bound_buffers`).
/// (`LoweringInputs::chroma_pairs` of its first slots, `LoweringInputs::chroma_handles`).
fn of( fn of(
core: &Arc<Core>, core: &Arc<Core>,
descriptor: &ComputePipelineDescriptor, descriptor: &ComputePipelineDescriptor,
(srgb, words, chroma): (u128, u32, Chroma), (srgb, words): (u128, u32),
) -> Result<Compiled, Error> { ) -> Result<Compiled, Error> {
let core = Arc::clone(core); let core = Arc::clone(core);
let budget = Budget::standard(); let budget = Budget::standard();
@@ -1300,8 +1272,6 @@ impl Compiled {
index, index,
}) })
.collect(); .collect();
inputs.chroma_pairs = chroma_slots(Stage::Kernel, chroma.slots[0]);
inputs.chroma_handles = chroma.handles;
let plain = translating(&core, || { let plain = translating(&core, || {
translator.kernel_inputs_read(function, &inputs, &budget, entries) translator.kernel_inputs_read(function, &inputs, &budget, entries)
}) })
@@ -2009,6 +1979,9 @@ pub(crate) fn interface(
.iter() .iter()
.position(|&numbered| numbered == NumberedSampler::Constexpr(words)) .position(|&numbered| numbered == NumberedSampler::Constexpr(words))
.ok_or(KernelInputKind::ConstexprSampler)?; .ok_or(KernelInputKind::ConstexprSampler)?;
if sampler.unnormalized {
return Err(KernelInputKind::ConstexprSampler);
}
constexprs.push((at, sampler)); constexprs.push((at, sampler));
FieldValue::ConstexprSampler(at) FieldValue::ConstexprSampler(at)
} }
@@ -2141,7 +2114,6 @@ pub(crate) fn interface(
numbered, numbered,
constexprs, constexprs,
reads_unbound: translated.reads_unbound_resources, reads_unbound: translated.reads_unbound_resources,
handle_float_images: translated.handle_float_images,
writes_unbound: translated.writes_unbound_resources, writes_unbound: translated.writes_unbound_resources,
unbound_storage: translated.unbound_storage_textures, unbound_storage: translated.unbound_storage_textures,
has_effects: translated.writes_memory, has_effects: translated.writes_memory,
@@ -2610,46 +2582,34 @@ impl PipelineInner {
/// holding an 8-bit sRGB texture's UNORM twin, each write there encoded in the shader /// holding an 8-bit sRGB texture's UNORM twin, each write there encoded in the shader
/// (`LoweringInputs::srgb_storage`), and its buffer slots of `words` bound at a multiple of 4 /// (`LoweringInputs::srgb_storage`), and its buffer slots of `words` bound at a multiple of 4
/// below their argument's alignment, each held to what its accesses need /// below their argument's alignment, each held to what its accesses need
/// (`LoweringInputs::word_bound_buffers`), and its reads of the 4:2:2 textures `chroma` /// (`LoweringInputs::word_bound_buffers`): the one the device's map of contents holds under
/// reaches decoded (`LoweringInputs::chroma_pairs`, `LoweringInputs::chroma_handles`): the /// the state's key with both, else lowered now and kept there, so the map bounds how many
/// one the device's map of contents holds under the state's key with them, else lowered now /// live. It numbers the state's samplers, as it lowers the same function. `None` for a kernel
/// and kept there, so the map bounds how many live. It numbers the state's samplers, as it /// the consumer compiled, which has no function to lower it from. A make, at the dispatch that
/// lowers the same function. `None` for a kernel the consumer compiled, which has no function /// needs it, counts in [`Metrics::translations_at_encode`](crate::Metrics).
/// to lower it from. A make, at the dispatch that needs it, counts in
/// [`Metrics::translations_at_encode`](crate::Metrics), and one for `chroma` in
/// [`Metrics::chroma_contents`](crate::Metrics) too.
/// ///
/// Err: the translator's errors of its lowering, as the state's creation reports them; /// Err: the translator's errors of its lowering, as the state's creation reports them;
/// [`Gap::KernelInput`] of a constexpr sampler where it samples one the state's module does /// [`Gap::KernelInput`] of a constexpr sampler where it samples one the state's module does
/// not. /// not.
pub(crate) fn variant( pub(crate) fn variant(&self, srgb: u128, words: u32) -> Option<Result<Arc<Compiled>, Error>> {
&self,
srgb: u128,
words: u32,
chroma: Chroma,
) -> Option<Result<Arc<Compiled>, Error>> {
let core = self.core(); let core = self.core();
let (descriptor, key) = self.source.as_ref()?; let (descriptor, key) = self.source.as_ref()?;
let key = KernelKey { let key = KernelKey {
srgb: [srgb, 0], srgb: [srgb, 0],
words: u64::from(words), words: u64::from(words),
chroma,
..key.clone() ..key.clone()
}; };
if let Some(compiled) = core.kernels.find(&key) { if let Some(compiled) = core.kernels.find(&key) {
return Some(Ok(compiled)); return Some(Ok(compiled));
} }
let began = host_time(); let began = host_time();
if chroma.any() {
core.counters.count(Metric::ChromaContents);
}
let made = let made =
Compiled::of(core, descriptor, (srgb, words, chroma)).and_then( Compiled::of(core, descriptor, (srgb, words)).and_then(|compiled| {
|compiled| match covers(&self.compiled.whole.interface, &compiled.whole.interface) { match covers(&self.compiled.whole.interface, &compiled.whole.interface) {
true => Ok(core.kernels.keep(key, Arc::new(compiled), &core.counters)), true => Ok(core.kernels.keep(key, Arc::new(compiled), &core.counters)),
false => Err(gap(KernelInputKind::ConstexprSampler)), false => Err(gap(KernelInputKind::ConstexprSampler)),
}, }
); });
(core.counters).translation_at_encode(host_time().saturating_sub(began)); (core.counters).translation_at_encode(host_time().saturating_sub(began));
Some(made) Some(made)
} }
+29
View File
@@ -1,6 +1,8 @@
//! Places: the Private blocks the runtime places textures' images in, taken as the consumer takes //! Places: the Private blocks the runtime places textures' images in, taken as the consumer takes
//! blocks. A texture block holds images alone, so no buffer lies beside an optimal image in one //! blocks. A texture block holds images alone, so no buffer lies beside an optimal image in one
//! block. //! block.
//! When the device enables buffer address replay, the pool keeps texture allocations separate
//! and leaves their replay flags clear. Restoring a buffer can still request its captured address.
//! //!
//! A place is a resource's bytes at a multiple of its alignment. One no longer than the class's //! A place is a resource's bytes at a multiple of its alignment. One no longer than the class's
//! block length ([`MemoryClass::block_len`]) is the first that fits in the blocks of that length, //! block length ([`MemoryClass::block_len`]) is the first that fits in the blocks of that length,
@@ -248,6 +250,33 @@ impl Ranges {
Some(at) Some(at)
} }
/// Takes the exact range `at..at + len` if it is completely free.
pub(crate) fn take_at(&mut self, at: u64, len: u64) -> bool {
let Some(stop) = at.checked_add(len) else {
return false;
};
let Some(index) = self
.free
.iter()
.position(|&(start, end)| start <= at && stop <= end)
else {
return false;
};
let (start, end) = self.free[index];
match (start < at, stop < end) {
(false, false) => {
self.free.remove(index);
}
(true, false) => self.free[index] = (start, at),
(false, true) => self.free[index] = (stop, end),
(true, true) => {
self.free[index] = (start, at);
self.free.insert(index + 1, (stop, end));
}
}
true
}
/// Frees `offset..offset + len`, taken before, joining it to the free ranges beside it. /// Frees `offset..offset + len`, taken before, joining it to the free ranges beside it.
pub(crate) fn give(&mut self, offset: u64, len: u64) { pub(crate) fn give(&mut self, offset: u64, len: u64) {
let end = offset + len; let end = offset + len;
+62 -9
View File
@@ -20,7 +20,7 @@ pub struct CommandQueue {
/// The queue itself: what its command buffers and the submit thread hold. /// The queue itself: what its command buffers and the submit thread hold.
pub(crate) struct QueueInner { pub(crate) struct QueueInner {
max: u32, recording: Recording,
/// The command buffers made and not yet retired, and the lists retired ones left. /// The command buffers made and not yet retired, and the lists retired ones left.
live: Mutex<Live>, live: Mutex<Live>,
/// Signalled when one retires. /// Signalled when one retires.
@@ -46,13 +46,34 @@ pub(crate) struct QueueInner {
/// A queue's live command buffers: those made and not yet retired, and the kept-object lists /// A queue's live command buffers: those made and not yet retired, and the kept-object lists
/// of retired ones, empty, with their capacity, each in the allocation it came in /// of retired ones, empty, with their capacity, each in the allocation it came in
/// (`crate::kept::Objects`): together at most the queue's maximum, since each list is a live /// (`crate::kept::Objects`). Host batches keep only a submission group's worth of idle lists.
/// command buffer's or one retired since.
struct Live { struct Live {
count: u32, count: usize,
objects: Vec<Objects>, objects: Vec<Objects>,
} }
#[derive(Clone, Copy)]
enum Recording {
Metal(u32),
HostBatch,
}
impl Recording {
fn has_room(self, live: usize) -> bool {
match self {
Self::Metal(max) => live < max as usize,
Self::HostBatch => true,
}
}
fn recycle(self, idle: usize) -> bool {
match self {
Self::Metal(_) => true,
Self::HostBatch => idle < crate::submit::GROUP,
}
}
}
impl Device { impl Device {
/// `newCommandQueueWithMaxCommandBufferCount:`; `newCommandQueue` is this call with 64. /// `newCommandQueueWithMaxCommandBufferCount:`; `newCommandQueue` is this call with 64.
/// ///
@@ -65,10 +86,22 @@ impl Device {
if max_command_buffer_count == 0 { if max_command_buffer_count == 0 {
return Err(Error::Refused(Refusal::NoCommandBuffers)); return Err(Error::Refused(Refusal::NoCommandBuffers));
} }
Ok(self.queue_with_recording(Recording::Metal(max_command_buffer_count)))
}
/// A private FIFO for host copies prepared together and published after their dependencies
/// have been recorded. Recording must never wait for another member of that transaction to
/// retire. Committed work follows the ordinary submit thread's ordering and GPU pacing.
/// The host owns the lifetime of the batch and the memory held by its recorded copies.
pub fn new_host_batch_queue(&self) -> CommandQueue {
self.queue_with_recording(Recording::HostBatch)
}
fn queue_with_recording(&self, recording: Recording) -> CommandQueue {
let core = self.core(); let core = self.core();
Ok(CommandQueue { CommandQueue {
inner: Arc::new(QueueInner { inner: Arc::new(QueueInner {
max: max_command_buffer_count, recording,
live: Mutex::new(Live { live: Mutex::new(Live {
count: 0, count: 0,
objects: Vec::new(), objects: Vec::new(),
@@ -82,7 +115,7 @@ impl Device {
core: Arc::downgrade(core), core: Arc::downgrade(core),
}), }),
device: self.clone(), device: self.clone(),
}) }
} }
} }
@@ -100,7 +133,7 @@ impl CommandQueue {
if core.closed() { if core.closed() {
return Err(Error::Quiesced); return Err(Error::Quiesced);
} }
if live.count < self.inner.max { if self.inner.recording.has_room(live.count) {
break; break;
} }
if crate::device::on_handler_thread(core) { if crate::device::on_handler_thread(core) {
@@ -205,7 +238,9 @@ impl QueueInner {
self.counters.fall(Gauge::CommandBuffers); self.counters.fall(Gauge::CommandBuffers);
let mut live = lock(&self.live); let mut live = lock(&self.live);
live.count -= 1; live.count -= 1;
live.objects.push(kept); if self.recording.recycle(live.objects.len()) {
live.objects.push(kept);
}
drop(live); drop(live);
self.room.notify_one(); self.room.notify_one();
} }
@@ -221,3 +256,21 @@ pub(crate) fn next_run(expected: Option<u64>, nanos: u64) -> u64 {
_ => nanos.min(u64::MAX - 1), _ => nanos.min(u64::MAX - 1),
} }
} }
#[cfg(test)]
mod recording_tests {
use super::Recording;
#[test]
fn host_batches_stage_independently_of_the_metal_recording_window() {
let metal = Recording::Metal(2);
assert!(metal.has_room(1));
for live in [2, 3, 64, 65, 128] {
assert!(!metal.has_room(live));
assert!(Recording::HostBatch.has_room(live));
}
let group = crate::submit::GROUP;
assert!(Recording::HostBatch.recycle(group - 1));
assert!(!Recording::HostBatch.recycle(group));
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2 -74
View File
@@ -22,9 +22,6 @@
//! A slot the fragment function reads only at its own pixel (`StageModule::own_pixel_textures`) //! A slot the fragment function reads only at its own pixel (`StageModule::own_pixel_textures`)
//! reads the rectangle of the draw's scissor, a pixel wider each way for its helper invocations, //! reads the rectangle of the draw's scissor, a pixel wider each way for its helper invocations,
//! clamped into its level; any other slot reads every level and layer its texture reaches. //! clamped into its level; any other slot reads every level and layer its texture reaches.
//!
//! The copies' bytes are counted by read (at the fragment's own pixel, or all a texture reaches)
//! and by when they come ([`Moment`]).
/// The most areas a shadow's [`Held`] keeps: past them it forgets the oldest, which a later read /// The most areas a shadow's [`Held`] keeps: past them it forgets the oldest, which a later read
/// copies again. /// copies again.
@@ -199,62 +196,11 @@ pub(crate) fn parted(
(rendered, rest) (rendered, rest)
} }
/// When a draw copies into a shadow, for its copies' counters
/// ([`Metrics::attachment_read_copy_bytes_first_in_pass`](crate::Metrics::attachment_read_copy_bytes_first_in_pass)
/// and the two beside it), taken before the draw plans them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Moment {
/// The shadow has held nothing since its pass began.
FirstInPass,
/// A memory barrier after draws, or a draw that reads a colour attachment at its own pixel
/// after draws, left it holding nothing.
AfterBarrier,
/// It holds something, and the draw reads what it does not hold.
BeyondHeld,
}
/// The bytes of a draw's copies into its pass's shadows, parted for their counters: by read and by
/// [`Moment`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Copied {
/// Of reads at the fragment's own pixel ([`own_pixel`]).
pub(crate) own_pixel: u64,
/// Of reads of all a texture reaches ([`whole`]).
pub(crate) whole_texture: u64,
/// Of each [`Moment`].
pub(crate) first_in_pass: u64,
pub(crate) after_barrier: u64,
pub(crate) beyond_held: u64,
}
impl Copied {
/// A copy of `bytes` for a read at the fragment's own pixel or not, at `moment`.
pub(crate) fn add(&mut self, bytes: u64, own_pixel: bool, moment: Moment) {
*match own_pixel {
true => &mut self.own_pixel,
false => &mut self.whole_texture,
} += bytes;
*match moment {
Moment::FirstInPass => &mut self.first_in_pass,
Moment::AfterBarrier => &mut self.after_barrier,
Moment::BeyondHeld => &mut self.beyond_held,
} += bytes;
}
/// All the copies' bytes.
pub(crate) fn bytes(&self) -> u64 {
self.own_pixel + self.whole_texture
}
}
/// What a shadow holds of its image since the pass's first copy into it or its last memory /// What a shadow holds of its image since the pass's first copy into it or its last memory
/// barrier after draws: areas, each copied whole, at most [`HELD`] of them; and, for the copies' /// barrier after draws: areas, each copied whole, at most [`HELD`] of them.
/// counters, whether a memory barrier left it holding nothing since it last held something.
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub(crate) struct Held { pub(crate) struct Held {
areas: Vec<Area>, areas: Vec<Area>,
/// A memory barrier after draws left it holding nothing, and it has held nothing since.
dropped: bool,
} }
impl Held { impl Held {
@@ -293,24 +239,6 @@ impl Held {
/// A memory barrier after draws: the shadow holds nothing of what they rendered. /// A memory barrier after draws: the shadow holds nothing of what they rendered.
pub(crate) fn clear(&mut self) { pub(crate) fn clear(&mut self) {
if !self.areas.is_empty() { self.areas.clear();
self.dropped = true;
self.areas.clear();
}
}
/// When a draw's copies come, taken before the draw plans them.
pub(crate) fn moment(&self) -> Moment {
match (self.areas.is_empty(), self.dropped) {
(false, _) => Moment::BeyondHeld,
(true, false) => Moment::FirstInPass,
(true, true) => Moment::AfterBarrier,
}
}
/// The draw's copies made the shadow hold something after it held nothing
/// ([`Moment::FirstInPass`] or [`Moment::AfterBarrier`]).
pub(crate) fn began(&mut self) {
self.dropped = false;
} }
} }
+1 -9
View File
@@ -2420,20 +2420,12 @@ impl WorkState {
// their ranges by writes submitted before, which its upload makes first // their ranges by writes submitted before, which its upload makes first
// (`crate::capture`). // (`crate::capture`).
let taken = self.changes.captured.take(&batch.leads); let taken = self.changes.captured.take(&batch.leads);
for (lead, copy_in) in &taken { for (_, copy_in) in &taken {
copy_in.backs(&mut batch.backs); copy_in.backs(&mut batch.backs);
if let Some(coherence) = &core.coherence { if let Some(coherence) = &core.coherence {
let flushes = batch.flushes.get_or_insert_with(Box::default); let flushes = batch.flushes.get_or_insert_with(Box::default);
flushes.copied.extend(copy_in.shared_ranges(coherence.atom)); flushes.copied.extend(copy_in.shared_ranges(coherence.atom));
} }
// A taker with nothing for the GPU has the copy-in as its submission
// (`Gpu::copy_in_only`). It has one segment, so its group finished it.
let seq = batch.leads[*lead];
if let Some((_, pending, _)) = (batch.finished.iter_mut())
.find(|(_, pending, _)| pending.seq == seq && pending.gpu.is_empty())
{
pending.gpu.copy_in_only = true;
}
} }
// The copies back owed by writes submitted before it to the Managed buffers its segments // The copies back owed by writes submitted before it to the Managed buffers its segments
// reach, which its upload makes first: as it goes, the order of each write and its // reach, which its upload makes first: as it goes, the order of each write and its
@@ -198,7 +198,8 @@ mod on_device {
/// The floor's last item, asked of the created device: every device of the cfg's kind /// The floor's last item, asked of the created device: every device of the cfg's kind
/// supports both of the runtime's set layouts (`vkGetDescriptorSetLayoutSupport`), the empty /// supports both of the runtime's set layouts (`vkGetDescriptorSetLayoutSupport`), the empty
/// set 0 and set 1 of the arrays, which `Device::new` asks before it makes them. /// set 0 and set 1 of the arrays, with the sampled-texture array's second elements where the
/// device reads attachments, which `Device::new` asks before it makes them.
#[test] #[test]
fn every_device_supports_the_runtimes_set_layouts() { fn every_device_supports_the_runtimes_set_layouts() {
let instance = crate::tests::validation::instance(&[]); let instance = crate::tests::validation::instance(&[]);
@@ -214,11 +215,13 @@ mod on_device {
let empty = vk::DescriptorSetLayoutCreateInfo::default(); let empty = vk::DescriptorSetLayoutCreateInfo::default();
// SAFETY: the device is live, with the floor's features. // SAFETY: the device is live, with the floor's features.
unsafe { supported(raw, &empty, 0) }.unwrap_or_else(|error| panic!("{name}: {error}")); unsafe { supported(raw, &empty, 0) }.unwrap_or_else(|error| panic!("{name}: {error}"));
with_arrays_layout(layout_counts(), |info| { for seconds in [false, device.core().attachment_reads] {
// SAFETY: the device is live, with the floor's features. with_arrays_layout(layout_counts(seconds), |info| {
unsafe { supported(raw, info, 1) } // SAFETY: the device is live, with the floor's features.
}) unsafe { supported(raw, info, 1) }
.unwrap_or_else(|error| panic!("{name}: {error}")); })
.unwrap_or_else(|error| panic!("{name}: {error}"));
}
println!("floor: {name}: set layouts 0 and 1 supported"); println!("floor: {name}: set layouts 0 and 1 supported");
} }
} }
@@ -256,7 +259,7 @@ mod on_device {
let start = Instant::now(); let start = Instant::now();
// SAFETY: the device is live and made at the floor. // SAFETY: the device is live and made at the floor.
let buffers = core.translator.profile().binds_kernel_buffers(); let buffers = core.translator.profile().binds_kernel_buffers();
let second = unsafe { Arrays::new(&core.device, &counters, buffers) } let second = unsafe { Arrays::new(&core.device, &counters, (false, buffers)) }
.unwrap_or_else(|error| panic!("{name}: a second set 1: {error}")); .unwrap_or_else(|error| panic!("{name}: a second set 1: {error}"));
let micros = start.elapsed().as_micros(); let micros = start.elapsed().as_micros();
assert_eq!(counters.gauges().device_samplers, 4, "{name}"); assert_eq!(counters.gauges().device_samplers, 4, "{name}");
@@ -1,87 +0,0 @@
//! The driver's make of a render content lowered for a 4:2:2 texture
//! (`LoweringInputs::chroma_pairs`) beside the same state's own content, under a device cfg on
//! every device of the cfg's kind: `colored_vertex` with the owned fixture `device_level`'s
//! `dl_runtime`, one sample of texture 0 through the runtime sampler at sampler 0, decoded at
//! texture 0; and `grd_half_many_samples` drawn by `grd_many_vertex`, 40 samples of each of its
//! eight textures through one runtime sampler, decoded at texture 3 (40 sites). Each content's
//! main pipeline is made by `finish_pipeline`, and the test prints its `vkCreateGraphicsPipelines`
//! time (`Metrics::pipeline_creation_nanos`), its translation's and its modules' SPIR-V bytes. The
//! driver's own shader cache is the job's: a job that times a cold make gives the process an empty
//! one.
//!
//! `llvm-as` assembles the functions; without it the test skips visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::kernel_map::Chroma;
use crate::tests::command::on_device::each_device;
use crate::tests::draw::on_device::{descriptor, examples, library};
use crate::{
ColorAttachmentDescriptor, FunctionDescriptor, PixelFormat, RenderPipelineDescriptor,
RenderPipelineState, StageSource,
};
use metal2vulkan_devtools::engine_dir;
#[test]
fn four_two_two_content_make_time() {
let (Some(examples), Some(levels), Some(many)) = (
examples(),
library(&engine_dir().join("device_level.ll")),
library(&engine_dir().join("grd_half_many_samples.ll")),
) else {
return;
};
let function = |library: &crate::Library, name| {
StageSource::Function(FunctionDescriptor::new(
library.function(name).expect("the function"),
))
};
let mut one = descriptor(&examples, "colored_fragment", PixelFormat::RGBA8Unorm);
one.fragment = Some(function(&levels, "dl_runtime"));
let mut forty = RenderPipelineDescriptor::new(function(&many, "grd_many_vertex"));
forty.fragment = Some(function(&many, "grd_half_many_samples"));
for color in &mut forty.color_attachments[..2] {
*color = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float));
}
let cases = [("1 site", one, 1u128), ("40 sites", forty, 1 << 3)];
each_device("4:2:2 content make time", |name, _, device| {
for (case, d, slots) in &cases {
let made = |what: &str, state: &RenderPipelineState| {
let before = device.counters().metrics();
(state.finish_pipeline())
.unwrap_or_else(|error| panic!("{name}: {case}: {what}: {error}"));
let after = device.counters().metrics();
let created = after.pipelines_created - before.pipelines_created;
let nanos = after.pipeline_creation_nanos - before.pipeline_creation_nanos;
println!(
"{name}: {case}: {what}: {created} pipeline in {:.1} ms, {} bytes of SPIR-V",
nanos as f64 / 1e6,
state.allocated_size()
);
assert_eq!(created, 1, "{name}: {case}: {what}: the pipelines made");
};
let state = (device.new_render_pipeline_state(d, |samplers| {
assert!(samplers.is_empty(), "{name}: {case}: {samplers:?}");
Ok(Vec::new())
}))
.unwrap_or_else(|error| panic!("{name}: {case}: {error}"));
made("plain", &state);
let before = device.counters().metrics();
let chroma = Chroma {
slots: [0, *slots],
handles: false,
};
let decoded = (state.for_draws(&device, (0, [0; 2], chroma)))
.unwrap_or_else(|error| panic!("{name}: {case}: {error}"));
let after = device.counters().metrics();
let contents = after.chroma_contents - before.chroma_contents;
assert_eq!(contents, 1, "{name}: {case}");
println!(
"{name}: {case}: 4:2:2 content translated in {:.1} ms",
(after.translation_nanos - before.translation_nanos) as f64 / 1e6
);
made("4:2:2", &decoded);
}
});
}
}
@@ -1,529 +0,0 @@
//! Metal's 4:2:2 chroma-pair textures (`GBGR422`, `BGRG422`) made over a buffer laid out as a
//! CoreVideo surface of the matching FourCC lays it out ('yuvs': Y0 Cb Y1 Cr; '2vuy': Cb Y0 Cr
//! Y1), as the consumer makes one for `newTextureWithDescriptor:iosurface:plane:`, under a device
//! cfg on every device of the cfg's kind, through the owned fixture `fpv_swizzled_reads`:
//!
//! - over a Shared and a Private buffer, a 64 by 8 texture of shader-read usage at rows 128 bytes
//! apart (the surface's own pitch for that width) and at 192, and a 640 by 480 one at 1280 over a
//! Private buffer (the consumer's camera frames: 'yuvs', 1280 bytes a row): each is made, in the
//! form `Buffer::texture_copy_cause` answers for it, which for the 640 by 480 one is in place;
//! - a read of each texel, and a nearest sample at its centre, answer Metal's decode exactly
//! (an Apple M3 Max under macOS 27.0.1): green the texel's own
//! luma, red and blue `(3c + n + 2) >> 2` of its pair's chroma `c` and the chroma `n` of the pair
//! on its side (left for an even texel, right for an odd one, the pair itself at the edges), each
//! code `c / 255` correctly rounded, alpha 1;
//! - a gather of each component at the corner of each 2 by 2 footprint answers those four texels'
//! values in Metal's order, `(i0, j1)`, `(i1, j1)`, `(i1, j0)`, `(i0, j0)`;
//! - a linear sample a quarter of the way between two texels, and at the corner of a footprint,
//! answers the weighted mean of the decoded texels (weights 3/4 and 1/4, or 1/4 each), within
//! `f32` rounding;
//! - each kernel state's dispatches run its content lowered for the texture: one content a state
//! (`Metrics::chroma_contents`), every dispatch counted (`Metrics::chroma_launches`), and the
//! texture counted live while it lives (`Gauges::chroma_textures`).
//!
//! On every device too, what Metal refuses of the formats is refused (`Refusal::ChromaPairs`: a
//! 2D array, an odd width, two levels, a view), and the uses the runtime does not build are gaps
//! (`Gap::ChromaPairsUse`: shader-write and render-target usage, a swizzle).
//!
//! The bytes are a hash of their place, so neighbouring pairs' chroma do not all differ by
//! multiples of 4 and the decode's rounding shows. `llvm-as` assembles the kernels; without it the
//! test skips visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
pub(crate) mod on_device {
use crate::tests::command::on_device::{each_device, finished};
use crate::texture::TextureObject;
use crate::{
Buffer, ChromaPairsGap, ChromaPairsRule, ComputePipelineDescriptor, ComputePipelineState,
Device, DispatchType, Error, FunctionDescriptor, Gap, IndexClass, Library, MemoryClass,
PixelFormat, Refusal, SamplerDescriptor, SamplerMinMagFilter, SamplerState, StageSource,
Texture, TextureDescriptor, TextureSwizzle, TextureType, TextureUsage,
};
use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError};
/// The two formats, each with the FourCC whose surface lays its bytes out.
const FORMATS: [(PixelFormat, &str); 2] = [
(PixelFormat::GBGR422, "yuvs"),
(PixelFormat::BGRG422, "2vuy"),
];
/// The threads of a threadgroup of every dispatch.
pub(crate) const GROUP: u32 = 64;
/// The fixture's library, or None where `llvm-as` is missing.
fn library() -> Option<Library> {
let path = engine_dir().join("fpv_swizzled_reads.ll");
match llvm_assemble(&path) {
Ok(bitcode) => Some(Library::from_air(&bitcode).expect("the library")),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(error) => panic!("{}: {error:?}", path.display()),
}
}
/// The kernel `name`'s state.
fn state(device: &Device, library: &Library, name: &str) -> ComputePipelineState {
let function = library.function(name).expect("the kernel");
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(function),
));
(device.new_compute_pipeline_state(&descriptor, |samplers| Ok(vec![0; samplers.len()])))
.unwrap_or_else(|error| panic!("{name}: {error}"))
}
/// Byte `k` of a texture's rows, counted along the rows without their padding: a hash of `k`.
pub(crate) fn byte(k: u32) -> u8 {
let mut h = k.wrapping_mul(2_654_435_761).wrapping_add(0x9e37_79b9);
h ^= h >> 15;
h = h.wrapping_mul(0x85eb_ca6b);
h ^= h >> 13;
h as u8
}
/// The bytes of a `width` by `height` texture at rows `pitch` bytes apart, each row's padding
/// 0xee.
fn rows(width: u32, height: u32, pitch: u64) -> Vec<u8> {
let row = 2 * width;
let mut bytes = vec![0xee; (pitch * u64::from(height)) as usize];
for y in 0..height {
for b in 0..row {
bytes[(u64::from(y) * pitch + u64::from(b)) as usize] = byte(y * row + b);
}
}
bytes
}
/// Metal's codes of texel `(x, y)` of a `width`-wide texture of `format` over [`rows`]' bytes:
/// red, green, blue, and alpha 255.
fn codes(format: PixelFormat, width: u32, x: u32, y: u32) -> [u32; 4] {
let row = 2 * width;
let at = |b: u32| u32::from(byte(y * row + b));
let pairs = width / 2;
let pair = x / 2;
let side = match x % 2 {
0 => pair.saturating_sub(1),
_ => (pair + 1).min(pairs - 1),
};
// The bytes of a pair: GBGR422's Y0 Cb Y1 Cr, BGRG422's Cb Y0 Cr Y1.
let (luma, cb, cr) = match format {
PixelFormat::GBGR422 => (if x % 2 == 0 { 0 } else { 2 }, 1, 3),
_ => (if x % 2 == 0 { 1 } else { 3 }, 0, 2),
};
let chroma = |byte: u32| (3 * at(pair * 4 + byte) + at(side * 4 + byte) + 2) >> 2;
[chroma(cr), at(pair * 4 + luma), chroma(cb), 255]
}
/// Metal's value of texel `(x, y)`: each code over 255, correctly rounded.
fn texel(format: PixelFormat, width: u32, x: u32, y: u32) -> [f32; 4] {
codes(format, width, x, y).map(|c| (f64::from(c) / 255.0) as f32)
}
/// A buffer of `class` holding `bytes` at its start, in a block of its own: a Private one
/// written by a blit from a Shared one.
pub(crate) fn buffer_of(
name: &str,
device: &Device,
class: MemoryClass,
bytes: &[u8],
) -> Buffer {
let len = bytes.len() as u64;
let shared = |len: u64| {
let block = (device.take_block(MemoryClass::Shared, len))
.unwrap_or_else(|error| panic!("{name}: {error}"));
(device.new_buffer(block.id, 0, len, None))
.unwrap_or_else(|error| panic!("{name}: {error}"))
};
let staged = shared(len);
let contents = staged.contents().expect("a Shared buffer");
// SAFETY: the buffer holds `len` bytes, all written, and no work is pending on it.
unsafe { (bytes.as_ptr()).copy_to_nonoverlapping(contents.as_ptr(), bytes.len()) };
if class == MemoryClass::Shared {
return staged;
}
let block =
(device.take_block(class, len)).unwrap_or_else(|error| panic!("{name}: {error}"));
let private = (device.new_buffer(block.id, 0, len, None))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let queue = device.new_command_queue(1).expect("a queue");
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut blit = command_buffer.blit_command_encoder().expect("an encoder");
(blit.copy_from_buffer_to_buffer(&staged, 0, &private, 0, len))
.unwrap_or_else(|error| panic!("{name}: the fill: {error}"));
blit.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}: the fill");
private
}
/// One thread of `kernel` at each of `positions` (8 bytes each) over `texture` through
/// `sampler`: each thread's `float4`.
fn run(
name: &str,
device: &Device,
(state, texture, sampler): (&ComputePipelineState, &Texture, &SamplerState),
positions: &[[u8; 8]],
) -> Vec<[f32; 4]> {
let n = positions.len() as u32;
let bytes: Vec<u8> = positions.iter().flatten().copied().collect();
let at = buffer_of(name, device, MemoryClass::Shared, &bytes);
let out = buffer_of(
name,
device,
MemoryClass::Shared,
&vec![0xab; 16 * n as usize],
);
let queue = device.new_command_queue(1).expect("a queue");
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder =
(command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder");
encoder
.set_compute_pipeline_state(state)
.expect("the state");
encoder.set_texture(Some(texture), 0).expect("the texture");
(encoder.set_sampler_state(Some(sampler), 0)).expect("the sampler");
encoder.set_buffer(Some(&out), 0, 0).expect("the output");
encoder.set_buffer(Some(&at), 0, 1).expect("the positions");
(encoder.dispatch_threads([n, 1, 1], [GROUP.min(n), 1, 1])).expect("the dispatch");
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
let contents = out.contents().expect("a Shared buffer");
// SAFETY: the dispatch that wrote the buffer finished, and its writes reach the host; the
// buffer holds `16 n` bytes.
let floats =
unsafe { std::slice::from_raw_parts(contents.as_ptr().cast::<f32>(), 4 * n as usize) };
(floats.chunks(4))
.map(|c| std::array::from_fn(|k| c[k]))
.collect()
}
/// A texel coordinate's position.
fn texel_at(x: u32, y: u32) -> [u8; 8] {
let mut p = [0u8; 8];
p[..4].copy_from_slice(&x.to_le_bytes());
p[4..].copy_from_slice(&y.to_le_bytes());
p
}
/// A normalized coordinate's position.
fn point(u: f32, v: f32) -> [u8; 8] {
let mut p = [0u8; 8];
p[..4].copy_from_slice(&u.to_le_bytes());
p[4..].copy_from_slice(&v.to_le_bytes());
p
}
fn bits(x: [f32; 4]) -> [u32; 4] {
x.map(f32::to_bits)
}
/// One texture to make and read: its size, the buffer's memory and the rows' pitch.
struct Case {
size: (u32, u32),
class: MemoryClass,
pitch: u64,
/// The consumer's camera frame, which must lie in place.
in_place: bool,
}
const CASES: [Case; 5] = [
Case {
size: (64, 8),
class: MemoryClass::Shared,
pitch: 128,
in_place: false,
},
Case {
size: (64, 8),
class: MemoryClass::Shared,
pitch: 192,
in_place: false,
},
Case {
size: (64, 8),
class: MemoryClass::Private,
pitch: 128,
in_place: false,
},
Case {
size: (64, 8),
class: MemoryClass::Private,
pitch: 192,
in_place: false,
},
Case {
size: (640, 480),
class: MemoryClass::Private,
pitch: 1280,
in_place: true,
},
];
/// The texels a case reads and samples: every texel of a 64 by 8 texture; the first 64 by 8 of
/// a larger one, and its last row's last 64 texels.
fn reached(width: u32, height: u32) -> Vec<(u32, u32)> {
let mut at: Vec<(u32, u32)> = (0..8).flat_map(|y| (0..64).map(move |x| (x, y))).collect();
if (width, height) != (64, 8) {
at.extend((width - 64..width).map(|x| (x, height - 1)));
}
at
}
#[test]
fn every_device_reads_samples_and_gathers_four_two_two_textures_over_a_surface_buffer() {
let Some(library) = library() else {
return;
};
each_device("4:2:2 textures over a surface buffer", |name, _, device| {
let _textures = (device.grant_indices(IndexClass::Texture, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let _samplers = (device.grant_indices(IndexClass::Sampler, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let nearest = (device.new_sampler_state(&SamplerDescriptor::new(), 1))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let mut d = SamplerDescriptor::new();
d.min_filter = SamplerMinMagFilter::Linear;
d.mag_filter = SamplerMinMagFilter::Linear;
let linear =
(device.new_sampler_state(&d, 2)).unwrap_or_else(|error| panic!("{name}: {error}"));
let read = state(&device, &library, "fpv_swz_read");
let sample = state(&device, &library, "fpv_swz_sample");
let gathers = ["x", "y", "z", "w"]
.map(|c| state(&device, &library, &format!("fpv_swz_gather_{c}")));
let before = device.counters().metrics();
for (format, fourcc) in FORMATS {
for case in &CASES {
let (width, height) = case.size;
let label = format!(
"{name}: {format:?} over a {:?} '{fourcc}' buffer, {width}x{height} at \
{}",
case.class, case.pitch
);
let buffer = buffer_of(
&label,
&device,
case.class,
&rows(width, height, case.pitch),
);
let mut d = TextureDescriptor::new(TextureType::Type2D, format, width, height);
d.usage = TextureUsage::SHADER_READ;
let answer = (buffer.texture_copy_cause(&d, 0, case.pitch))
.unwrap_or_else(|error| panic!("{label}: the answer: {error}"));
let texture = (buffer.new_texture(&d, Some(1), 0, case.pitch))
.unwrap_or_else(|error| panic!("{label}: the texture: {error}"));
let made = texture.copied_over().map(|(_, copy)| copy.kind.cause);
assert_eq!(made, answer, "{label}: the form made against the answer");
let live = device.counters().gauges().chroma_textures;
assert_eq!(live, 1, "{label}: the texture counted live");
if case.in_place {
assert_eq!(made, None, "{label}: in place");
}
let at = reached(width, height);
let want: Vec<[f32; 4]> = (at.iter())
.map(|&(x, y)| texel(format, width, x, y))
.collect();
let (w, h) = (width as f32, height as f32);
let centre = |x: u32, y: u32| point((x as f32 + 0.5) / w, (y as f32 + 0.5) / h);
let reads: Vec<[u8; 8]> = at.iter().map(|&(x, y)| texel_at(x, y)).collect();
let centres: Vec<[u8; 8]> = at.iter().map(|&(x, y)| centre(x, y)).collect();
let got = run(&label, &device, (&read, &texture, &nearest), &reads);
let got_nearest = run(&label, &device, (&sample, &texture, &nearest), &centres);
for (i, (want, &(x, y))) in want.iter().zip(&at).enumerate() {
assert_eq!(bits(got[i]), bits(*want), "{label}: read ({x}, {y})");
assert_eq!(
bits(got_nearest[i]),
bits(*want),
"{label}: nearest sample ({x}, {y})"
);
}
// The footprints whose top-left texel is in the first 63 by 7: a gather of
// each component at the footprint's corner, and a linear sample there and a
// quarter of the way from its top-left texel toward its top-right one.
let corners: Vec<(u32, u32)> =
(0..7).flat_map(|y| (0..63).map(move |x| (x, y))).collect();
let corner_points: Vec<[u8; 8]> = (corners.iter())
.map(|&(x, y)| point((x as f32 + 1.0) / w, (y as f32 + 1.0) / h))
.collect();
let quarter_points: Vec<[u8; 8]> = (corners.iter())
.map(|&(x, y)| point((x as f32 + 0.75) / w, (y as f32 + 0.5) / h))
.collect();
let value = |x: u32, y: u32| texel(format, width, x, y);
for (c, gather) in gathers.iter().enumerate() {
let got = run(
&label,
&device,
(gather, &texture, &nearest),
&corner_points,
);
for (i, &(x, y)) in corners.iter().enumerate() {
let quad = [
value(x, y + 1),
value(x + 1, y + 1),
value(x + 1, y),
value(x, y),
];
let want: [f32; 4] = std::array::from_fn(|k| quad[k][c]);
assert_eq!(
bits(got[i]),
bits(want),
"{label}: gather {c} at ({x}, {y})"
);
}
}
let got_corners = run(
&label,
&device,
(&sample, &texture, &linear),
&corner_points,
);
let got_quarters = run(
&label,
&device,
(&sample, &texture, &linear),
&quarter_points,
);
for (i, &(x, y)) in corners.iter().enumerate() {
let mean = |weights: [((u32, u32), f64); 4]| -> [f64; 4] {
std::array::from_fn(|c| {
(weights.iter())
.map(|&((x, y), weight)| f64::from(value(x, y)[c]) * weight)
.sum()
})
};
let corner = mean([
((x, y), 0.25),
((x + 1, y), 0.25),
((x, y + 1), 0.25),
((x + 1, y + 1), 0.25),
]);
let quarter = mean([
((x, y), 0.75),
((x + 1, y), 0.25),
((x, y), 0.0),
((x + 1, y), 0.0),
]);
for (got, want, what) in [
(got_corners[i], corner, "corner"),
(got_quarters[i], quarter, "quarter"),
] {
for c in 0..4 {
assert!(
(f64::from(got[c]) - want[c]).abs() <= 1e-6,
"{label}: linear {what} at ({x}, {y}): {got:?} for {want:?}"
);
}
}
}
println!(
"{label}: made {}, every texel read, sampled and gathered as Metal's \
decode",
match made {
None => "in place".to_owned(),
Some(cause) => format!("copied for {cause:?}"),
}
);
drop((texture, buffer));
let live = device.counters().gauges().chroma_textures;
assert_eq!(live, 0, "{label}: the texture no longer counted");
}
}
// Six kernel states, each with one content lowered for its texture slot 0 bound to a
// 4:2:2 texture, which every one of a case's eight dispatches runs.
let after = device.counters().metrics();
let contents = after.chroma_contents - before.chroma_contents;
let launches = after.chroma_launches - before.chroma_launches;
assert_eq!(
contents, 6,
"{name}: the contents lowered for 4:2:2 textures"
);
let dispatches = (8 * FORMATS.len() * CASES.len()) as u64;
assert_eq!(launches, dispatches, "{name}: the dispatches that ran them");
let bound = after.bound_dispatches - before.bound_dispatches;
let address = after.address_dispatches - before.address_dispatches;
println!(
"{name}: chroma_contents +{contents}, chroma_launches +{launches}, \
bound_dispatches +{bound}, address_dispatches +{address}"
);
});
}
#[test]
fn every_device_refuses_what_metal_refuses_of_four_two_two_textures() {
each_device("4:2:2 refusals", |name, _, device| {
let _textures = (device.grant_indices(IndexClass::Texture, 2, 1))
.unwrap_or_else(|error| panic!("{name}: {error}"));
for (format, _) in FORMATS {
let plain = || {
let mut d = TextureDescriptor::new(TextureType::Type2D, format, 64, 8);
d.usage = TextureUsage::SHADER_READ;
d
};
// A refusal as `Ok`, a gap as `Err`.
let refused = |rule| -> Result<Refusal, Gap> {
Ok(Refusal::ChromaPairs {
pixel_format: format,
rule,
})
};
let gap = |cause| -> Result<Refusal, Gap> { Err(Gap::ChromaPairsUse { cause }) };
let answered = |error: Error, what: &str| match error {
Error::Refused(refusal) => Ok(refusal),
Error::Unsupported(gap) => Err(gap),
other => panic!("{name}: {format:?}, {what}: {other}"),
};
let mut array = plain();
array.texture_type = TextureType::Type2DArray;
let mut odd = plain();
odd.width = 63;
let mut levels = plain();
levels.mipmap_level_count = 2;
let mut written = plain();
written.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE;
let mut rendered = plain();
rendered.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET;
let mut swizzled = plain();
swizzled.swizzle.red = TextureSwizzle::Green;
for (d, want, what) in [
(array, refused(ChromaPairsRule::TextureType), "a 2D array"),
(odd, refused(ChromaPairsRule::OddWidth), "an odd width"),
(levels, refused(ChromaPairsRule::Levels), "two levels"),
(
written,
gap(ChromaPairsGap::ShaderWrite),
"shader-write usage",
),
(
rendered,
gap(ChromaPairsGap::RenderTarget),
"render-target usage",
),
(swizzled, gap(ChromaPairsGap::Swizzle), "a swizzle"),
] {
match device.new_texture(&d, None) {
Err(error) => {
assert_eq!(answered(error, what), want, "{name}: {format:?}, {what}");
}
Ok(_) => panic!("{name}: {format:?}, {what}: made"),
}
}
let texture = (device.new_texture(&plain(), Some(2)))
.unwrap_or_else(|error| panic!("{name}: {format:?}: {error}"));
let view = texture.new_texture_view(format, TextureType::Type2D, 0..1, 0..1, None);
match view {
Err(error) => {
let want = refused(ChromaPairsRule::View);
assert_eq!(answered(error, "a view"), want, "{name}: {format:?}");
}
Ok(_) => panic!("{name}: {format:?}: a view made"),
}
}
println!("{name}: every 4:2:2 refusal and gap answered");
});
}
}
@@ -1,241 +0,0 @@
//! The GPU time of a linear sample of a 4:2:2 texture beside the same sample of an `RGBA8Unorm`
//! texture of its size, under a device cfg on every device of the cfg's kind, printed and asserting
//! nothing of time. The owned fixture `xr_samples`' `xr_sample_runtime` (through the runtime sampler
//! at sampler slot 0, a linear clamp-to-edge sampler state) and `xr_sample_constexpr` (through its
//! constexpr linear clamp-to-edge sampler) each take one sample at the centre of each texel of a
//! 1920 by 1080 frame, one thread a texel, and write it out, over a `GBGR422` texture made over a
//! Private buffer at 3,840 bytes a row (a 'yuvs' surface's pitch for that width) and over an
//! `RGBA8Unorm` texture made over a Private buffer at 7,680, each in the form
//! `Buffer::new_texture` makes it, which the lines name. The positions and the output are Private
//! buffers too.
//!
//! Each dispatch is a command buffer of its own, timed by its GPU start and end
//! (`CommandBuffer::gpu_start_time`, `CommandBuffer::gpu_end_time`). A round runs nine of each
//! kernel over each texture, the four taking turns, and takes each one's median. Unmeasured rounds
//! run first until a second has passed, so a GPU whose clocks rise under load has raised them;
//! then three rounds print each kernel's two medians and their ratio. The chroma counters show the
//! decode ran: each kernel's state makes one content lowered for its 4:2:2 slot, and each of its
//! dispatches over the `GBGR422` texture runs it (`Metrics::chroma_contents`,
//! `Metrics::chroma_launches`); no dispatch over the `RGBA8Unorm` texture does. Every value written
//! is finite and within [0, 1].
//!
//! Run it on one device with `--run-ignored only`. `llvm-as` assembles the kernels; without it the
//! test skips visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::tests::chroma_pairs::on_device::{buffer_of, byte, GROUP};
use crate::tests::command::on_device::{each_device, finished};
use crate::tests::draw::on_device::library;
use crate::texture::TextureObject;
use crate::{
Buffer, ComputePipelineDescriptor, ComputePipelineState, DispatchType, FunctionDescriptor,
IndexClass, MemoryClass, PixelFormat, SamplerDescriptor, SamplerMinMagFilter, StageSource,
Texture, TextureDescriptor, TextureType, TextureUsage,
};
use metal2vulkan_devtools::engine_dir;
use std::time::{Duration, Instant};
/// The frame's width and height.
const WIDTH: u32 = 1920;
const HEIGHT: u32 = 1080;
/// The dispatches of each kernel over each texture in a round.
const RUNS: usize = 9;
/// The rounds printed.
const ROUNDS: usize = 3;
/// How long the unmeasured rounds run: at least one round.
const WARM: Duration = Duration::from_secs(1);
/// The kernels, each with the sampler it samples through.
const KERNELS: [(&str, &str); 2] = [
("a runtime sampler", "xr_sample_runtime"),
("a constexpr sampler", "xr_sample_constexpr"),
];
/// The textures' formats, each with its bytes a texel.
const FORMATS: [(PixelFormat, u64); 2] =
[(PixelFormat::GBGR422, 2), (PixelFormat::RGBA8Unorm, 4)];
/// The sampler state's index, and the constexpr sampler's.
const SAMPLER: u32 = 1;
const CONSTEXPR: u32 = 2;
#[test]
#[ignore = "prints GPU times; run it on one device with --run-ignored only"]
fn time_a_linear_sample_of_a_1080p_frame() {
let Some(library) = library(&engine_dir().join("xr_samples.ll")) else {
return;
};
let n = WIDTH * HEIGHT;
let positions: Vec<u8> = (0..HEIGHT)
.flat_map(|y| (0..WIDTH).map(move |x| (x, y)))
.flat_map(|(x, y)| {
[
(x as f32 + 0.5) / WIDTH as f32,
(y as f32 + 0.5) / HEIGHT as f32,
]
})
.flat_map(f32::to_le_bytes)
.collect();
// Each output starts as NaNs, so a dispatch that wrote nothing fails the check.
let unwritten = vec![0xff; 16 * n as usize];
each_device("4:2:2 linear sample time", |name, _, device| {
let _grants =
[(IndexClass::Texture, 1), (IndexClass::Sampler, SAMPLER)].map(|(class, first)| {
(device.grant_indices(class, first, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"))
});
let mut d = SamplerDescriptor::new();
d.min_filter = SamplerMinMagFilter::Linear;
d.mag_filter = SamplerMinMagFilter::Linear;
let sampler = (device.new_sampler_state(&d, SAMPLER))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let states: Vec<ComputePipelineState> = (KERNELS.iter())
.map(|&(_, kernel)| {
let function = library.function(kernel).expect("the kernel");
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(function),
));
(device.new_compute_pipeline_state(&descriptor, |samplers| {
Ok(vec![CONSTEXPR; samplers.len()])
}))
.unwrap_or_else(|error| panic!("{name}: {kernel}: {error}"))
})
.collect();
let textures: Vec<(Texture, Buffer, String)> = (FORMATS.iter().zip(1..))
.map(|(&(format, texel), index)| {
let pitch = texel * u64::from(WIDTH);
let bytes: Vec<u8> = (0..pitch * u64::from(HEIGHT))
.map(|k| byte(k as u32))
.collect();
let buffer = buffer_of(name, &device, MemoryClass::Private, &bytes);
let mut d = TextureDescriptor::new(TextureType::Type2D, format, WIDTH, HEIGHT);
d.usage = TextureUsage::SHADER_READ;
let texture = (buffer.new_texture(&d, Some(index), 0, pitch))
.unwrap_or_else(|error| panic!("{name}: {format:?}: {error}"));
let form = match texture.copied_over() {
None => "in place".to_owned(),
Some((_, copy)) => format!("copied for {:?}", copy.kind.cause),
};
(texture, buffer, form)
})
.collect();
let uv = buffer_of(name, &device, MemoryClass::Private, &positions);
let outs: Vec<Vec<Buffer>> = (KERNELS.iter())
.map(|_| {
(FORMATS.iter())
.map(|_| buffer_of(name, &device, MemoryClass::Private, &unwritten))
.collect()
})
.collect();
let queue = device.new_command_queue(1).expect("a queue");
// One dispatch of `state` over `texture` into `out`, in a command buffer of its own:
// its GPU time in nanoseconds.
let time = |state: &ComputePipelineState, texture: &Texture, out: &Buffer| -> u64 {
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = (command_buffer.compute_command_encoder(DispatchType::Serial))
.expect("an encoder");
encoder
.set_compute_pipeline_state(state)
.expect("the state");
encoder.set_texture(Some(texture), 0).expect("the texture");
(encoder.set_sampler_state(Some(&sampler), 0)).expect("the sampler");
encoder.set_buffer(Some(&uv), 0, 0).expect("the positions");
encoder.set_buffer(Some(out), 0, 1).expect("the output");
(encoder.dispatch_threads([n, 1, 1], [GROUP, 1, 1])).expect("the dispatch");
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
(command_buffer.gpu_end_time()).saturating_sub(command_buffer.gpu_start_time())
};
// Each kernel's median over each texture, the four taking turns.
let round = || -> Vec<Vec<u64>> {
let mut times = vec![vec![Vec::with_capacity(RUNS); FORMATS.len()]; KERNELS.len()];
for _ in 0..RUNS {
for ((state, outs), times) in states.iter().zip(&outs).zip(&mut times) {
for (((texture, ..), out), times) in
textures.iter().zip(outs).zip(times.iter_mut())
{
times.push(time(state, texture, out));
}
}
}
(times.into_iter())
.map(|kernel| {
(kernel.into_iter())
.map(|mut runs| {
runs.sort_unstable();
runs[RUNS / 2]
})
.collect()
})
.collect()
};
let before = device.counters().metrics();
let warming = Instant::now();
let mut warm = 0;
while warm == 0 || warming.elapsed() < WARM {
round();
warm += 1;
}
println!(
"{name}: {warm} unmeasured rounds in {} ms",
warming.elapsed().as_millis()
);
for r in 0..ROUNDS {
for ((sampler, _), medians) in KERNELS.iter().zip(round()) {
let [(chroma, chroma_form), (plain, plain_form)] =
[0, 1].map(|f| (medians[f], &textures[f].2));
println!(
"{name}: round {r}: {sampler}: {:?} {chroma_form}: {chroma} ns; {:?} \
{plain_form}: {plain} ns; ratio {:.3}",
FORMATS[0].0,
FORMATS[1].0,
chroma as f64 / plain.max(1) as f64
);
}
}
let after = device.counters().metrics();
let contents = after.chroma_contents - before.chroma_contents;
let launches = after.chroma_launches - before.chroma_launches;
println!(
"{name}: chroma_contents +{contents}, chroma_launches +{launches}, \
translation_at_encode_max_nanos {}",
after.translation_at_encode_max_nanos
);
assert_eq!(
contents,
KERNELS.len() as u64,
"{name}: the contents lowered for the 4:2:2 texture"
);
let decoded = ((warm + ROUNDS) * RUNS * KERNELS.len()) as u64;
assert_eq!(launches, decoded, "{name}: the dispatches that ran them");
// Every value each kernel wrote over each texture.
let len = 16 * u64::from(n);
let block = (device.take_block(MemoryClass::Shared, len))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let staged = (device.new_buffer(block.id, 0, len, None))
.unwrap_or_else(|error| panic!("{name}: {error}"));
for ((_, kernel), outs) in KERNELS.iter().zip(&outs) {
for ((format, _), out) in FORMATS.iter().zip(outs) {
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut blit = command_buffer.blit_command_encoder().expect("an encoder");
(blit.copy_from_buffer_to_buffer(out, 0, &staged, 0, len))
.unwrap_or_else(|error| panic!("{name}: the read: {error}"));
blit.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}: the read");
let contents = staged.contents().expect("a Shared buffer");
// SAFETY: the copy that wrote the buffer finished, and its writes reach the
// host; the buffer holds `4 n` floats.
let floats = unsafe {
std::slice::from_raw_parts(contents.as_ptr().cast::<f32>(), 4 * n as usize)
};
let wrong = (floats.iter()).position(|v| !(0.0..=1.0).contains(v));
assert_eq!(wrong, None, "{name}: {kernel} over {format:?}: a value");
}
}
});
}
}
@@ -50,7 +50,6 @@ pub(crate) mod on_device {
numbered: Vec::new(), numbered: Vec::new(),
constexprs: Vec::new(), constexprs: Vec::new(),
reads_unbound: false, reads_unbound: false,
handle_float_images: false,
writes_unbound: false, writes_unbound: false,
unbound_storage: false, unbound_storage: false,
has_effects: true, has_effects: true,
@@ -9,13 +9,10 @@
//! and column among them; `cr_int` reads an `R32Sint` cube array of two cubes and two levels at //! and column among them; `cr_int` reads an `R32Sint` cube array of two cubes and two levels at
//! every texel of every face, cube and level. Each read is the texel uploaded there. `cr_float` //! every texel of every face, cube and level. Each read is the texel uploaded there. `cr_float`
//! over an `RGBA8Unorm_sRGB` cube is compared with `cr_ref`'s read of a 2D array of six slices //! over an `RGBA8Unorm_sRGB` cube is compared with `cr_ref`'s read of a 2D array of six slices
//! holding the same bytes at the same levels: the device's sRGB decode, through a fetch. //! holding the same bytes at the same levels: the device's sRGB decode, through a fetch. Each
//! `cr_depth` reads a `Depth32Float` depth cube of three levels and `cr_depth_array` a depth cube //! kernel also reads past the level's extent on each axis (inside level 0's), at face 6 and past,
//! array of two cubes and two levels (`depthcube<float, access::read>`, //! at the level count and past, at the cube count and past, and at `u32::MAX` on each operand:
//! `depthcube_array<float, access::read>`), each read the depth uploaded there. Each kernel also //! each Metal's out-of-bounds texel, zero with alpha 1 for a format without alpha.
//! reads past the level's extent on each axis (inside level 0's), at face 6 and past, at the level
//! count and past, at the cube count and past, and at `u32::MAX` on each operand: each Metal's
//! out-of-bounds texel, zero with alpha 1 for a format without alpha, and zero for a depth.
//! //!
//! `llvm-as` assembles the kernels; without it the test skips visibly. //! `llvm-as` assembles the kernels; without it the test skips visibly.
@@ -115,53 +112,13 @@ define void @cr_ref(ptr addrspace(1) %t, ptr addrspace(1) noundef %at, ptr addrs
ret void ret void
} }
define void @cr_depth(ptr addrspace(1) %t, ptr addrspace(1) noundef %at, ptr addrspace(1) noundef %out, i32 noundef %gid) {
%s = tail call ptr addrspace(2) @air.get_read_sampler()
%z = zext i32 %gid to i64
%i = shl i64 %z, 1
%pa = getelementptr inbounds <4 x i32>, ptr addrspace(1) %at, i64 %i
%a = load <4 x i32>, ptr addrspace(1) %pa, align 16
%xy = shufflevector <4 x i32> %a, <4 x i32> poison, <2 x i32> <i32 0, i32 1>
%f = extractelement <4 x i32> %a, i64 2
%l = extractelement <4 x i32> %a, i64 3
%r = tail call { float, i8 } @air.read_depth_cube.f32(ptr addrspace(1) %t, ptr addrspace(2) %s, i32 1, <2 x i32> %xy, i32 %f, i32 %l, i32 1)
%d = extractvalue { float, i8 } %r, 0
%v = insertelement <4 x float> zeroinitializer, float %d, i64 0
%po = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %z
store <4 x float> %v, ptr addrspace(1) %po, align 16
ret void
}
define void @cr_depth_array(ptr addrspace(1) %t, ptr addrspace(1) noundef %at, ptr addrspace(1) noundef %out, i32 noundef %gid) {
%s = tail call ptr addrspace(2) @air.get_read_sampler()
%z = zext i32 %gid to i64
%i = shl i64 %z, 1
%pa = getelementptr inbounds <4 x i32>, ptr addrspace(1) %at, i64 %i
%a = load <4 x i32>, ptr addrspace(1) %pa, align 16
%j = or i64 %i, 1
%pb = getelementptr inbounds <4 x i32>, ptr addrspace(1) %at, i64 %j
%b = load <4 x i32>, ptr addrspace(1) %pb, align 16
%xy = shufflevector <4 x i32> %a, <4 x i32> poison, <2 x i32> <i32 0, i32 1>
%f = extractelement <4 x i32> %a, i64 2
%l = extractelement <4 x i32> %a, i64 3
%c = extractelement <4 x i32> %b, i64 0
%r = tail call { float, i8 } @air.read_depth_cube_array.f32(ptr addrspace(1) %t, ptr addrspace(2) %s, i32 1, <2 x i32> %xy, i32 %f, i32 %c, i32 %l, i32 1)
%d = extractvalue { float, i8 } %r, 0
%v = insertelement <4 x float> zeroinitializer, float %d, i64 0
%po = getelementptr inbounds <4 x float>, ptr addrspace(1) %out, i64 %z
store <4 x float> %v, ptr addrspace(1) %po, align 16
ret void
}
declare ptr addrspace(2) @air.get_read_sampler() declare ptr addrspace(2) @air.get_read_sampler()
declare { <4 x float>, i8 } @air.read_texture_cube.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, i32, i32) declare { <4 x float>, i8 } @air.read_texture_cube.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, i32, i32)
declare { <4 x i32>, i8 } @air.read_texture_cube.u.v4i32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, i32, i32) declare { <4 x i32>, i8 } @air.read_texture_cube.u.v4i32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, i32, i32)
declare { <4 x i32>, i8 } @air.read_texture_cube_array.s.v4i32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, i32, i32, i32) declare { <4 x i32>, i8 } @air.read_texture_cube_array.s.v4i32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, i32, i32, i32)
declare { <4 x float>, i8 } @air.read_texture_2d_array.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, <2 x i32>, i32, i32) declare { <4 x float>, i8 } @air.read_texture_2d_array.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, <2 x i32>, i32, i32)
declare { float, i8 } @air.read_depth_cube.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x i32>, i32, i32, i32)
declare { float, i8 } @air.read_depth_cube_array.f32(ptr addrspace(1), ptr addrspace(2), i32, <2 x i32>, i32, i32, i32, i32)
!air.kernel = !{!0, !10, !20, !30, !40, !50} !air.kernel = !{!0, !10, !20, !30}
!air.version = !{!8} !air.version = !{!8}
!air.language_version = !{!9} !air.language_version = !{!9}
!0 = !{ptr @cr_float, !1, !2} !0 = !{ptr @cr_float, !1, !2}
@@ -184,12 +141,6 @@ declare { float, i8 } @air.read_depth_cube_array.f32(ptr addrspace(1), ptr addrs
!30 = !{ptr @cr_ref, !1, !31} !30 = !{ptr @cr_ref, !1, !31}
!31 = !{!32, !4, !5, !6} !31 = !{!32, !4, !5, !6}
!32 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d_array<float, read>", !"air.arg_name", !"t"} !32 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d_array<float, read>", !"air.arg_name", !"t"}
!40 = !{ptr @cr_depth, !1, !41}
!41 = !{!42, !4, !5, !6}
!42 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"depthcube<float, read>", !"air.arg_name", !"t"}
!50 = !{ptr @cr_depth_array, !1, !51}
!51 = !{!52, !4, !5, !6}
!52 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"depthcube_array<float, read>", !"air.arg_name", !"t"}
"#; "#;
/// A texture's bytes and the words a read of each texel answers. /// A texture's bytes and the words a read of each texel answers.
@@ -270,21 +221,6 @@ declare { float, i8 } @air.read_depth_cube_array.f32(ptr addrspace(1), ptr addrs
outside: [0, 0, 0, 1], outside: [0, 0, 0, 1],
}; };
/// The depth of texel `(x, y)` of level `level` of layer `layer`: distinct, inside [0, 1], and
/// exact in `float`.
fn depth(layer: u32, level: u32, x: u32, y: u32) -> f32 {
(64 * layer + 16 * level + 4 * y + x + 1) as f32 / 1024.0
}
/// A depth read answers the depth in its first word; the kernels store zero in the others.
const DEPTH: Texels = Texels {
format: PixelFormat::Depth32Float,
size: 4,
bytes: |layer, level, x, y| depth(layer, level, x, y).to_le_bytes().to_vec(),
read: |layer, level, x, y| [depth(layer, level, x, y).to_bits(), 0, 0, 0],
outside: [0; 4],
};
/// The sRGB texture's reads are compared with the 2D array's, not with these words. /// The sRGB texture's reads are compared with the 2D array's, not with these words.
const SRGB: Texels = Texels { const SRGB: Texels = Texels {
format: PixelFormat::RGBA8UnormSRGB, format: PixelFormat::RGBA8UnormSRGB,
@@ -459,7 +395,7 @@ declare { float, i8 } @air.read_depth_cube_array.f32(ptr addrspace(1), ptr addrs
}; };
let library = Library::from_air(&bitcode).expect("the library"); let library = Library::from_air(&bitcode).expect("the library");
each_device("cube_reads", |name, _, device| { each_device("cube_reads", |name, _, device| {
let _textures = (device.grant_indices(IndexClass::Texture, 1, 7)) let _textures = (device.grant_indices(IndexClass::Texture, 1, 5))
.unwrap_or_else(|error| panic!("{name}: {error}")); .unwrap_or_else(|error| panic!("{name}: {error}"));
let mut buffers = Buffers::sized(&device, 1 << 20); let mut buffers = Buffers::sized(&device, 1 << 20);
let queue = device.new_command_queue(4).expect("a queue"); let queue = device.new_command_queue(4).expect("a queue");
@@ -468,8 +404,6 @@ declare { float, i8 } @air.read_depth_cube_array.f32(ptr addrspace(1), ptr addrs
(1, "cr_float", TextureType::Cube, &FLOAT, 3, 1), (1, "cr_float", TextureType::Cube, &FLOAT, 3, 1),
(2, "cr_uint", TextureType::Cube, &UINT, 3, 1), (2, "cr_uint", TextureType::Cube, &UINT, 3, 1),
(3, "cr_int", TextureType::CubeArray, &INT, 2, 2), (3, "cr_int", TextureType::CubeArray, &INT, 2, 2),
(6, "cr_depth", TextureType::Cube, &DEPTH, 3, 1),
(7, "cr_depth_array", TextureType::CubeArray, &DEPTH, 2, 2),
] { ] {
let shape = (texture_type, texels, levels, 6 * cubes); let shape = (texture_type, texels, levels, 6 * cubes);
let t = texture(name, &device, shape, index); let t = texture(name, &device, shape, index);
+27 -44
View File
@@ -21,9 +21,7 @@
//! of a plane, the first included, names the general layout, with or without the call before it. //! of a plane, the first included, names the general layout, with or without the call before it.
//! While the surface lives, the surface imports gauge holds its two planes; it has no buffer and //! While the surface lives, the surface imports gauge holds its two planes; it has no buffer and
//! no export handle. Each plane's image takes the usage its texture's bind flags give and no //! no export handle. Each plane's image takes the usage its texture's bind flags give and no
//! other, on every device: made rendered and sampled under a render target shaders read, copied, //! other: made rendered and sampled, no storage; made sampled alone, not rendered; and a texture
//! sampled and rendered, with no storage and no attachment feedback loop usage, so a draw reads it
//! through its shadow; made sampled alone, not rendered; and a texture
//! over a plane whose uses ask storage is `Gap::SurfaceUsage`, where the device stores its //! over a plane whose uses ask storage is `Gap::SurfaceUsage`, where the device stores its
//! format. Planes made with `PixelFormatView` usage, an 8-bit luma, a chroma and a 10-bit luma, //! format. Planes made with `PixelFormatView` usage, an 8-bit luma, a chroma and a 10-bit luma,
//! list no format past their own, their texture's and that one's sRGB sibling (the 10-bit luma's //! list no format past their own, their texture's and that one's sRGB sibling (the 10-bit luma's
@@ -1068,17 +1066,14 @@ mod on_device {
}); });
} }
/// Each plane's image takes the usage its texture's bind flags give and no other, on /// Each plane's image takes the usage its texture's bind flags give and no other. Made
/// every device. Made rendered and sampled (`D3D11_BIND_RENDER_TARGET | /// rendered and sampled (`D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE`, as a
/// D3D11_BIND_SHADER_RESOURCE`, as a video's planes are) under a texture of the consumer's /// video's planes are), it is copied and sampled, and rendered at most beside, with no
/// planes' uses (`ShaderRead | RenderTarget`), a render target shaders read, which a draw /// storage; made sampled alone, it is copied and sampled, and not rendered. A texture over
/// may read in its own pass, it is copied, sampled and rendered (0x17), with no storage and /// a plane whose uses ask storage (`ShaderWrite`) is `Gap::SurfaceUsage` of storage, where
/// no attachment feedback loop usage, whether or not the device has the loop; made sampled /// the device stores the texture's format through a storage image without a format, as
/// alone under a texture shaders read, it is copied and sampled (0x7), and not rendered. A /// Direct3D 11 made the texture without `D3D11_BIND_UNORDERED_ACCESS`; where it does not,
/// texture over a plane whose uses ask storage (`ShaderWrite`) is `Gap::SurfaceUsage` of /// the uses ask no storage and the import is made.
/// storage, where the device stores the texture's format through a storage image without a
/// format, as Direct3D 11 made the texture without `D3D11_BIND_UNORDERED_ACCESS`; where it
/// does not, the uses ask no storage and the import is made.
#[test] #[test]
fn every_device_makes_a_direct3d_11_plane_of_the_usage_its_bind_flags_give() { fn every_device_makes_a_direct3d_11_plane_of_the_usage_its_bind_flags_give() {
each_device("import_d3d11_surface_usage", |name, _, device| { each_device("import_d3d11_surface_usage", |name, _, device| {
@@ -1088,34 +1083,22 @@ mod on_device {
let copied = vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST; let copied = vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST;
let read = copied | vk::ImageUsageFlags::SAMPLED; let read = copied | vk::ImageUsageFlags::SAMPLED;
let rendered = read | vk::ImageUsageFlags::COLOR_ATTACHMENT; let rendered = read | vk::ImageUsageFlags::COLOR_ATTACHMENT;
let looped = device.core().feedback_loop; for (bind, given) in [(BOUND, rendered), (SHADER_RESOURCE, read)] {
for (bind, given, uses) in [
(
BOUND,
rendered,
TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET,
),
(SHADER_RESOURCE, read, TextureUsage::SHADER_READ),
] {
let textures = PLANES let textures = PLANES
.each_ref() .each_ref()
.map(|p| d3d.shared_texture(p.width, p.height, p.dxgi, bind)); .map(|p| d3d.shared_texture(p.width, p.height, p.dxgi, bind));
let planes: Vec<D3d11Plane<'_>> = (textures.iter().zip(&PLANES)) let planes: Vec<D3d11Plane<'_>> = (textures.iter().zip(&PLANES))
.map(|(texture, plane)| { .map(|(texture, plane)| D3d11Plane {
let mut descriptor = TextureDescriptor::new( handle: texture.handle.as_handle(),
image_format: plane.image,
bind_flags: bind,
descriptor: TextureDescriptor::new(
TextureType::Type2D, TextureType::Type2D,
plane.view, plane.view,
plane.width, plane.width,
plane.height, plane.height,
); ),
descriptor.usage = uses; index: None,
D3d11Plane {
handle: texture.handle.as_handle(),
image_format: plane.image,
bind_flags: bind,
descriptor,
index: None,
}
}) })
.collect(); .collect();
let surface = (device.import_d3d11_surface(&planes)) let surface = (device.import_d3d11_surface(&planes))
@@ -1127,19 +1110,20 @@ mod on_device {
); );
let usage = texture.object().image_usage(); let usage = texture.object().image_usage();
println!( println!(
"d3d11-usage: {label}: the image's usage {:#x}, the flags give {:#x}; \ "d3d11-usage: {label}: the image's usage {:#x}, the flags give {:#x}",
the device has the attachment feedback loop: {looped}",
usage.as_raw(), usage.as_raw(),
given.as_raw() given.as_raw()
); );
assert_eq!( assert_eq!(
usage.as_raw(), (usage & !given).as_raw(),
given.as_raw(), 0,
"{label}: the usage the bind flags give, and no other" "{label}: a usage the bind flags do not give, of {:#x}",
usage.as_raw()
); );
assert!( assert!(
!texture.looped(), usage.contains(read),
"{label}: a draw reads the plane through its shadow, not the loop" "{label}: copied and sampled: {:#x}",
usage.as_raw()
); );
} }
} }
@@ -1449,9 +1433,8 @@ mod on_device {
held.contains(feature) held.contains(feature)
}; };
let imports = |usage: vk::ImageUsageFlags, list: &[vk::Format]| { let imports = |usage: vk::ImageUsageFlags, list: &[vk::Format]| {
(import_query(core, format, usage, list)).is_ok_and(|(external, _)| { (import_query(core, format, usage, list)).is_ok_and(|(features, _)| {
(external.external_memory_features) features.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE)
.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE)
}) })
}; };
let wanted = vk::ImageUsageFlags::SAMPLED let wanted = vk::ImageUsageFlags::SAMPLED
Loaded 100 of 346 files, more files were not shown because too many files have changed in this diff. Show more