Fetch: the interlocked storage forms go; one input-attachment form, ordered by ROA where the device has it

What. The pixel interlock's storage forms of framebuffer fetch, of the fragment imageblock and of
the shadow stencil are deleted, with their snapshot reads, the sample planes' split and merge
modules, the stencil shadow's copies and the binder, pipeline and runtime items that served them.
A color input now has one form on every device: its input attachment, ordered by
rasterization-order attachment access where the device has it, and elsewhere ordered between
draws alone, noted `PrecisionNote::UnorderedFetchWithinDraw`. The pixel interlock serves raster
order groups only; on a device without rasterization-order access a group on a color input or a
read output does not interlock. What had no other form is refused, typed:
- a fragment function's imageblock use, `Unsupported{Imageblocks, NotImplemented}`;
- a `[[stencil]]` output on a device without `VK_EXT_shader_stencil_export`, naming
  `StencilExport`;
- a merge, a rotated blend or a logic operation that reads the attachment, on a device without
  rasterization-order access, naming `FramebufferFetch` and
  `RasterizationOrderColorAttachmentAccess`.

Why. Rule 2 (one form per Vulkan capability) and rule 4 (small): the storage forms were a second
form of fetch, imageblocks and stencil output chosen by the interlock feature, outside the eight
allowed second forms. The runtime never took them under the identity domains.

Versions: ARTIFACT_FORMAT_VERSION 586 -> 587 (a placeholder; the landing sets the number).
SEMANTICS_VERSION moves in this stack's fourth commit and the runtime-sources pin in its fifth.
RUNTIME_VERSION is not bumped.

Removed public items (crates/metal2vulkan/tests/api_signatures.tsv): pipeline::StorageAttachmentUse,
ShadowStencilUse, FragmentImageblock, ImageblockMechanism, SnapshotForm, SnapshotRefusal,
StorageAttachmentView; bind::PlanesSplitModule, PlanesMergeModules, StencilSplitModule,
planes_split_module, planes_merge_modules, stencil_split_module, CopySource, FragmentTests;
RuntimeFact::{FragmentImageblock, InterlockedFramebufferFetch, MovableStorageWrites,
ShadowStencil, TestedStorageWrites}; PushField::{ShadowStencilState, SnapshotPhase,
StorageKeptChannels}; ResourceKind::SnapshotTexels, BindingSource::SnapshotTexels,
WriteSource::{ShadowStencil, SnapshotTexels}, PushHole::SnapshotPhase,
DrawReplayRule::{FragmentImageblock, ShaderStencil}, PlanesCopy::Alpha8,
ExtendedRangeBlend::OneColorChannel, PrivateRenderField::SampleMask,
PrecisionNote::UnmeasuredFetchBlend (translator and runtime), runtime
RenderPipelineKind::{Imageblock, ShaderStencil}. Changed: FramebufferFetchInputs::of(read, colors),
DepthStencilCopy::{StencilExport, StencilPlane}, WriteSource::TileAttachment.

Runtime README, known gaps: a new bullet names a fragment function with imageblock data (an input
or output declared [[imageblock_data]]) as refused on every device, and the stencil output bullet
says the runtime has refused it on a device without the extension all along. Both say why: the
forms deleted here bound a storage image through a descriptor, which the identity domains the
runtime compiles under hold none of. The raster order group bullet already names its refusal.
docs/REFUSALS.md is unchanged (scripts/refusal-surface/refusal_surface.py leaves it as it is).

Consumer check (~/.cache/m2v-orch/consumer-uses.sh, consumer development e76e2ffeb4 plus its 49
steelbrain/* tips younger than a day): 0 code hits on development for every removed name above
(Imageblock appears there only in rt_platform/diag.rs comments); UnmeasuredFetchBlend and
OneColorChannel hit only crates/reims-vgpu-vulkan on unlanded lane branches, none on development.

This commit does not build crates/metal2vulkan-validation alone: its executor still names the
removed pipeline items until the next commit, which removes its storage-form arms.

Verified: in the stack's second commit, which states every job; this commit alone does not
build the validation crate.
This commit is contained in:
Anees Iqbal committed 2026-11-21 04:39:18 -08:00
1 parent a449642cc7
commit 7e8b93d953
130 files changed
+1262 -22689

No files matched your search

@@ -83,11 +83,9 @@
// formats' blends are each other's through the measured field orders and share no word, so no
// reading here is a constant and the orders are confirmed.
//
// So the word view's refusal of a packed 16-bit color input was ours, and the fetch is built on
// the decode the blend already uses (`lower::fragment::fetch`, `stage_io::word_color::decode`).
// The tile answers are the storage form's near-equivalence, not the word view's: our form reads
// the attachment's memory for every format, so a packed 16-bit attachment the device renders
// directly reads the codes too.
// So Metal's fetch of a packed 16-bit attachment reads the value of its codes, by the decode the
// blend already uses (`stage_io::word_color::decode`): the product's refusal of such a color input
// (`NotImplemented(Format)`) is its own gap, not Metal's.
//
// clang -O2 -fobjc-arc -framework Metal -framework Foundation -o packed16_word_fetch \
// packed16_word_fetch.m
@@ -736,8 +736,8 @@ impl Row {
}
/// What the runtime answers for a row that reads or samples with no barrier, where it takes
/// the read through a copy cleared to the clear or through a snapshot (the module docs): the
/// clear, as the barrier's rows answer. `None` for every other row.
/// the read through a copy cleared to the clear (the module docs): the clear, as the barrier's
/// rows answer. `None` for every other row.
fn drawn(&self) -> Option<Vec<u8>> {
match self.shape {
Shape::Small {
@@ -831,7 +831,7 @@ impl Case for PassStartRead {
})
.collect();
// A read with no barrier may answer the clear where the runtime reads it through a copy
// cleared to it or a snapshot (the module docs).
// cleared to it (the module docs).
if let Some(bytes) = self.row.drawn() {
allowances.push(Allowance::new(
format!("case/{}", texels_site(0)),
@@ -165,8 +165,6 @@ pub enum Degradation {
CoverageReadsRoundedAlpha,
/// `metal2vulkan-degrade-device-alpha-coverage`.
DeviceAlphaCoverage,
/// `metal2vulkan-degrade-unmeasured-fetch-blend`.
UnmeasuredFetchBlend,
/// `metal2vulkan-degrade-unordered-fetch-within-draw`.
UnorderedFetchWithinDraw,
/// `metal2vulkan-degrade-native-logic-operation`.
@@ -263,7 +261,6 @@ impl Degradation {
Degradation::DeviceSampleLevel,
Degradation::CoverageReadsRoundedAlpha,
Degradation::DeviceAlphaCoverage,
Degradation::UnmeasuredFetchBlend,
Degradation::UnorderedFetchWithinDraw,
Degradation::NativeLogicOperation,
Degradation::NativeFloat8,
@@ -391,7 +388,6 @@ impl Degradation {
"metal2vulkan-degrade-coverage-reads-rounded-alpha"
}
Degradation::DeviceAlphaCoverage => "metal2vulkan-degrade-device-alpha-coverage",
Degradation::UnmeasuredFetchBlend => "metal2vulkan-degrade-unmeasured-fetch-blend",
Degradation::UnorderedFetchWithinDraw => {
"metal2vulkan-degrade-unordered-fetch-within-draw"
}
@@ -483,7 +479,6 @@ impl Degradation {
PrecisionNote::DeviceSampleLevel => Degradation::DeviceSampleLevel,
PrecisionNote::CoverageReadsRoundedAlpha => Degradation::CoverageReadsRoundedAlpha,
PrecisionNote::DeviceAlphaCoverage => Degradation::DeviceAlphaCoverage,
PrecisionNote::UnmeasuredFetchBlend => Degradation::UnmeasuredFetchBlend,
PrecisionNote::UnorderedFetchWithinDraw => Degradation::UnorderedFetchWithinDraw,
PrecisionNote::NativeLogicOperation => Degradation::NativeLogicOperation,
PrecisionNote::NativeFloat8 => Degradation::NativeFloat8,
+14 -5
View File
@@ -2966,9 +2966,8 @@ or does not check is rebuilt from the generations' names, with young counted ful
count bits), vertex amplification, a post-tessellation vertex function's per-instance factor
step function or enabled factor scale (`Tessellation`;
a descriptor's tessellation state with any other vertex function is ignored, as Metal ignores it),
stages the translator synthesizes beside the functions' and a tessellation's, an imageblock, a
fragment function's stencil output applied by the function itself (`ShaderStencil`, a form the
translator does not choose under the identity domains), a specialization other than the sample and
stages the translator synthesizes beside the functions' and a tessellation's, a specialization
other than the sample and
amplification counts, dynamic state beyond Vulkan 1.3's (a vertex buffer layout whose stride is
set per bind among it), a feature or extension device creation does not enable, and a function
that reads what a draw does not supply (`DrawInput`: a function table, a table the binder builds,
@@ -2976,9 +2975,19 @@ or does not check is rebuilt from the generations' names, with young counted ful
an unnormalized constexpr sampler). Of the replay streams' contents that translate, every one
reads only its slots' addresses, resource IDs and constexpr sampler indices. The
`completionHandler:` forms are not built.
- A fragment function with imageblock data, an input or an output declared `[[imageblock_data]]`,
is refused at creation on every device, an `Error::Translation` naming `Imageblocks`
(`NotImplemented`): the translator has no form for it. The runtime has refused such a function on
every device all along, worded otherwise before: the only form the translator had bound a storage
image through a descriptor, which the identity domains the runtime compiles under hold none of.
The states-only plays of the 35 replay streams on lavapipe refuse none of their render or compute
states (jobs m3-max-63105 to 63108, and m3-max-63132 and m3-max-63156 for the two streams that
ran past those jobs' 300-second limit).
- On a device that does not list `VK_EXT_shader_stencil_export`, a fragment function's `[[stencil]]`
output is refused at creation, an `Error::Translation` naming `StencilExport`: under the identity
domains the pixel interlock chooses no other form. Metal's feature set tables give stencil
output is refused at creation, an `Error::Translation` naming `StencilExport`: the translator has
no other form. The runtime has refused it on such a device all along, worded otherwise before:
the translator's other form bound a storage image through a descriptor, which the identity
domains hold none of. Metal's feature set tables give stencil
feedback to the Apple5 family and later and to Metal 3 and Metal 4. NVIDIA's 615 and 620 drivers
on the RTX 2080, RTX 3090 and RTX 5080 Laptop list none (`vulkaninfo`, jobs m3-max-48727, 48729
and 48731); RADV on the RX 7900 XTX, the 780Ms and the RX 550, ANV on the Iris Xe, lavapipe,
-4
View File
@@ -1410,10 +1410,6 @@ pub enum RenderPipelineKind {
/// Stages the translator synthesizes beside the functions' but a tessellation's: lines drawn as
/// bands of triangles.
SynthesizedStages,
/// A fragment function that reaches the render pass's imageblock.
Imageblock,
/// A fragment function's stencil output applied by the shader.
ShaderStencil,
/// A specialization the draw would set, beside the sample and amplification counts.
Specialization,
/// Dynamic state the translator asks for beyond what Vulkan 1.3 leaves dynamic.
@@ -531,8 +531,6 @@ fn draws(
// the `SpecKey::SampleCount` constant, which the state's creation sets to its
// `rasterSampleCount`, the count of every pass it draws in (`renders_into`).
RuntimeFact::SampleCount => {}
// A colour moved into a storage form, which the runtime never moves.
RuntimeFact::MovableStorageWrites { .. } => {}
// The pulled attributes and their layouts' strides of a post-tessellation function and
// of a state made for indirect command buffers, which pulls every attribute: the
// content's own descriptor, whose projection link checked. A stride set per bind is
@@ -815,10 +813,6 @@ fn unbuilt(pipeline: &RenderPipeline, enabled: &EnabledCaps) -> Option<RenderPip
RenderPipelineKind::Tessellation
} else if synthesized {
RenderPipelineKind::SynthesizedStages
} else if g.fragment_imageblock.is_some() {
RenderPipelineKind::Imageblock
} else if g.shadow_stencil.is_some() {
RenderPipelineKind::ShaderStencil
} else if !(g.dynamic_states.iter()).all(|state| DYNAMIC.contains(&dynamic(*state))) {
RenderPipelineKind::DynamicState
} else if unenabled {
@@ -30,8 +30,6 @@ use Verdict::{Applied, Fact, Refused};
/// The draw's set-0 bindings, which `draws` refuses (`of_the_device`).
const SET_0: &str = "a set-0 binding, which draws() refuses";
/// What the runtime never asks the translator for.
const VARIANT: &str = "stated only under a VariantKey the runtime never asks for";
const GRAPHICS_STATE: &[(&str, Verdict)] = &[
(
@@ -63,7 +61,6 @@ const GRAPHICS_STATE: &[(&str, Verdict)] = &[
Fact("it matters only to multiview, which refuse() refuses"),
),
("tessellation", Applied),
("fragment_imageblock", Applied),
(
"vertex_writes_memory",
Fact("the runtime records each draw once, in no rate-mapped pass"),
@@ -75,8 +72,6 @@ const GRAPHICS_STATE: &[(&str, Verdict)] = &[
module stores no ViewportIndex",
),
),
("storage_attachments", Refused(SET_0)),
("shadow_stencil", Applied),
("line_band", Applied),
("writes_point_size", Applied),
(
@@ -100,7 +95,6 @@ const GRAPHICS_STATE: &[(&str, Verdict)] = &[
Fact("the runtime takes every attachment of a draw's pass as written"),
),
("sample_mask", Applied),
("snapshot_reads", Refused(VARIANT)),
("logic_op", Applied),
];
@@ -152,8 +146,6 @@ const STAGE_MODULE: &[(&str, Verdict)] = &[
Fact("the runtime announces every note of precision_notes, these among them"),
),
("own_pixel_textures", Applied),
("snapshot_textures", Refused(VARIANT)),
("snapshot_refusals", Refused(VARIANT)),
(
"level_reads",
Fact("the runtime takes a read of a texture as one of its whole bound view"),
@@ -3,11 +3,9 @@
//! Vulkan copies a multisampled aspect to or from another image only through maintenance8's
//! depth-stencil/colour `vkCmdCopyImage`. These crate-owned modules move
//! each sample another way. The source is read one sample per invocation, through a sampled view
//! of its copied aspect ([`CopySource::Aspect`]: a multisampled 2D image, unsigned for stencil,
//! float for depth) or as the shader-side stencil's shadow ([`CopySource::Shadow`]: a
//! multisampled `R8_UINT` storage image). The destination is written by a draw into it as the
//! depth/stencil attachment, at sample rate ([`depth_stencil_copy_modules`]), or by a kernel into
//! a storage image ([`stencil_split_module`]):
//! of its copied aspect (a multisampled 2D image, unsigned for stencil, float for depth). The
//! destination is written by a draw into it as the depth/stencil attachment, at sample rate
//! ([`depth_stencil_copy_modules`]):
//!
//! - **A draw** ([`DepthStencilCopyModules`]): a `Vertex` entry `main` that draws one triangle
//! over the whole viewport from `VertexIndex` 0 to 2 (no vertex input), and a `Fragment` entry
@@ -48,16 +46,9 @@
//! The fragment stage reads `SampleId`, so it runs once per sample (`sampleRateShading`): the
//! consumer enables sample shading with `minSampleShading` 1, and each invocation writes its own
//! sample. A pixel's `FragCoord` is its center, `(x + 0.5, y + 0.5)`, truncated to `(x, y)`.
//! - **The stencil split** ([`StencilSplitModule`]): a `GLCompute` entry `main` with local size
//! ([`StencilSplitModule::LOCAL_SIZE`], [`StencilSplitModule::LOCAL_SIZE`], 1) whose invocation
//! `(x, y, s)` inside the destination fetches sample `s` of pixel `(x, y)` of the unsigned source
//! aspect at [`StencilSplitModule::SOURCE_BINDING`] and writes it to sample `s` of texel `(x, y)`
//! of the multisampled `R8_UINT` storage image at [`StencilSplitModule::DESTINATION_BINDING`]:
//! the shadow's copy in. Dispatch `ceil(width / LOCAL_SIZE)`, `ceil(height / LOCAL_SIZE)`,
//! `samples` workgroups over a destination of the copied area.
//!
//! **Synchronization** (consumer): the source's writes before the copy's reads, and the
//! destination's earlier accesses before its attachment or storage writes; the copy's writes
//! destination's earlier accesses before its attachment writes; the copy's writes
//! before whatever reads the destination next.
use std::sync::Arc;
@@ -72,20 +63,10 @@ use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{TypeId, Value};
use crate::spirv::ir::{
BinOp, ConstBits, Constant, ConvOp, Dim, ExecMode, ExecModel, ImageOperands, ImageQuery,
ImageType, ImageUsage, IoDir, MemAccess, StorageClass, TexelMemory, Type, TypedModule,
BinOp, ConstBits, Constant, ConvOp, Dim, ExecMode, ExecModel, ImageOperands, ImageType,
ImageUsage, IoDir, MemAccess, StorageClass, Type, TypedModule,
};
/// Where a copy reads its source (the module docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CopySource {
/// A sampled view of the source's copied aspect: a multisampled 2D image, unsigned for a
/// stencil aspect and float for a depth aspect.
Aspect,
/// The shader-side stencil's shadow: a multisampled `R8_UINT` storage image.
Shadow,
}
/// One bit of an 8-bit stencil: the plane a [`DepthStencilCopy::StencilPlane`] draw writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StencilBit(u8);
@@ -114,9 +95,9 @@ impl StencilBit {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DepthStencilCopy {
/// One bit plane of the stencil: the invocation is killed where its bit is clear.
StencilPlane { source: CopySource, bit: StencilBit },
StencilPlane { bit: StencilBit },
/// The stencil, as `FragStencilRefEXT` (`VK_EXT_shader_stencil_export`).
StencilExport { source: CopySource },
StencilExport,
/// The depth, as `FragDepth`, from a sampled view of a depth aspect.
Depth,
/// The depth's bits, its `f32` bit-cast, as the first component of the unsigned colour output
@@ -144,61 +125,24 @@ pub struct DepthStencilCopyModules {
/// The fragment stage: SPIR-V 1.5 words, entry point `main`, the source at
/// [`DepthStencilCopyModules::SOURCE_BINDING`] of set [`DepthStencilCopyModules::SET`].
pub fragment: Arc<[u32]>,
/// What the two stages need from the device: `sampleRateShading`; for the shadow,
/// multisampled storage images of an extended format; for the export, the extension.
/// What the two stages need from the device: `sampleRateShading`; for the export, the
/// extension.
pub requirements: Requirements,
}
impl DepthStencilCopyModules {
/// Descriptor set of the binding.
pub const SET: u32 = 0;
/// The source: a sampled image ([`CopySource::Aspect`]) or a storage image
/// ([`CopySource::Shadow`]).
/// The source, a sampled image.
pub const SOURCE_BINDING: u32 = 0;
}
/// The crate-owned stencil split of one device, validated like any output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StencilSplitModule {
/// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0.
pub spirv: Arc<[u32]>,
/// What the module needs from the device: multisampled storage images
/// (`shaderStorageImageMultisample`) of an extended format
/// (`shaderStorageImageExtendedFormats`).
pub requirements: Requirements,
}
impl StencilSplitModule {
/// Descriptor set of every binding.
pub const SET: u32 = 0;
/// The source, a sampled image of the stencil aspect.
pub const SOURCE_BINDING: u32 = 0;
/// The destination, a multisampled `R8_UINT` storage image.
pub const DESTINATION_BINDING: u32 = 1;
/// Invocations of one workgroup along x, and along y.
pub const LOCAL_SIZE: u32 = 8;
}
/// The binding symbol of a draw's source ([`DepthStencilCopyModules::SOURCE_BINDING`]).
const DRAW_SOURCE: ResourceSlot = ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::Texture,
index: 0,
};
/// The binding symbol of the split's source ([`StencilSplitModule::SOURCE_BINDING`]).
const SPLIT_SOURCE: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Texture,
index: 0,
};
/// The binding symbol of the split's destination ([`StencilSplitModule::DESTINATION_BINDING`]).
const SPLIT_DESTINATION: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Texture,
index: 1,
};
/// The unsigned 32-bit scalar type.
pub(super) fn u32_ty(b: &mut ModuleBuilder) -> BResult<TypeId> {
b.ty(Type::Int {
@@ -255,38 +199,21 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
let f32_ = b.ty(Type::Float { width: 32 })?;
let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?;
let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?;
let source = match copy {
DepthStencilCopy::StencilPlane { source, .. }
| DepthStencilCopy::StencilExport { source } => source,
DepthStencilCopy::Depth
| DepthStencilCopy::DepthBits
let texel_type = match copy {
DepthStencilCopy::Depth | DepthStencilCopy::DepthBits | DepthStencilCopy::Depth16Bits => {
f32_
}
DepthStencilCopy::StencilPlane { .. }
| DepthStencilCopy::StencilExport
| DepthStencilCopy::StencilBits
| DepthStencilCopy::Depth16Code
| DepthStencilCopy::Depth16Bits => CopySource::Aspect,
};
let source_ty = match (copy, source) {
(
DepthStencilCopy::Depth | DepthStencilCopy::DepthBits | DepthStencilCopy::Depth16Bits,
_,
) => multisampled_image(
&mut b,
f32_,
ImageUsage::Sampled,
crate::spv::ImageFormat::Unknown,
)?,
(_, CopySource::Aspect) => multisampled_image(
&mut b,
u32_,
ImageUsage::Sampled,
crate::spv::ImageFormat::Unknown,
)?,
(_, CopySource::Shadow) => multisampled_image(
&mut b,
u32_,
ImageUsage::Storage,
crate::spv::ImageFormat::R8ui,
)?,
| DepthStencilCopy::Depth16Code => u32_,
};
let source_ty = multisampled_image(
&mut b,
texel_type,
ImageUsage::Sampled,
crate::spv::ImageFormat::Unknown,
)?;
let image = b.resource(DRAW_SOURCE, StorageClass::UniformConstant, source_ty)?;
let coord = b.builtin(crate::spv::BuiltIn::FragCoord, IoDir::Input, vec4)?;
let sample = b.builtin(crate::spv::BuiltIn::SampleId, IoDir::Input, i32_)?;
@@ -307,13 +234,10 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
sample: Some(sample),
..ImageOperands::default()
};
let texel = match source {
CopySource::Aspect => f.fetch(image, pixel, &ops)?,
CopySource::Shadow => f.read(image, pixel, &ops, TexelMemory::default())?,
};
let texel = f.fetch(image, pixel, &ops)?;
let value = f.composite_extract(texel, &[0])?;
match copy {
DepthStencilCopy::StencilPlane { bit, .. } => {
DepthStencilCopy::StencilPlane { bit } => {
let mask = uint(&mut f, bit.mask())?;
let set = f.binary(BinOp::BitwiseAnd, value, mask)?;
let zero = uint(&mut f, 0)?;
@@ -325,7 +249,7 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
});
f.if_(&mut (), clear, kill, None)?;
}
DepthStencilCopy::StencilExport { .. } => {
DepthStencilCopy::StencilExport => {
let reference = f.convert(ConvOp::Bitcast, value, i32_)?;
let output =
f.module()
@@ -382,7 +306,7 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
let mut modes = vec![ExecMode::OriginUpperLeft];
match copy {
DepthStencilCopy::StencilPlane { .. } => {}
DepthStencilCopy::StencilExport { .. } => modes.push(ExecMode::StencilRefReplacing),
DepthStencilCopy::StencilExport => modes.push(ExecMode::StencilRefReplacing),
DepthStencilCopy::Depth | DepthStencilCopy::Depth16Code => {
modes.push(ExecMode::DepthReplacing)
}
@@ -394,96 +318,11 @@ pub fn fragment_typed_module(copy: DepthStencilCopy) -> BResult<TypedModule> {
b.finalize()
}
/// The stencil split as a typed module, before serialization: the module
/// [`stencil_split_module`] serializes. Its bindings are the symbols [`SPLIT_SOURCE`] and
/// [`SPLIT_DESTINATION`].
pub fn split_typed_module() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let u32_ = u32_ty(&mut b)?;
let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let source_ty = multisampled_image(
&mut b,
u32_,
ImageUsage::Sampled,
crate::spv::ImageFormat::Unknown,
)?;
let destination_ty = multisampled_image(
&mut b,
u32_,
ImageUsage::Storage,
crate::spv::ImageFormat::R8ui,
)?;
let source = b.resource(SPLIT_SOURCE, StorageClass::UniformConstant, source_ty)?;
let destination = b.resource(
SPLIT_DESTINATION,
StorageClass::UniformConstant,
destination_ty,
)?;
let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let invocation = f.module().global_value(invocation)?;
let invocation = f.load(invocation, MemAccess::default())?;
let destination = f.module().global_value(destination)?;
let destination = f.load(destination, MemAccess::default())?;
let size = f.query(ImageQuery::Size, destination)?;
let samples = f.query(ImageQuery::Samples, destination)?;
let mut inside = None;
for axis in 0..3 {
let at = f.composite_extract(invocation, &[axis])?;
let end = if axis < 2 {
f.composite_extract(size, &[axis])?
} else {
samples
};
let below = f.binary(BinOp::ULessThan, at, end)?;
inside = Some(match inside {
None => below,
Some(all) => f.binary(BinOp::LogicalAnd, all, below)?,
});
}
let inside = inside.ok_or(crate::spirv::error::BuildError::IdSpaceExhausted)?;
let source = f.module().global_value(source)?;
// Invocation `(x, y, s)` inside the destination copies sample `s` of pixel `(x, y)`.
let copy_sample: ArmFn<'_, ()> = Box::new(move |f, _| {
let source = f.load(source, MemAccess::default())?;
let x = f.composite_extract(invocation, &[0])?;
let y = f.composite_extract(invocation, &[1])?;
let s = f.composite_extract(invocation, &[2])?;
let pixel = f.composite_construct(uvec2, &[x, y])?;
let ops = ImageOperands {
sample: Some(s),
..ImageOperands::default()
};
let texel = f.fetch(source, pixel, &ops)?;
f.write(destination, pixel, texel, &ops, TexelMemory::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, copy_sample, None)?;
f.ret(None)?;
let id = f.finish()?;
b.entry(
ExecModel::GLCompute,
id,
vec![ExecMode::LocalSize {
x: StencilSplitModule::LOCAL_SIZE,
y: StencilSplitModule::LOCAL_SIZE,
z: 1,
}],
)?;
b.finalize()
}
/// The fixed binding numbers of the modules' symbols.
fn binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(0),
Symbol::Binding(s) if *s == DRAW_SOURCE => Some(DepthStencilCopyModules::SOURCE_BINDING),
Symbol::Binding(s) if *s == SPLIT_SOURCE => Some(StencilSplitModule::SOURCE_BINDING),
Symbol::Binding(s) if *s == SPLIT_DESTINATION => {
Some(StencilSplitModule::DESTINATION_BINDING)
}
_ => None,
}
}
@@ -516,7 +355,7 @@ pub(super) fn finish(
}
/// The modules of the copy draw `copy` on `device`: built with the typed builder (the vertex
/// stage is the sample planes merge's, `bind::sample_planes`), checked by the owned verifier
/// stage is the interleave merge's, `bind::sample_interleave`), checked by the owned verifier
/// against the device's profile (requirements included), serialized, and numbered with the fixed
/// binding of [`DepthStencilCopyModules`]. Refused, `Unsupported` naming `feature` (what the
/// consumer copies for) and what the device lacks, where it lacks what the draw needs.
@@ -527,7 +366,7 @@ pub fn depth_stencil_copy_modules(
) -> Result<DepthStencilCopyModules, Error> {
let (vertex, vertex_needs) = finish(
device,
super::sample_planes::merge_vertex_typed_module()?,
super::sample_interleave::merge_vertex_typed_module()?,
&feature,
"depth/stencil copy's vertex stage",
)?;
@@ -547,18 +386,5 @@ pub fn depth_stencil_copy_modules(
})
}
/// The stencil split on `device`, built and checked as [`depth_stencil_copy_modules`] is;
/// refused likewise where the device lacks multisampled storage images of `R8_UINT`.
pub fn stencil_split_module(
device: &Device,
feature: Feature,
) -> Result<StencilSplitModule, Error> {
let (spirv, requirements) = finish(device, split_typed_module()?, &feature, "stencil split")?;
Ok(StencilSplitModule {
spirv,
requirements,
})
}
#[cfg(test)]
mod tests;
@@ -7,17 +7,15 @@ use crate::device::{DeviceDescription, DevicePolicy};
use crate::spirv::testing::assert_valid;
use std::path::PathBuf;
/// Every copy draw: each plane of each source, the export of each source, the depth, the
/// Every copy draw: each plane, the export, the depth, the
/// depth's and the stencil's bits into colour, a depth's magnitude as a depth and as bits, and a
/// 16-bit depth's code both ways.
fn every_copy() -> Vec<DepthStencilCopy> {
let mut copies = Vec::new();
for source in [CopySource::Aspect, CopySource::Shadow] {
for bit in StencilBit::ALL {
copies.push(DepthStencilCopy::StencilPlane { source, bit });
}
copies.push(DepthStencilCopy::StencilExport { source });
for bit in StencilBit::ALL {
copies.push(DepthStencilCopy::StencilPlane { bit });
}
copies.push(DepthStencilCopy::StencilExport);
copies.push(DepthStencilCopy::Depth);
copies.push(DepthStencilCopy::DepthBits);
copies.push(DepthStencilCopy::StencilBits);
@@ -41,8 +39,7 @@ fn each_bit_masks_its_plane() {
}
/// Each module needs exactly what the module docs say: every fragment stage `sampleRateShading`,
/// a read of the shadow multisampled storage images, the export the extension, the split
/// multisampled storage images of an extended format and no sample-rate shading.
/// the export the extension, and none multisampled storage images.
#[test]
fn each_module_needs_what_its_docs_say() {
for copy in every_copy() {
@@ -51,36 +48,18 @@ fn each_module_needs_what_its_docs_say() {
r.features.contains(&VkFeature::SampleRateShading),
"{copy:?}: {r:?}"
);
let export = matches!(copy, DepthStencilCopy::StencilExport { .. });
let export = matches!(copy, DepthStencilCopy::StencilExport);
assert_eq!(
r.extensions.contains(&VkExtension::ExtShaderStencilExport),
export,
"{copy:?}: {r:?}"
);
let shadow = matches!(
copy,
DepthStencilCopy::StencilPlane {
source: CopySource::Shadow,
..
} | DepthStencilCopy::StencilExport {
source: CopySource::Shadow
}
);
assert_eq!(
r.features
assert!(
!r.features
.contains(&VkFeature::ShaderStorageImageMultisample),
shadow,
"{copy:?}: {r:?}"
);
}
let r = needs(split_typed_module().expect("split"));
for feature in [
VkFeature::ShaderStorageImageMultisample,
VkFeature::ShaderStorageImageExtendedFormats,
] {
assert!(r.features.contains(&feature), "{feature:?}: {r:?}");
}
assert!(!r.features.contains(&VkFeature::SampleRateShading), "{r:?}");
}
/// Every committed device (`validation/profiles/*.json`), derived with the resident-table domains,
@@ -112,7 +91,7 @@ fn committed_devices() -> Vec<(String, Device)> {
#[test]
fn the_modules_are_valid_where_the_device_has_what_they_need() {
let feature = Feature::SeparateMultisampledDepthStencil;
let (mut draws, mut splits) = (0, 0);
let mut draws = 0;
for (name, device) in committed_devices() {
let profile = device.profile();
let fits = |m: TypedModule| profile.check(&needs(m)).is_ok();
@@ -132,22 +111,8 @@ fn the_modules_are_valid_where_the_device_has_what_they_need() {
Err(other) => panic!("{name} {copy:?}: {other}"),
}
}
let fit = fits(split_typed_module().expect("split"));
match stencil_split_module(&device, feature.clone()) {
Ok(module) => {
assert!(fit, "{name}");
assert_valid(split_typed_module().expect("split"), profile);
assert!(!module.spirv.is_empty());
splits += 1;
}
Err(Error::Unsupported(u)) => {
assert!(!fit, "{name}");
assert_eq!(u.feature, feature, "{name}");
}
Err(other) => panic!("{name}: {other}"),
}
}
assert!(draws > 0 && splits > 0, "{draws} {splits}");
assert!(draws > 0);
}
/// The 16-bit depth pair's arithmetic is exact for **every** code: of all 65536 codes, each one
+12 -407
View File
@@ -10,12 +10,7 @@
//! stage's handle table and the set-1 heap arrays through the heap planner (`bind::heap`): the
//! heap's members are shared by both stages, and each stage's table enters the members that reach
//! it (a used texture's render stages, a bound texture's own stage). A fragment function's
//! imageblock storage binding is `WriteSource::Imageblock`; the pass's imageblock is one plane of
//! cells, so a pass of more than one layer or an amplified draw is not implemented. An attachment
//! the fragment function reads in the interlocked storage form
//! (`GraphicsState::storage_attachments`) is `WriteSource::TileAttachment` in the attachment's
//! own format, likewise one 2D view, so such a pass or draw is not implemented either. A fragment
//! function's threadgroup arguments (`RuntimeFact::TileThreadgroupMemory`) are the pass's tile
//! threadgroup arguments (`RuntimeFact::TileThreadgroupMemory`) are the pass's tile
//! memory, `WriteSource::TileMemory` as a tile function's (`plan::compute`): the shape's
//! `tile_threadgroup` places each argument, and its `render_area` and `imageblock_size` (the
//! pass's tile) the tiles; a layered pass or an amplified draw is not implemented.
@@ -93,29 +88,6 @@
//! has no attachment for (`BindShape::dropped_colors`), whose writes plain Metal drops: the
//! variant whose fragment function keeps no output there (`VariantKey::dropped_colors`). A mesh
//! pipeline's is not implemented.
//! - **Interlocked colors**. A draw into a render pass instance that leaves color attachments out
//! of its subpass for other draws' interlocked storage form (`BindShape::interlocked_colors`)
//! runs the variant whose fragment function writes those it writes through that form too
//! (`VariantKey::interlocked_colors`), so the draw records in the instance. That variant stores
//! them before the depth and stencil tests (tested storage writes, below): the plan of the
//! pipeline as compiled selects such a moved writer's tests from
//! `RuntimeFact::MovableStorageWrites`. A mesh pipeline's is not implemented, nor a
//! multisampled, layered or amplified draw's.
//! - **Snapshot reads**. A draw the consumer reads a texture of its own subpass for through a
//! snapshot (`BindShape::snapshot_textures`) runs the variant whose fragment function reads it so
//! (`VariantKey::snapshot_textures`, `lower::fragment`'s `snapshot`), for each slot of the
//! fragment stage's `StageInterface::snapshot_textures`, where the pipeline's two draws are
//! Metal's one: a device with `fragmentShaderPixelInterlock`, `fragmentStoresAndAtomics`,
//! `attachmentFeedbackLoopLayout` and `extendedDynamicState3ColorWriteMask` (the variant's
//! pipeline requires the last two: its feedback loop flag and dynamic write masks), one
//! sample, no depth or stencil attachment, no rasterizer discard, no memory the vertex or
//! fragment function writes, no attachment in the storage form or input attachment, no
//! imageblock, tile memory, shader-side stencil or tests, no interlocked or shadowed colors, no
//! tessellation or mesh stages, and no amplified or layered draw. Every other
//! slot the shape names is left out, and the plan's `variant.snapshot_textures` says which it
//! kept. Its plan binds each slot's snapshot (`WriteSource::SnapshotTexels`) and leaves which of
//! the two draws runs to the consumer (`PushHole::SnapshotPhase`, zero in the plan's bytes);
//! `GraphicsState::snapshot_reads` states the consumer's part.
//! - **Depth clamp range**. A draw in depth clamp mode through a range above 0 whose Vulkan depth
//! clamp holds 0 (`BindShape::depth_clamp_range`) runs the variant whose fragment function, where
//! it writes its depth, clamps that depth to the draw's range itself
@@ -125,25 +97,6 @@
//! (`BindShape::rotated_weights`) of a pipeline whose fragment function reads
//! `[[barycentric_coord]]` runs the variant that takes Metal's weights back from the drawn
//! triangle's (`VariantKey::rotated_weights`, `LoweringInputs::rotated_weights`).
//! - **Tested storage writes**. A fragment function that stores a color through the interlocked
//! storage form and declares no early tests only because it discards
//! (`RuntimeFact::TestedStorageWrites`), in a pipeline with a depth or stencil attachment, stores
//! before Vulkan's tests where Metal stores after its own: a draw whose tests drop no fragment
//! (`BindShape::fragment_tests`, `FragmentTests::Pass`) runs it as compiled; one whose tests may
//! drop fragments but write neither attachment and count nothing (`Drop`) runs the variant whose
//! function declares early tests (`VariantKey::read_only_tests`); any other is
//! `NotImplemented(FramebufferFetch)`. A function that also writes other memory, or returns
//! depth, stencil, or a sample mask, states the fact without that variant (`early_variant`): a
//! draw whose tests drop no fragment runs it as compiled, and any other is
//! `NotImplemented(FramebufferFetch)` at the depth attachment (the stencil one where the pipeline
//! has no depth attachment). A draw that moves a color the function writes as an ordinary output
//! into the storage form (interlocked colors, above) takes its tests alike from
//! `RuntimeFact::MovableStorageWrites`, which states the `early_variant` the moved writer's
//! variant states, where the pipeline as compiled states no `TestedStorageWrites`; a moved write
//! whose mask names none of the attachment's components stores nothing, and takes no tests. (A
//! draw whose depth test alone acts, `Depth`, is `NotImplemented(FramebufferFetch)` at the depth
//! attachment, unless it writes nothing and the early-tests variant serves it; one whose stencil
//! test acts and whose tests write, `Stencil`, is so at the stencil attachment.)
//! - **Draws.** A Metal draw maps to the Vulkan draw of the same arguments; an indirect draw is
//! GPU-side unless a stage reads `BaseVertexInstance` from push constants or the plan is
//! multiview, in which case `indirect_needs_arguments` asks for the CPU read.
@@ -268,26 +221,25 @@ use crate::bind::plan::resources::{separate_samplers, ResourcePlanner};
use crate::bind::plan::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, large_view_candidates,
mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted, snapshot_forms,
srgb_variant, storage_view_variant, texel_buffer_parts_variant, used_uses,
ycbcr_in_place_variant, ycbcr_planes_sampled_variant,
mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted, srgb_variant,
storage_view_variant, texel_buffer_parts_variant, used_uses, ycbcr_in_place_variant,
ycbcr_planes_sampled_variant,
};
use crate::bind::plan::{
AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorTemplate, FieldLocation,
GraphicsTemplate, GroupLimits, GroupStage, MeshTemplate, PlannedVertexBuffer,
PushFieldPlacement, PushTemplate, ResourceUse, ShadowTemplate, StageTemplate, StrideRules,
UseTarget, VertexBufferBind, ViewSetup, WriteSource,
PushFieldPlacement, PushTemplate, ResourceUse, StageTemplate, StrideRules, UseTarget,
VertexBufferBind, ViewSetup, WriteSource,
};
use crate::bind::resident::{stage_root_table, table_entries};
use crate::bind::state::{
offset_alignment, BindShape, BindState, BoundBuffer, BufferShape, FragmentTests,
VertexAmplification,
offset_alignment, BindShape, BindState, BoundBuffer, BufferShape, VertexAmplification,
};
use crate::cache::{SpecializationKey, VariantKey};
use crate::device::profile::portable_vertex_stride;
use crate::device::requirements::{VkFeature, VkLimit};
use crate::device::{vk_stage, Device};
use crate::error::{Attachment, BindError, Capability, Feature, LowerFamily, Unsupported};
use crate::error::{BindError, Capability, Feature, LowerFamily, Unsupported};
use crate::float16::{f16_bits_to_f32, f32_to_f16_bits};
use crate::lower::dispatch::region_bytes;
use crate::metal;
@@ -719,16 +671,6 @@ fn vertex_layer(p: &RenderPipeline) -> Option<bool> {
})
}
/// Whether a draw's write to the ordinary color attachment of state `a` stores something: its
/// mask names some of the format's color components (Vulkan writes nothing to a component the
/// mask leaves out, nor to one the format lacks), as the storage form's write stores something
/// where its mask covers some of the format's channels (`StorageView::stores_nothing`).
fn stores(a: crate::pipeline::graphics::ColorAttachmentState) -> bool {
a.format
.block()
.is_some_and(|b| a.write_mask.intersects(b.color_components))
}
fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<BindingPlan, BindError> {
check_slots(shape)?;
let tessellation = p.graphics.tessellation.is_some();
@@ -830,28 +772,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
}
_ => None,
});
// The fragment imageblock is one plane per render pass instance. What Metal gives each layer of
// a layered pass, or each view of an amplified draw, is not read yet: such a pass is not
// implemented.
if p.graphics.fragment_imageblock.is_some()
&& (shape.render_target_array_length > 1 || shape.vertex_amplification.count > 1)
{
return Err(not_implemented(Feature::Imageblocks));
}
// An attachment read in the interlocked storage form is one 2D view: what a layered pass, or an
// amplified draw, reads and writes of each layer or view is not modelled.
if !p.graphics.storage_attachments.is_empty()
&& (shape.render_target_array_length > 1 || shape.vertex_amplification.count > 1)
{
return Err(not_implemented(Feature::FramebufferFetch));
}
// The shader-side stencil's shadow is one 2D image: the same holds.
let shadow = shadow_template(p);
if shadow.is_some()
&& (shape.render_target_array_length > 1 || shape.vertex_amplification.count > 1)
{
return Err(not_implemented(Feature::StencilExport));
}
// A fragment function's tile threadgroup memory is the pass's, every tile's in one buffer:
// what Metal gives each layer of a layered pass, or each view of an amplified draw, is not
// read yet, as for a tile dispatch.
@@ -904,101 +824,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
_ => None,
})
.collect();
// The colors the draw's instance keeps out of its subpass that the fragment function writes
// through its first output: the variant that writes them through the interlocked storage
// form, as a fetching function does. A pipeline that writes them so is that variant. A mesh
// pipeline's is not built.
let interlocked_colors: std::collections::BTreeSet<u32> = shape
.interlocked_colors
.iter()
.copied()
.filter(|&c| {
1u32.checked_shl(c)
.is_some_and(|bit| p.graphics.color_outputs & bit != 0)
})
.collect();
if !interlocked_colors.is_empty() && mesh {
return Err(not_implemented(Feature::MeshShading));
}
// Nor a multisampled draw's, whose storage form reads and writes the attachment per sample,
// which runs the function per sample where a plain writer runs it per pixel; nor a layered
// pass's or an amplified draw's, whose storage form is one 2D view (above).
if !interlocked_colors.is_empty()
&& (p.graphics.rasterization_samples.as_raw() > 1
|| shape.render_target_array_length > 1
|| shape.vertex_amplification.count > 1)
{
return Err(not_implemented(Feature::FramebufferFetch));
}
let compiled_interlocked: std::collections::BTreeSet<u32> = p
.graphics
.storage_attachments
.iter()
.filter(|a| a.writes && shape.interlocked_colors.contains(&a.color_index))
.map(|a| a.color_index)
.collect();
// The fragment texture slots the draw reads through a snapshot: those the shape names that
// the fragment function can read so, where the pipeline's two draws are Metal's one. The two
// run the same fragments (the pipeline differs only in its dynamic write masks), the first
// with every mask 0 running none of the function past its copy, so the pipeline may hold
// nothing else either draw writes, tests, or orders: one sample, no depth or stencil, no
// memory either function writes, no attachment, imageblock, tile memory or stencil shadow of
// the storage form or an input attachment, and no other interlock. A tessellation
// or mesh pipeline's, and an amplified or layered draw's are not built.
// The device makes the variant's pipeline: its feedback loop flag and dynamic write masks
// need `attachmentFeedbackLoopLayout` and `extendedDynamicState3ColorWriteMask`.
// Every other slot the shape names is left out, and the consumer reads it as it would without
// a snapshot.
let enabled = &profile.fields().enabled.features;
let snapshot_able = crate::lower::fragment::interlock_forms(profile)
&& enabled.contains(&VkFeature::FragmentStoresAndAtomics)
&& enabled.contains(&VkFeature::AttachmentFeedbackLoopLayout)
&& enabled.contains(&VkFeature::ExtendedDynamicState3ColorWriteMask)
&& p.graphics.rasterization_samples.as_raw() <= 1
&& p.graphics.depth_format.is_none()
&& p.graphics.stencil_format.is_none()
&& !p.graphics.rasterizer_discard
&& !p.graphics.vertex_writes_memory
&& !p.graphics.fragment_writes_memory
&& p.graphics.storage_attachments.is_empty()
&& p.graphics.input_attachments.is_empty()
&& p.graphics.fragment_imageblock.is_none()
&& p.graphics.tessellation.is_none()
&& shadow.is_none()
&& tile_memory.is_none()
&& !mesh
&& interlocked_colors.is_empty()
&& shape.vertex_amplification.count <= 1
&& shape.render_target_array_length <= 1;
let snapshot_textures: std::collections::BTreeSet<SlotRef> = match snapshot_able {
true => p
.stages
.iter()
.filter(|m| m.stage == vk::ShaderStage::FRAGMENT)
.flat_map(|m| &m.snapshot_textures)
.filter(|index| shape.snapshot_textures.contains(index))
.map(|&index| SlotRef {
stage: Stage::Fragment,
class: SlotClass::Texture,
index,
})
.collect(),
false => std::collections::BTreeSet::new(),
};
let compiled_snapshots: std::collections::BTreeSet<SlotRef> = p
.layout
.sets
.iter()
.flat_map(|set| &set.bindings)
.filter_map(|b| match b.source {
BindingSource::SnapshotTexels(index) => Some(SlotRef {
stage: Stage::Fragment,
class: SlotClass::Texture,
index,
}),
_ => None,
})
.collect();
// A draw in depth clamp mode through a range above 0 whose Vulkan depth clamp holds 0: the
// variant whose fragment function clamps the depth it writes to the draw's range. A pipeline
// whose fragment function writes no depth has none to clamp.
@@ -1019,93 +844,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
// tessellation stages draw them so, which its graphics state states.
let line_band = shape.line_band;
let compiled_band = p.graphics.line_band.map(|b| b.primitive);
// A fragment function that stores a color through the interlocked storage form before the
// depth and stencil tests, since it discards (`RuntimeFact::TestedStorageWrites`), in a
// pipeline with a depth or stencil attachment: Metal's store, as compiled, where the draw's
// tests drop no fragment; where they drop some but write and count nothing, the variant whose
// function declares early tests, which a pipeline compiled under it states; refused
// otherwise. A draw that moves a color the function writes as an ordinary output into that
// form (an interlocked color) asks for the variant that stores
// it so: where the pipeline as compiled stores no color so, the function states that variant's
// tests (`RuntimeFact::MovableStorageWrites`), so this plan selects them, and the variant it
// names plans itself. A moved write whose mask names none of its attachment's components
// stores nothing, so no test bears on it: its variant states none, and this plan selects none
// for it. (A color the pipeline as compiled already writes through the storage form has no
// ordinary attachment state; its stores state their own tests.)
let moves = interlocked_colors.iter().any(|&c| {
1u32.checked_shl(c)
.is_some_and(|bit| p.graphics.color_outputs & bit != 0)
&& p.graphics
.color_attachments
.get(c as usize)
.copied()
.flatten()
.is_some_and(stores)
});
let tested = p
.dependencies
.iter()
.find_map(|d| match d.fact {
RuntimeFact::TestedStorageWrites {
early_tests,
early_variant,
} => Some((early_tests, early_variant)),
_ => None,
})
.or_else(|| {
let movable = p.dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::MovableStorageWrites { early_variant } => Some((false, early_variant)),
_ => None,
});
movable.filter(|_| moves)
});
let tested_attachments =
p.graphics.depth_format.is_some() || p.graphics.stencil_format.is_some();
// What stores before the tests: the storage form's colors, or else the imageblock.
let tested_feature = match p.graphics.fragment_imageblock {
Some(_) if p.graphics.storage_attachments.is_empty() => Feature::Imageblocks,
_ => Feature::FramebufferFetch,
};
// A draw whose tests drop some fragments but write and count nothing runs the early-tests
// variant where the function has one; a draw whose tests may drop a fragment and write, or
// count, is not implemented, as the function stores before Vulkan's tests. The refusal is
// placed at the tested attachment: the depth one where the pipeline has one, else the
// stencil.
let depth = p.graphics.depth_format.is_some();
let stencil = p.graphics.stencil_format.is_some();
let at = |attachment: Attachment| {
Err(BindError::Unsupported(
Unsupported::not_implemented(tested_feature.clone()).at_attachment(attachment),
))
};
let read_only_tests = match (tested, shape.fragment_tests) {
(Some((_, true)), FragmentTests::Drop | FragmentTests::Depth { writes: false })
if tested_attachments =>
{
true
}
// A function that writes other memory or returns depth, stencil, or a sample mask: its
// stores are Metal's only where no test can drop a fragment.
(
Some((_, false)),
FragmentTests::Drop
| FragmentTests::Depth { .. }
| FragmentTests::Any
| FragmentTests::Stencil,
) if tested_attachments => {
return at(match depth {
true => Attachment::Depth,
false => Attachment::Stencil,
});
}
(Some(_), FragmentTests::Depth { .. }) if depth => return at(Attachment::Depth),
(Some(_), FragmentTests::Stencil) if stencil => return at(Attachment::Stencil),
(Some(_), FragmentTests::Any | FragmentTests::Stencil) if tested_attachments => {
return Err(not_implemented(tested_feature.clone()));
}
_ => false,
};
let compiled_tests = tested.is_some_and(|(early, _)| early);
// A mesh entry's `Layer` at or past `maxMeshOutputLayers` is undefined: a pass of more layers
// than that, which a mesh function choosing its slice could render into, is past the device.
let mesh_layers = limits.mesh.max_mesh_output_layers;
@@ -1201,7 +939,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
| PushField::ExecutionStatusAddress
| PushField::CaptureIndexAddress
| PushField::MergedDrawAddress
| PushField::SnapshotPhase
| PushField::ReplayRegionAddress
);
match field.field {
@@ -1219,8 +956,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
// The draw's vertices per primitive, which instantiation writes from its
// primitive type.
PushField::VerticesPerPrimitive if stage == Stage::Vertex => {}
// Which of a snapshot variant's draws runs: the consumer's hole.
PushField::SnapshotPhase if stage == Stage::Fragment => {}
PushField::SlotBindOffset(slot)
if planned(slot).is_some_and(|b| b.binding.is_some()) => {}
// The bound buffer's Metal address; a `set*Bytes` binding has none.
@@ -1266,8 +1001,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
// An in-place YCbCr texture's words, and a texture's rows in its texel buffer
// view, which instantiation reads from the state.
PushField::YCbCrInPlace(_) | PushField::TexelRows(_) => {}
// The encoder's stencil state, which instantiation reads from the state.
PushField::ShadowStencilState if stage == Stage::Fragment => {}
// The encoder's viewport count, which instantiation reads from the state, in the
// stage that chooses a viewport (a mesh function per primitive).
PushField::ViewportCount if matches!(stage, Stage::Vertex | Stage::Mesh) => {}
@@ -1286,8 +1019,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
PushField::AlphaTestReference if stage == Stage::Fragment => {}
// The encoder's blend color, which instantiation reads from the state.
PushField::HalfBlendColor if stage == Stage::Fragment => {}
// The storage form's kept channels, which instantiation reads from the template.
PushField::StorageKeptChannels if stage == Stage::Fragment => {}
// A draw of one amplification's id and offsets, which instantiation writes before
// each draw; the placement order puts them right after the addresses, so the window
// holds them.
@@ -1546,12 +1277,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
SyntheticBinding::FunctionTableSnapshot => {
planner(&mut heap)?.snapshot(stage, set.set, b.binding)?
}
// The pass's imageblock storage.
SyntheticBinding::Imageblock
if stage == Stage::Fragment && p.graphics.fragment_imageblock.is_some() =>
{
WriteSource::Imageblock
}
// The pass's tile threadgroup memory.
SyntheticBinding::TileMemory if stage == Stage::Fragment => {
match &tile_memory {
@@ -1563,21 +1288,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
}
}
}
// The stencil's shadow, or, in a pass without a stencil attachment, a neutral
// the function never reads (its state says nothing is attached), of the
// pipeline's samples as the function's declaration is.
SyntheticBinding::ShadowStencil if stage == Stage::Fragment => {
match &p.graphics.shadow_stencil {
Some(_) => WriteSource::ShadowStencil,
None => WriteSource::Neutral(NeutralResource::Image {
view_type: vk::ImageViewType::TYPE_2D,
sampled_type: crate::pipeline::sym::SampledType::Uint,
depth_compare: false,
samples: p.graphics.rasterization_samples.as_raw().max(1),
storage_format: Some(crate::lower::fragment::SHADOW_FORMAT),
}),
}
}
// The command buffer's status, on a device that does not address buffers.
SyntheticBinding::ExecutionStatus => WriteSource::ExecutionStatus,
other => return Err(internal(format!("a render binding {other:?}"))),
@@ -1598,31 +1308,12 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
BindingSource::AccelerationStructure { slot, level } => {
WriteSource::AccelerationStructure { slot, level }
}
// An attachment the fragment function reads in the interlocked storage form, a
// storage view of the attachment, or of its sample planes, in its own format.
BindingSource::TileAttachment(color_index) => {
let a = p
.graphics
.storage_attachments
.iter()
.find(|a| a.color_index == color_index)
.ok_or_else(|| {
internal(format!(
"a storage binding of color attachment {color_index}, which the \
pipeline does not read in the storage form"
))
})?;
WriteSource::TileAttachment {
color_index,
format: a.format,
view: a.view,
view_alias: a.view_alias,
}
// A tile function's attachment, which no render pipeline binds.
BindingSource::TileAttachment(_) => {
return Err(internal("a tile attachment binding in a render pipeline"))
}
// A sparse texture's tile map.
BindingSource::TileMap(slot) => resources.tile_map(slot),
// A texture's snapshot, which the draw reads the texture through.
BindingSource::SnapshotTexels(slot) => WriteSource::SnapshotTexels { slot },
// A two-plane YCbCr texture's planes image, through the device's conversion.
BindingSource::YCbCrPlanes(slot) => resources.planes_image_write(slot)?,
};
@@ -1969,28 +1660,12 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
.iter()
.any(|d| d.fact == RuntimeFact::MergedDraws);
// The pipeline compiled under other zeroed or dropped colors (or none) is the other variant.
let other_colors = compiled_zeroed != zeroed_colors
|| compiled_dropped != dropped_colors
|| compiled_interlocked != interlocked_colors
|| compiled_snapshots != snapshot_textures;
let other_colors = compiled_zeroed != zeroed_colors || compiled_dropped != dropped_colors;
variant.zeroed_colors = zeroed_colors;
variant.dropped_colors = dropped_colors;
variant.interlocked_colors = interlocked_colors;
variant.snapshot_textures = snapshot_forms(
profile,
&snapshot_textures,
&p.interface.slots,
shape,
&variant.cross_class,
);
// A slot the draw reads through a snapshot reads the snapshot's image, never the rows.
variant
.texel_rows
.retain(|slot| !variant.snapshot_textures.contains_key(slot));
variant.depth_clamp_range = depth_clamp_range;
variant.rotated_weights = rotated_weights;
variant.line_band = line_band;
variant.read_only_tests = read_only_tests;
variant.primitive_id_indices = primitive_id_indices;
variant.quad_primitive_ids = quad_primitive_ids;
variant.private_list = private_list;
@@ -2025,7 +1700,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|| compiled_range != depth_clamp_range
|| compiled_rotated != rotated_weights
|| compiled_band != line_band
|| compiled_tests != read_only_tests
|| compiled_quads != quad_primitive_ids
|| compiled_list != private_list
|| compiled_regions != region_viewports,
@@ -2052,75 +1726,15 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
u64::from(limits.max_storage_buffer_range),
),
)?,
shadow_stencil: shadow,
mesh,
deindexed: primitive_id_indices,
private_list,
storage_kept: storage_kept(p)?,
line_band: p.graphics.line_band.map(|b| b.push_offset),
}),
views,
})
}
/// `PushField::StorageKeptChannels` of `p`: each storage-form color attachment's kept channels
/// (`StorageAttachmentUse::kept`, Vulkan's `R`, `G`, `B` and `A` bits) at bits `4c` to `4c + 3`
/// for color `c`.
fn storage_kept(p: &RenderPipeline) -> Result<u32, BindError> {
p.graphics
.storage_attachments
.iter()
.try_fold(0u32, |word, s| match s.color_index {
c @ 0..8 => Ok(word | ((s.kept.as_raw() & 0xF) << (4 * c))),
_ => Err(internal("a storage-form color attachment past the eighth")),
})
}
/// The shader-side stencil of `p`'s fragment function, when it has one.
fn shadow_template(p: &RenderPipeline) -> Option<ShadowTemplate> {
let has = p.interface.push.iter().any(|pl| {
pl.fields
.iter()
.any(|f| f.field == PushField::ShadowStencilState)
});
has.then(|| ShadowTemplate {
attached: p.graphics.shadow_stencil.is_some(),
depth_attachment: p.graphics.depth_format.is_some(),
})
}
/// The `PushField::ShadowStencilState` words of a draw under encoder state `state`: the front
/// face's, then the back face's (`lower::fragment::face_word`). A state whose stencil write could
/// depend on the depth test is refused as needing stencil export: the pass has a depth attachment,
/// the depth comparison is not `Always`, and a face's depth-failure operation differs from its pass
/// operation (the depth test runs after the function).
fn shadow_stencil_words(t: &ShadowTemplate, state: &BindState) -> Result<FieldBytes, BindError> {
let ds = &state.depth_stencil;
let faces = [&ds.front_face_stencil, &ds.back_face_stencil];
if t.attached
&& t.depth_attachment
&& ds.depth_compare_function != metal::CompareFunction::Always
&& faces
.iter()
.any(|f| f.depth_failure_operation != f.depth_stencil_pass_operation)
{
return Err(BindError::Unsupported(Unsupported::needs(
Feature::StencilExport,
Capability::Extension(crate::device::requirements::VkExtension::ExtShaderStencilExport),
)));
}
Ok(FieldBytes::words(faces.map(|f| {
crate::lower::fragment::face_word(
f.stencil_compare_function.as_raw(),
f.stencil_failure_operation.as_raw(),
f.depth_stencil_pass_operation.as_raw(),
f.read_mask,
f.write_mask,
t.attached,
)
})))
}
/// The 8-bit unorm code Metal's private alpha test compares the reference `reference` as
/// (`setAlphaTestReferenceValue:`, Apple SPI; `PushField::AlphaTestReference`, probes on an Apple
/// M3 Max): NaN is 0, the value is clamped to `[0, 1]`, and the code is the exact product with
@@ -3431,7 +3045,6 @@ fn instantiate(
| PushField::ExecutionStatusAddress
| PushField::CaptureIndexAddress
| PushField::MergedDrawAddress
| PushField::SnapshotPhase
| PushField::ReplayRegionAddress => {
let PushLoc::Push { offset } = f.loc else {
return Err(not_implemented(Feature::Lowering(LowerFamily::StageIo)));
@@ -3444,7 +3057,6 @@ fn instantiate(
PushField::ExecutionStatusAddress => {
PushHole::ExecutionStatusAddress { stages, offset }
}
PushField::SnapshotPhase => PushHole::SnapshotPhase { stages, offset },
PushField::MergedDrawAddress => {
PushHole::MergedDrawAddress { stages, offset }
}
@@ -3459,12 +3071,6 @@ fn instantiate(
Some(d) => FieldBytes::words(d.layout.iter().copied()),
None => return Err(internal("a draw layout without its de-indexed form")),
},
PushField::ShadowStencilState => {
let Some(shadow) = &t.shadow_stencil else {
return Err(internal("a stencil state without its shader-side stencil"));
};
shadow_stencil_words(shadow, state)?
}
PushField::DispatchRegion => match mesh.as_ref().and_then(|m| m.region(st.stage)) {
Some(region) => FieldBytes::of(&region),
None => return Err(internal("a dispatch region outside a mesh draw")),
@@ -3482,7 +3088,6 @@ fn instantiate(
.iter()
.flat_map(|v| v.to_le_bytes())
.collect(),
PushField::StorageKeptChannels => FieldBytes::of(&t.storage_kept.to_le_bytes()),
// The alpha test reference's code, Metal's 1 where the encoder never set it.
PushField::AlphaTestReference => FieldBytes::of(
&alpha_test_code(state.alpha_test_reference.unwrap_or(1.0)).to_le_bytes(),
@@ -599,11 +599,9 @@ fn instantiation_bounds_a_draw_by_its_index_buffer() {
tessellation: None,
indirect_first_instance_missing: false,
robust_index_fetch,
shadow_stencil: None,
mesh: None,
deindexed: None,
private_list: false,
storage_kept: 0,
line_band: None,
};
let state = BindState::default();
@@ -647,11 +645,9 @@ fn a_draw_of_no_index_binds_inside_the_buffer() {
tessellation: None,
indirect_first_instance_missing: false,
robust_index_fetch,
shadow_stencil: None,
mesh: None,
deindexed: None,
private_list: false,
storage_kept: 0,
line_band: None,
};
let state = BindState::default();
@@ -730,11 +726,9 @@ fn an_unbounded_indexed_indirect_draw_reads_its_arguments() {
tessellation: None,
indirect_first_instance_missing,
robust_index_fetch,
shadow_stencil: None,
mesh: None,
deindexed: None,
private_list: false,
storage_kept: 0,
line_band: None,
};
let state = BindState::default();
@@ -785,11 +779,9 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() {
tessellation: None,
indirect_first_instance_missing: false,
robust_index_fetch: false,
shadow_stencil: None,
mesh: None,
deindexed: None,
private_list: false,
storage_kept: 0,
line_band: None,
};
let state = |offsets: (u64, u64), stride| {
@@ -875,11 +867,9 @@ fn inline_vertex_bytes_bind_the_strides_a_dynamic_layout_reads() {
tessellation: None,
indirect_first_instance_missing: false,
robust_index_fetch: false,
shadow_stencil: None,
mesh: None,
deindexed: None,
private_list: false,
storage_kept: 0,
line_band: None,
};
let state = |attribute_stride| {
@@ -1463,7 +1453,6 @@ fn mesh_template(flat: bool, multiples: Vec<u32>) -> GraphicsTemplate {
tessellation: None,
indirect_first_instance_missing: false,
robust_index_fetch: true,
shadow_stencil: None,
mesh: Some(MeshTemplate {
spec: layout,
fixed: vec![(SpecKey::Presence(fragment_buffer), 1)],
@@ -1481,7 +1470,6 @@ fn mesh_template(flat: bool, multiples: Vec<u32>) -> GraphicsTemplate {
}),
deindexed: None,
private_list: false,
storage_kept: 0,
line_band: None,
}
}
@@ -101,14 +101,6 @@ pub enum PushHole {
stages: vk::ShaderStageFlags,
offset: u32,
},
/// Which draw of a snapshot variant (`VariantKey::snapshot_textures`,
/// `PushField::SnapshotPhase`) runs, as a `u32` at `offset` of the variant's fragment push
/// bytes: 1 in the draw that takes the snapshot (every color write mask 0), 0 in the draw that
/// reads it (the pipeline's masks).
SnapshotPhase {
stages: vk::ShaderStageFlags,
offset: u32,
},
}
/// A consumer-owned indirect-argument buffer and the byte offset of the arguments.
+6 -15
View File
@@ -36,13 +36,9 @@
//! through the binding [`WriteSource::ExecutionStatus`] names where it does not. An indirect
//! dispatch reads its group counts from Metal's buffer itself ([`IndirectArgs::Buffer`]).
//! A pass's visibility results are its queries' results copied to their
//! offsets, a `Boolean` one the device's own nonzero value where a sample passed. A pass whose
//! fetching draws
//! read a multisampled attachment's sample planes (`StorageAttachmentView::SamplePlanes`) splits
//! the attachment into them with [`planes_split_module`] and merges them back with
//! [`planes_merge_modules`], through the [`PlanesCopy`] view of its texel size. A multisampled
//! offsets, a `Boolean` one the device's own nonzero value where a sample passed. A multisampled
//! depth or stencil aspect moves between images without colour copies through the draws of
//! [`depth_stencil_copy_modules`] and the kernel of [`stencil_split_module`]. Compute commands
//! [`depth_stencil_copy_modules`]. Compute commands
//! a kernel encodes into an indirect command buffer replay on the device where it has device
//! addresses: the [`replay_preprocess`] of an execution ([`ReplayExecution`]) over registered
//! [`ReplayVariant`]s, recorded with [`replay_preprocess_module`], writes each command's arguments
@@ -97,7 +93,6 @@ pub(crate) mod rate_map;
pub(crate) mod replay;
pub(crate) mod resident;
pub(crate) mod sample_interleave;
pub(crate) mod sample_planes;
pub(crate) mod state;
pub(crate) mod status;
pub(crate) mod table;
@@ -119,8 +114,7 @@ pub use astc_decode::{AstcDecode, AstcTexels};
pub use chroma_decode::ChromaDecode;
pub use depth_clamp::clamped_depth;
pub use depth_stencil_copy::{
depth_stencil_copy_modules, stencil_split_module, CopySource, DepthStencilCopy,
DepthStencilCopyModules, StencilBit, StencilSplitModule,
depth_stencil_copy_modules, DepthStencilCopy, DepthStencilCopyModules, StencilBit,
};
pub use dispatch::{Dispatch, DispatchCommands, DispatchRegion, IndirectArgs};
pub use etc_decode::{EtcDecode, EtcTexels};
@@ -172,8 +166,8 @@ pub use replay::{
pub use state::{
ArgumentFunctionTable, ArgumentSampler, ArgumentSamplersShape, BindShape, BindState,
BoundAccelerationStructure, BoundBuffer, BoundSampler, BoundSamplerShape, BoundTexture,
BufferRanges, BufferShape, FragmentTests, FunctionTablesShape, HeapPlacement, ImageblockSize,
ResourceClass, SamplerDescriptor, SamplerShape, StageInRegion, StageShape, StageTable,
BufferRanges, BufferShape, FunctionTablesShape, HeapPlacement, ImageblockSize, ResourceClass,
SamplerDescriptor, SamplerShape, StageInRegion, StageShape, StageTable,
TessellationFactorBuffer, TessellationFactors, TextureFacts, TextureShape,
TileThreadgroupArgument, TileThreadgroupMemory, UsedClass, UsedResource, UsedShape,
VertexAmplification, ViewMapping,
@@ -183,10 +177,7 @@ pub use state::{
pub use pvrtc_decode::PvrtcDecode;
pub use sample_interleave::{
interleave_merge_modules, interleave_split_module, InterleaveMergeModules,
InterleaveSplitModule,
};
pub use sample_planes::{
planes_merge_modules, planes_split_module, PlanesCopy, PlanesMergeModules, PlanesSplitModule,
InterleaveSplitModule, PlanesCopy,
};
pub use status::{ExecutionStatus, ReplayFaults, StatusBits, StatusReport, StatusWord};
pub use table::{FunctionTableSnapshot, FunctionTableWords};
+12 -63
View File
@@ -14,7 +14,6 @@ use crate::bind::neutral::NeutralResource;
use crate::cache::{SpecializationKey, VariantKey};
use crate::metal::sampler::OpaqueBlackBorder;
use crate::pipeline::artifact::SpecConstant;
use crate::pipeline::graphics::StorageAttachmentView;
use crate::pipeline::interface::{AccessSet, BufferForm, PlacedField, Window};
use crate::pipeline::sym::{
@@ -207,10 +206,6 @@ pub struct GraphicsTemplate {
/// only without it): a direct indexed draw past its index buffer is drawn, not clamped.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) robust_index_fetch: bool,
/// A fragment function's shader-side stencil: its draws write the encoder's stencil state as
/// `PushField::ShadowStencilState`.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) shadow_stencil: Option<ShadowTemplate>,
/// A mesh render pipeline's mesh stage: its draws are mesh draws, each of its own
/// specialization.
#[cfg_attr(feature = "serde", serde(default))]
@@ -225,11 +220,6 @@ pub struct GraphicsTemplate {
/// draw call.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) private_list: bool,
/// `PushField::StorageKeptChannels`: each storage-form color attachment's kept channels
/// (`StorageAttachmentUse::kept`), bits `4c` to `4c + 3` for color `c`, which its draws
/// write.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) storage_kept: u32,
/// A band variant's (`GraphicsState::line_band`): the byte offset of its evaluation stage's
/// push range, where its draws push `BindState::line_band` (`PushField::LineBand`).
#[cfg_attr(feature = "serde", serde(default))]
@@ -291,17 +281,6 @@ pub(crate) enum GroupStage {
Mesh,
}
/// What a draw of a pipeline with a shader-side stencil instantiates.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct ShadowTemplate {
/// The pass has a stencil attachment, so the plan binds the shadow
/// (`GraphicsState::shadow_stencil`); otherwise a neutral stands in and nothing is tested.
pub attached: bool,
/// The pass has a depth attachment, whose test could decide the stencil write.
pub depth_attachment: bool,
}
/// What a patch draw of a tessellation pipeline instantiates: the control stage's push range, the
/// patch and control-point index buffers' descriptor ranges, and the factor buffer's range.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -668,41 +647,22 @@ pub enum WriteSource {
slot: SlotRef,
level: AccelerationStructureLevel,
},
/// The render pass's fragment imageblock storage (`GraphicsState::fragment_imageblock`): the
/// one storage image the consumer creates for the pass instance, in `GENERAL` layout, bound to
/// every draw of the pass, and to every tile dispatch whose function's explicit imageblock
/// stands alone, which stages its tile's cells from it and back.
/// The render pass's imageblock storage: the one storage image the consumer creates for the
/// pass instance, in `GENERAL` layout, bound to every tile dispatch whose function's explicit
/// imageblock stands alone, which stages its tile's cells from it and back.
Imageblock,
/// A render pass's color attachment `color_index` as a storage image: the view `view` names,
/// in `format`, with the identity component mapping, in `GENERAL` layout. For
/// [`StorageAttachmentView::Attachment`] that is a 2D view of the attachment's own image, of
/// the pass's layer and level; for [`StorageAttachmentView::SamplePlanes`] `{ layers }` a
/// 2D-array view of all `layers` layers of the attachment's sample planes, the single-sample
/// image the consumer keeps beside a multisampled attachment, never a 2D view.
///
/// - A tile dispatch's: the image's format is the tile pipeline descriptor's
/// (`TileRenderPipelineDescriptor::color_attachment_formats`), as Metal requires of the
/// pass, and its extent at least the render area (`BindState::render_area`). `format` is
/// the image's own for an integer format, and for a float format the unsigned-integer
/// format of the same channels and widths (`R16_UINT` for `R16_SFLOAT`), so the dispatch
/// moves the texels' bits: the consumer creates such an image with `MUTABLE_FORMAT` (and
/// `EXTENDED_USAGE` when its own format is not storage-capable).
/// `view` is always `Attachment`.
/// - A draw's whose fragment function reads the attachment in the interlocked storage form
/// (`GraphicsState::storage_attachments`): `format` and `view` are the pipeline's
/// [`StorageAttachmentUse`](crate::pipeline::StorageAttachmentUse)'s, and the image has
/// `STORAGE` usage and is no color attachment of the subpass.
/// A render pass's color attachment `color_index` as a storage image of a tile dispatch: a 2D
/// view of the attachment's own image, of the pass's layer and level, in `format`, with the
/// identity component mapping, in `GENERAL` layout. The image's format is the tile pipeline
/// descriptor's (`TileRenderPipelineDescriptor::color_attachment_formats`), as Metal requires
/// of the pass, and its extent at least the render area (`BindState::render_area`). `format`
/// is the image's own for an integer format, and for a float format the unsigned-integer
/// format of the same channels and widths (`R16_UINT` for `R16_SFLOAT`), so the dispatch moves
/// the texels' bits: the consumer creates such an image with `MUTABLE_FORMAT` (and
/// `EXTENDED_USAGE` when its own format is not storage-capable).
TileAttachment {
color_index: u32,
format: vk::Format,
view: StorageAttachmentView,
/// A draw's: the pipeline's `StorageAttachmentUse::view_alias`, where the view is in that
/// format, of an image the consumer made mutable to it (an sRGB attachment's
/// unsigned-integer format of its texel size, a BGRA-order one's RGBA-order twin on a
/// device that accesses its format without one in neither direction); `None` elsewhere,
/// and for a tile dispatch's, whose view is `format`.
#[cfg_attr(feature = "serde", serde(alias = "uint_view"))]
view_alias: Option<vk::Format>,
},
/// The tile map of the sparse texture bound at texture slot `slot` (`bind::SparseTileMap`),
/// a read-only storage buffer of [`SparseTileMap::byte_len`](crate::bind::SparseTileMap)
@@ -723,11 +683,6 @@ pub enum WriteSource {
compare: bool,
integer: bool,
},
/// The shadow of the render pass's stencil attachment that a fragment function's
/// shader-side stencil tests and writes (`GraphicsState::shadow_stencil`): the consumer's
/// `R8_UINT` 2D storage image of the attachment's extent, in `GENERAL` layout
/// ([`ShadowStencilUse`](crate::pipeline::ShadowStencilUse)).
ShadowStencil,
/// Element `index + 1` of the set-1 function-table array: the words of
/// `BindState::function_tables[index]` (`pipeline::table`'s layout, as
/// [`FunctionTableWords`](crate::bind::FunctionTableWords) encodes them), a read-only
@@ -769,12 +724,6 @@ pub enum WriteSource {
/// zero ([`ExecutionStatus::initial`](crate::bind::ExecutionStatus::initial)). The consumer
/// reads it once the command buffer completes.
ExecutionStatus,
/// The snapshot of the texture the draw binds at fragment texture slot `slot`
/// (`BindingSource::SnapshotTexels`, `VariantKey::snapshot_textures`): the consumer's
/// single-sample 2D `R32G32B32A32_UINT` storage image covering the draw's render area, in
/// `GENERAL` layout, which the draw's fragments write at their pixels in the draw that takes
/// the snapshot and read in the draw that reads it (`PushHole::SnapshotPhase`).
SnapshotTexels { slot: u32 },
}
/// The image of a combined image-sampler write.
@@ -84,7 +84,6 @@ use crate::lower::simd::divergent::VOTE_BYTES;
use crate::lower::simd::workgroup::arena_bytes;
use crate::pipeline::artifact::{ComputePipeline, RuntimeDependency, SpecConstant};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::graphics::StorageAttachmentView;
use crate::pipeline::interface::{BufferForm, PushLoc, SlotInterface};
use crate::pipeline::layout::BindingSource;
use crate::pipeline::sym::{PushField, SlotClass, SlotRef, SpecKey, Stage, SyntheticBinding};
@@ -684,8 +683,6 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
BindingSource::TileAttachment(color_index) => WriteSource::TileAttachment {
color_index,
format: tile_view_format(p, color_index)?,
view: StorageAttachmentView::Attachment,
view_alias: None,
},
other => return Err(internal(format!("a compute binding {other:?}"))),
};
+1 -34
View File
@@ -18,7 +18,7 @@ use crate::pipeline::facts::{Mechanism, RuntimeFact, UniformViewChoice};
use crate::pipeline::interface::SlotInterface;
use crate::pipeline::interface::{AccessSet, BufferForm, BufferSlot, Window};
use crate::pipeline::layout::{BindingSource, PipelineLayout};
use crate::pipeline::sym::{SampledType, SlotClass, SlotRef, SnapshotForm, SpecKey, Stage};
use crate::pipeline::sym::{SampledType, SlotClass, SlotRef, SpecKey, Stage};
use crate::vk;
use super::compute::internal;
@@ -400,39 +400,6 @@ pub(crate) fn srgb_variant(
.collect()
}
/// The form each of the snapshot slots `slots` keeps its texels in (`VariantKey::snapshot_textures`,
/// `SnapshotForm::of`): by the bound texture's sampled view, which the snapshot's copy fetches
/// through, and the slot's declared sampled type. [`SnapshotForm::Bits`] at a slot the variant
/// reads in another class (`cross`), or one whose sampled view the device has no format for (an
/// 8-bit sRGB format held as its UNORM twin among them). The variant's compile reads the same
/// key, so its plan for the same shape states the same forms.
pub(crate) fn snapshot_forms(
profile: &DeviceProfile,
slots: &std::collections::BTreeSet<SlotRef>,
interface: &BTreeMap<SlotRef, SlotInterface>,
shape: &BindShape,
cross: &BTreeMap<SlotRef, SampledType>,
) -> BTreeMap<SlotRef, SnapshotForm> {
let form = |slot: SlotRef| {
let Some(SlotInterface::Texture(t)) = interface.get(&slot) else {
return SnapshotForm::Bits;
};
let Some(TextureShape::Texture { pixel_format, .. }) = bound_texture(shape, slot) else {
return SnapshotForm::Bits;
};
if cross.contains_key(&slot) {
return SnapshotForm::Bits;
}
let usages: std::collections::BTreeSet<_> =
[crate::device::requirements::FormatUsage::SampledImage].into();
let Ok(m) = metal::format::vk_format(*pixel_format, &usages, profile) else {
return SnapshotForm::Bits;
};
SnapshotForm::of(m.format, t.sampled_type)
};
slots.iter().map(|&slot| (slot, form(slot))).collect()
}
/// The sampled texture slots whose function reads their texels in any numeric class
/// (`RuntimeFact::CrossClassReads`) at which `shape` binds a texture whose format's class is not
/// the slot's declared one and which the variant reads in that class
+2 -16
View File
@@ -44,10 +44,6 @@ pub enum DrawReplayRule {
VertexWritesMemory,
/// The state's fragment function writes memory.
FragmentWritesMemory,
/// The state has a fragment imageblock.
FragmentImageblock,
/// The state tests stencil in its shaders.
ShaderStencil,
/// The state reads its attachments.
InputAttachments,
/// The state's indirect draw needs its arguments on the CPU.
@@ -102,8 +98,6 @@ impl fmt::Display for DrawReplayRule {
DrawReplayRule::FragmentWritesMemory => {
"the inherited state's fragment function writes memory"
}
DrawReplayRule::FragmentImageblock => "the inherited state has a fragment imageblock",
DrawReplayRule::ShaderStencil => "the inherited state tests stencil in its shaders",
DrawReplayRule::InputAttachments => "the inherited state reads its attachments",
DrawReplayRule::ArgumentsOnCpu => {
"the inherited state's indirect draw needs its arguments on the CPU"
@@ -193,8 +187,8 @@ pub fn draw_replay_merges(primitive_type: PrimitiveType) -> bool {
/// The inherited state's rules (its `graphics` facts) for a draw replay, `merged` into one draw or
/// not: its functions write no memory (but a vertex function where nothing rasterizes, unless the
/// draws merge: a merged draw runs a vertex for each corner of a whole primitive, which only a
/// vertex function that writes no memory cannot tell from Metal's), and it has no fragment
/// imageblock, shader-side stencil or depth test or attachment read.
/// vertex function that writes no memory cannot tell from Metal's), and it has no depth test or
/// attachment read.
pub fn draw_replay_state(graphics: &GraphicsState, merged: bool) -> Result<(), DrawReplayRule> {
let rules = [
(
@@ -205,14 +199,6 @@ pub fn draw_replay_state(graphics: &GraphicsState, merged: bool) -> Result<(), D
graphics.fragment_writes_memory,
DrawReplayRule::FragmentWritesMemory,
),
(
graphics.fragment_imageblock.is_some(),
DrawReplayRule::FragmentImageblock,
),
(
graphics.shadow_stencil.is_some(),
DrawReplayRule::ShaderStencil,
),
(
!graphics.input_attachments.is_empty(),
DrawReplayRule::InputAttachments,
@@ -340,7 +340,6 @@ fn run_preprocess_counted(
PushHole::CommandRecordsAddress { offset, .. } => (offset, RECORDS),
PushHole::ReplayRegionAddress { .. } => panic!("the preprocess reads no region"),
PushHole::CaptureIndexAddress { .. } => panic!("the preprocess reads no index"),
PushHole::SnapshotPhase { .. } => panic!("the preprocess draws no snapshot"),
PushHole::MergedDrawAddress { .. } => panic!("the preprocess draws no merged draw"),
};
push[offset as usize..offset as usize + 8].copy_from_slice(&address.to_le_bytes());
+112 -13
View File
@@ -10,7 +10,7 @@
//! `x`; the runtime copies the buffer to and from that wide image with ordinary buffer-image
//! copies (one per row, so any `bytesPerRow`, overlapping rows included, is exact) and moves the
//! samples between it and the multisampled texture with these two crate-owned modules, each
//! through an unsigned-integer view of the texel size ([`PlanesCopy`], reused), so every texel's
//! through an unsigned-integer view of the texel size ([`PlanesCopy`]), so every texel's
//! bits cross unchanged whatever the format. `n` is baked into each module, so the split is one
//! per [`PlanesCopy`] and sample count, and the merge (whose fragment stage writes an unsigned
//! `uvec4` whatever the attachment's format) one per sample count.
@@ -29,7 +29,7 @@
//! wide image. Dispatch `ceil((width / n) / LOCAL_SIZE)`, `ceil(height / LOCAL_SIZE)`, `n`
//! workgroups.
//! - **The merge** ([`interleave_merge_modules`], buffer to texture): the fullscreen-triangle
//! vertex entry ([`super::sample_planes::merge_vertex_typed_module`], shared) and a `Fragment`
//! vertex entry ([`merge_vertex_typed_module`], which the depth/stencil copies share) and a `Fragment`
//! entry `main` with one sampled 2D image, the wide image in [`PlanesCopy::format`], at
//! [`InterleaveMergeModules::WIDE_BINDING`] of set 0. Each invocation at texel `(x, y)` sample
//! `s` fetches wide texel `(x * n + s, y)` and writes it, an unsigned `uvec4`, to the color
@@ -45,7 +45,6 @@
use std::sync::Arc;
use super::sample_planes::PlanesCopy;
use crate::budget::{Budget, Meter};
use crate::device::requirements::Requirements;
use crate::device::Device;
@@ -56,9 +55,61 @@ use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{TypeId, Value};
use crate::spirv::ir::{
BinOp, ExecMode, ExecModel, ImageOperands, ImageQuery, ImageType, ImageUsage, IoDir, MemAccess,
StorageClass, TexelMemory, Type, TypedModule,
BinOp, ConstBits, Constant, ConvOp, ExecMode, ExecModel, ImageOperands, ImageQuery, ImageType,
ImageUsage, IoDir, MemAccess, StorageClass, TexelMemory, Type, TypedModule,
};
use crate::vk::Format;
/// The unsigned-integer format of a color format's texel size, through which the split and the
/// merge move a texel's bits unchanged (the module docs).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PlanesCopy {
/// One byte: `R8_UINT`.
R8,
/// Two bytes: `R16_UINT`.
R16,
/// Four bytes: `R32_UINT`.
R32,
/// Eight bytes: `R32G32_UINT`.
Rg32,
/// Sixteen bytes: `R32G32B32A32_UINT`.
Rgba32,
}
impl PlanesCopy {
/// Every copy format, by texel size.
pub const ALL: [PlanesCopy; 5] = [
PlanesCopy::R8,
PlanesCopy::R16,
PlanesCopy::R32,
PlanesCopy::Rg32,
PlanesCopy::Rgba32,
];
/// The Vulkan format of the copy's views, an unsigned-integer one.
pub fn format(self) -> Format {
match self {
PlanesCopy::R8 => Format::R8_UINT,
PlanesCopy::R16 => Format::R16_UINT,
PlanesCopy::R32 => Format::R32_UINT,
PlanesCopy::Rg32 => Format::R32G32_UINT,
PlanesCopy::Rgba32 => Format::R32G32B32A32_UINT,
}
}
/// The SPIR-V image format of a storage view in [`PlanesCopy::format`].
pub(crate) fn spirv_format(self) -> crate::spv::ImageFormat {
match self {
PlanesCopy::R8 => crate::spv::ImageFormat::R8ui,
PlanesCopy::R16 => crate::spv::ImageFormat::R16ui,
PlanesCopy::R32 => crate::spv::ImageFormat::R32ui,
PlanesCopy::Rg32 => crate::spv::ImageFormat::Rg32ui,
PlanesCopy::Rgba32 => crate::spv::ImageFormat::Rgba32ui,
}
}
}
/// The crate-owned split module of one copy format and sample count on one device.
#[non_exhaustive]
@@ -317,18 +368,12 @@ fn finish(
/// The split module of `copy` at `samples` on `device`, built, verified, serialized and
/// numbered. Refused, `Unsupported` (feature `Format`) naming what the device lacks: an extended
/// copy format's storage without `shaderStorageImageExtendedFormats`; and `NotImplemented` for a
/// copy that moves no bits ([`PlanesCopy::Alpha8`], the sample planes' alone).
/// copy format's storage without `shaderStorageImageExtendedFormats`.
pub fn interleave_split_module(
device: &Device,
copy: PlanesCopy,
samples: u32,
) -> Result<InterleaveSplitModule, Error> {
if !copy.moves_bits() {
return Err(Error::Unsupported(Unsupported::not_implemented(
Feature::Format,
)));
}
let (spirv, requirements) = finish(
device,
split_typed_module(copy, samples)?,
@@ -348,7 +393,7 @@ pub fn interleave_merge_modules(
) -> Result<InterleaveMergeModules, Error> {
let (vertex, vertex_needs) = finish(
device,
super::sample_planes::merge_vertex_typed_module()?,
merge_vertex_typed_module()?,
"interleave merge's vertex stage",
)?;
let (fragment, fragment_needs) = finish(
@@ -366,5 +411,59 @@ pub fn interleave_merge_modules(
})
}
/// The merge's vertex stage as a typed module: one triangle over the viewport, `VertexIndex`
/// 0, 1, 2 at clip positions (-1, -1), (3, -1), (-1, 3).
pub(super) fn merge_vertex_typed_module() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let i32_ = b.ty(Type::Int {
width: 32,
signed: true,
})?;
let f32_ = b.ty(Type::Float { width: 32 })?;
let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?;
let index = b.builtin(crate::spv::BuiltIn::VertexIndex, IoDir::Input, i32_)?;
let position = b.builtin(crate::spv::BuiltIn::Position, IoDir::Output, vec4)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let int = |f: &mut FunctionBuilder<'_>, v: i32| -> BResult<Value> {
let c = f.module().constant(Constant::Scalar {
ty: i32_,
bits: ConstBits(u64::from(v as u32)),
})?;
f.module().const_value(c)
};
let float = |f: &mut FunctionBuilder<'_>, v: f32| -> BResult<Value> {
let c = f.module().constant(Constant::Scalar {
ty: f32_,
bits: ConstBits(u64::from(v.to_bits())),
})?;
f.module().const_value(c)
};
let index = f.module().global_value(index)?;
let index = f.load(index, MemAccess::default())?;
let one = int(&mut f, 1)?;
let two = int(&mut f, 2)?;
// x = (i << 1) & 2, y = i & 2: (0, 0), (2, 0), (0, 2); the position is twice that, less 1.
let shifted = f.binary(BinOp::ShiftLeftLogical, index, one)?;
let x = f.binary(BinOp::BitwiseAnd, shifted, two)?;
let y = f.binary(BinOp::BitwiseAnd, index, two)?;
let x = f.convert(ConvOp::ConvertSToF, x, f32_)?;
let y = f.convert(ConvOp::ConvertSToF, y, f32_)?;
let twice = float(&mut f, 2.0)?;
let less = float(&mut f, 1.0)?;
let x = f.binary(BinOp::FMul, x, twice)?;
let x = f.binary(BinOp::FSub, x, less)?;
let y = f.binary(BinOp::FMul, y, twice)?;
let y = f.binary(BinOp::FSub, y, less)?;
let zero = float(&mut f, 0.0)?;
let at = f.composite_construct(vec4, &[x, y, zero, less])?;
let position = f.module().global_value(position)?;
f.store(position, at, MemAccess::default())?;
f.ret(None)?;
let id = f.finish()?;
b.entry(ExecModel::Vertex, id, Vec::new())?;
b.finalize()
}
#[cfg(test)]
mod tests;
@@ -21,7 +21,7 @@ fn needs(m: TypedModule) -> Requirements {
/// `shaderStorageImageExtendedFormats`, the merge's fragment stage `sampleRateShading`.
#[test]
fn each_module_needs_what_its_docs_say() {
for copy in PlanesCopy::ALL.into_iter().filter(|c| c.moves_bits()) {
for copy in PlanesCopy::ALL {
for samples in SAMPLES {
let r = needs(split_typed_module(copy, samples).expect("split"));
let extended = !matches!(copy, PlanesCopy::R32 | PlanesCopy::Rgba32);
@@ -99,7 +99,7 @@ fn the_modules_are_valid_where_the_device_has_what_they_need() {
let mut built = 0;
for (name, device) in committed_devices() {
let profile = device.profile();
for copy in PlanesCopy::ALL.into_iter().filter(|c| c.moves_bits()) {
for copy in PlanesCopy::ALL {
for samples in SAMPLES {
let fits = profile
.check(&needs(split_typed_module(copy, samples).expect("split")))
@@ -116,14 +116,6 @@ fn the_modules_are_valid_where_the_device_has_what_they_need() {
}
}
}
// The sample planes' copy of floats moves no bits: no interleave takes it.
assert_eq!(
interleave_split_module(&device, PlanesCopy::Alpha8, 4).err(),
Some(Error::Unsupported(Unsupported::not_implemented(
Feature::Format
))),
"{name}"
);
for samples in SAMPLES {
let fits = profile
.check(&needs(
@@ -1,493 +0,0 @@
//! The copies between a multisampled color attachment and its sample planes.
//!
//! On a device without multisampled storage images, the storage form of framebuffer fetch reads
//! and writes a multisampled pass's fetched attachment as sample planes
//! (`StorageAttachmentView::SamplePlanes`): a single-sample 2D-array image of one layer per sample,
//! addressed `(x, y, SampleId)`. The consumer keeps the planes and moves the samples between
//! them and the attachment around the fetching draws. These crate-owned modules are the two
//! moves, each through an unsigned-integer view of the attachment format's texel size
//! ([`PlanesCopy`]), so every texel's bits cross unchanged whatever the format; `A8_UNORM`, whose
//! class no unsigned format shares, moves through its own format's `float`s
//! ([`PlanesCopy::Alpha8`]), which keep each 8-bit code:
//!
//! - **The split** ([`planes_split_module`], one per [`PlanesCopy`]): one `GLCompute` entry `main`
//! with local size ([`PlanesSplitModule::LOCAL_SIZE`], [`PlanesSplitModule::LOCAL_SIZE`], 1)
//! and two images in set 0:
//!
//! | Binding | Image | View |
//! |---|---|---|
//! | [`PlanesSplitModule::SOURCE_BINDING`] | the multisampled attachment | a sampled 2D view of its level and layer, in [`PlanesCopy::format`] |
//! | [`PlanesSplitModule::PLANES_BINDING`] | the planes | a storage 2D-array view of every layer, in [`PlanesCopy::format`] (declared without a format for [`PlanesCopy::Alpha8`]) |
//!
//! Invocation `(x, y, s)` inside the planes' size fetches sample `s` of pixel `(x, y)` and
//! writes it to texel `(x, y)` of layer `s`. Dispatch `ceil(width / LOCAL_SIZE)`,
//! `ceil(height / LOCAL_SIZE)`, `samples` workgroups over planes of the render area's size.
//! - **The merge** ([`planes_merge_modules`]): a `Vertex` entry `main` that draws one triangle over
//! the whole viewport from `VertexIndex` 0 to 2 (no vertex input), and a `Fragment` entry `main`
//! with one sampled 2D-array image, the planes in [`PlanesCopy::format`], at
//! [`PlanesMergeModules::PLANES_BINDING`] of set 0. Each invocation fetches texel
//! `(FragCoord.xy, SampleId)` and writes it, an unsigned `uvec4` (a `vec4` for
//! [`PlanesCopy::Alpha8`]), to the color output at `Location` 0. Run at sample rate (`sampleShadingEnable`, `minSampleShading` 1) into a
//! render pass whose one color attachment is the multisampled attachment's view in
//! [`PlanesCopy::format`], over the render area, without blending: each invocation writes its
//! own sample. The fragment module reads `SampleId`, so it needs `sampleRateShading`.
//!
//! **Synchronization** (consumer): the attachment's writes before the split's sampled reads, and
//! the planes' earlier accesses before its storage writes; the planes' storage writes before
//! the fetching draws; their writes before the merge's sampled reads, and the attachment's
//! earlier accesses before the merge's color writes.
use std::sync::Arc;
use crate::budget::{Budget, Meter};
use crate::device::requirements::Requirements;
use crate::device::Device;
use crate::error::{Error, Feature, InternalError, InternalKind, Unsupported};
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{TypeId, Value};
use crate::spirv::ir::{
BinOp, ConstBits, Constant, ConvOp, Dim, ExecMode, ExecModel, ImageOperands, ImageQuery,
ImageType, ImageUsage, IoDir, MemAccess, StorageClass, TexelMemory, Type, TypedModule,
};
use crate::vk::Format;
/// The unsigned-integer format of a color format's texel size, through which the split and the
/// merge move a texel's bits unchanged (the module docs).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PlanesCopy {
/// One byte: `R8_UINT`.
R8,
/// Two bytes: `R16_UINT`.
R16,
/// Four bytes: `R32_UINT`.
R32,
/// Eight bytes: `R32G32_UINT`.
Rg32,
/// Sixteen bytes: `R32G32B32A32_UINT`.
Rgba32,
/// One byte of `A8_UNORM`'s own compatibility class ("8-bit alpha"), which no view of another
/// format reads: moved through `A8_UNORM` views as the `float` each reads, `code / 255` in
/// alpha, which its store keeps as the code. Not a bits copy ([`PlanesCopy::moves_bits`]):
/// the sample planes' copies alone take it.
Alpha8,
}
impl PlanesCopy {
/// Every copy format, by texel size, then [`PlanesCopy::Alpha8`].
pub const ALL: [PlanesCopy; 6] = [
PlanesCopy::R8,
PlanesCopy::R16,
PlanesCopy::R32,
PlanesCopy::Rg32,
PlanesCopy::Rgba32,
PlanesCopy::Alpha8,
];
/// The Vulkan format of the copy's views: an unsigned-integer one, or `A8_UNORM` for
/// [`PlanesCopy::Alpha8`].
pub fn format(self) -> Format {
match self {
PlanesCopy::R8 => Format::R8_UINT,
PlanesCopy::R16 => Format::R16_UINT,
PlanesCopy::R32 => Format::R32_UINT,
PlanesCopy::Rg32 => Format::R32G32_UINT,
PlanesCopy::Rgba32 => Format::R32G32B32A32_UINT,
PlanesCopy::Alpha8 => Format::A8_UNORM,
}
}
/// Whether the copy moves texels as their bits, through an unsigned-integer format; else as
/// the `float`s of their own format ([`PlanesCopy::Alpha8`]).
pub fn moves_bits(self) -> bool {
self != PlanesCopy::Alpha8
}
/// The SPIR-V image format of a storage view in [`PlanesCopy::format`]: `Unknown` for
/// [`PlanesCopy::Alpha8`], whose format no SPIR-V format names.
pub(crate) fn spirv_format(self) -> crate::spv::ImageFormat {
match self {
PlanesCopy::R8 => crate::spv::ImageFormat::R8ui,
PlanesCopy::R16 => crate::spv::ImageFormat::R16ui,
PlanesCopy::R32 => crate::spv::ImageFormat::R32ui,
PlanesCopy::Rg32 => crate::spv::ImageFormat::Rg32ui,
PlanesCopy::Rgba32 => crate::spv::ImageFormat::Rgba32ui,
PlanesCopy::Alpha8 => crate::spv::ImageFormat::Unknown,
}
}
}
/// The crate-owned split module of one copy format on one device, validated like any output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanesSplitModule {
/// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0.
pub spirv: Arc<[u32]>,
/// What the module needs from the device: a storage image of an extended format
/// (`shaderStorageImageExtendedFormats`) for [`PlanesCopy::R8`], [`PlanesCopy::R16`] and
/// [`PlanesCopy::Rg32`], and a storage write without a format (the SPIR-V capability
/// `StorageImageWriteWithoutFormat`, which the device resolves, `Requirements`) for
/// [`PlanesCopy::Alpha8`].
pub requirements: Requirements,
}
impl PlanesSplitModule {
/// Descriptor set of every binding.
pub const SET: u32 = 0;
/// The multisampled attachment, a sampled image.
pub const SOURCE_BINDING: u32 = 0;
/// The planes, a storage image.
pub const PLANES_BINDING: u32 = 1;
/// Invocations of one workgroup along x, and along y.
pub const LOCAL_SIZE: u32 = 8;
}
/// The crate-owned merge modules of one device, validated like any output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanesMergeModules {
/// The vertex stage: SPIR-V 1.5 words, entry point `main`, no resources.
pub vertex: Arc<[u32]>,
/// The fragment stage: SPIR-V 1.5 words, entry point `main`, the planes at
/// [`PlanesMergeModules::PLANES_BINDING`] of set 0, the output at `Location` 0: a `uvec4`, or
/// a `vec4` for [`PlanesCopy::Alpha8`].
pub fragment: Arc<[u32]>,
/// What the two stages need from the device: `sampleRateShading`.
pub requirements: Requirements,
}
impl PlanesMergeModules {
/// Descriptor set of the binding.
pub const SET: u32 = 0;
/// The planes, a sampled image.
pub const PLANES_BINDING: u32 = 0;
}
/// The binding symbol of the split's multisampled attachment in its typed module
/// ([`PlanesSplitModule::SOURCE_BINDING`]).
const SPLIT_SOURCE: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Texture,
index: 0,
};
/// The binding symbol of the split's planes in its typed module
/// ([`PlanesSplitModule::PLANES_BINDING`]).
const SPLIT_PLANES: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Texture,
index: 1,
};
/// The binding symbol of the merge's planes in its typed fragment module
/// ([`PlanesMergeModules::PLANES_BINDING`]).
const MERGE_PLANES: ResourceSlot = ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::Texture,
index: 0,
};
/// The unsigned 32-bit scalar type.
fn u32_ty(b: &mut ModuleBuilder) -> BResult<TypeId> {
b.ty(Type::Int {
width: 32,
signed: false,
})
}
/// The scalar type of `copy`'s texels: unsigned 32-bit, or 32-bit float for a copy that does not
/// move bits ([`PlanesCopy::moves_bits`]).
fn texel_scalar(b: &mut ModuleBuilder, copy: PlanesCopy) -> BResult<TypeId> {
match copy.moves_bits() {
true => u32_ty(b),
false => b.ty(Type::Float { width: 32 }),
}
}
/// A 2D image type of `copy`'s texels ([`texel_scalar`]), of `usage` and `format`, arrayed or
/// multisampled as asked.
fn copy_image(
b: &mut ModuleBuilder,
copy: PlanesCopy,
usage: ImageUsage,
format: crate::spv::ImageFormat,
arrayed: bool,
multisampled: bool,
) -> BResult<TypeId> {
let sampled_type = texel_scalar(b, copy)?;
b.ty(Type::Image(ImageType {
sampled_type,
dim: Dim::D2,
depth: false,
arrayed,
multisampled,
usage,
format,
}))
}
/// The unsigned 32-bit constant `v` as a value.
fn uint(f: &mut FunctionBuilder<'_>, v: u32) -> BResult<Value> {
let c = f.u32_const(v)?;
f.module().const_value(c)
}
/// The split module of `copy` as a typed module, before serialization: the module
/// [`planes_split_module`] serializes. Its bindings are the symbols [`SPLIT_SOURCE`] and
/// [`SPLIT_PLANES`].
pub fn split_typed_module(copy: PlanesCopy) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let u32_ = u32_ty(&mut b)?;
let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let unknown = crate::spv::ImageFormat::Unknown;
let source_ty = copy_image(&mut b, copy, ImageUsage::Sampled, unknown, false, true)?;
let planes_ty = copy_image(
&mut b,
copy,
ImageUsage::Storage,
copy.spirv_format(),
true,
false,
)?;
let source = b.resource(SPLIT_SOURCE, StorageClass::UniformConstant, source_ty)?;
let planes = b.resource(SPLIT_PLANES, StorageClass::UniformConstant, planes_ty)?;
let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let invocation = f.module().global_value(invocation)?;
let invocation = f.load(invocation, MemAccess::default())?;
let planes = f.module().global_value(planes)?;
let planes = f.load(planes, MemAccess::default())?;
let size = f.query(ImageQuery::Size, planes)?;
let mut inside = None;
for axis in 0..3 {
let at = f.composite_extract(invocation, &[axis])?;
let end = f.composite_extract(size, &[axis])?;
let below = f.binary(BinOp::ULessThan, at, end)?;
inside = Some(match inside {
None => below,
Some(all) => f.binary(BinOp::LogicalAnd, all, below)?,
});
}
let inside = inside.ok_or(crate::spirv::error::BuildError::IdSpaceExhausted)?;
let source = f.module().global_value(source)?;
// Invocation `(x, y, s)` inside the planes copies sample `s` of pixel `(x, y)` into layer `s`.
let copy_sample: ArmFn<'_, ()> = Box::new(move |f, _| {
let source = f.load(source, MemAccess::default())?;
let x = f.composite_extract(invocation, &[0])?;
let y = f.composite_extract(invocation, &[1])?;
let s = f.composite_extract(invocation, &[2])?;
let pixel = f.composite_construct(uvec2, &[x, y])?;
let ops = ImageOperands {
sample: Some(s),
..ImageOperands::default()
};
let texel = f.fetch(source, pixel, &ops)?;
f.write(
planes,
invocation,
texel,
&ImageOperands::default(),
TexelMemory::default(),
)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, copy_sample, None)?;
f.ret(None)?;
let id = f.finish()?;
b.entry(
ExecModel::GLCompute,
id,
vec![ExecMode::LocalSize {
x: PlanesSplitModule::LOCAL_SIZE,
y: PlanesSplitModule::LOCAL_SIZE,
z: 1,
}],
)?;
b.finalize()
}
/// The merge's vertex stage as a typed module: one triangle over the viewport, `VertexIndex`
/// 0, 1, 2 at clip positions (-1, -1), (3, -1), (-1, 3).
pub fn merge_vertex_typed_module() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let i32_ = b.ty(Type::Int {
width: 32,
signed: true,
})?;
let f32_ = b.ty(Type::Float { width: 32 })?;
let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?;
let index = b.builtin(crate::spv::BuiltIn::VertexIndex, IoDir::Input, i32_)?;
let position = b.builtin(crate::spv::BuiltIn::Position, IoDir::Output, vec4)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let int = |f: &mut FunctionBuilder<'_>, v: i32| -> BResult<Value> {
let c = f.module().constant(Constant::Scalar {
ty: i32_,
bits: ConstBits(u64::from(v as u32)),
})?;
f.module().const_value(c)
};
let float = |f: &mut FunctionBuilder<'_>, v: f32| -> BResult<Value> {
let c = f.module().constant(Constant::Scalar {
ty: f32_,
bits: ConstBits(u64::from(v.to_bits())),
})?;
f.module().const_value(c)
};
let index = f.module().global_value(index)?;
let index = f.load(index, MemAccess::default())?;
let one = int(&mut f, 1)?;
let two = int(&mut f, 2)?;
// x = (i << 1) & 2, y = i & 2: (0, 0), (2, 0), (0, 2); the position is twice that, less 1.
let shifted = f.binary(BinOp::ShiftLeftLogical, index, one)?;
let x = f.binary(BinOp::BitwiseAnd, shifted, two)?;
let y = f.binary(BinOp::BitwiseAnd, index, two)?;
let x = f.convert(ConvOp::ConvertSToF, x, f32_)?;
let y = f.convert(ConvOp::ConvertSToF, y, f32_)?;
let twice = float(&mut f, 2.0)?;
let less = float(&mut f, 1.0)?;
let x = f.binary(BinOp::FMul, x, twice)?;
let x = f.binary(BinOp::FSub, x, less)?;
let y = f.binary(BinOp::FMul, y, twice)?;
let y = f.binary(BinOp::FSub, y, less)?;
let zero = float(&mut f, 0.0)?;
let at = f.composite_construct(vec4, &[x, y, zero, less])?;
let position = f.module().global_value(position)?;
f.store(position, at, MemAccess::default())?;
f.ret(None)?;
let id = f.finish()?;
b.entry(ExecModel::Vertex, id, Vec::new())?;
b.finalize()
}
/// The merge's fragment stage of `copy` as a typed module. Its binding is the symbol
/// [`MERGE_PLANES`].
pub fn merge_fragment_typed_module(copy: PlanesCopy) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let u32_ = u32_ty(&mut b)?;
let scalar = texel_scalar(&mut b, copy)?;
let i32_ = b.ty(Type::Int {
width: 32,
signed: true,
})?;
let f32_ = b.ty(Type::Float { width: 32 })?;
let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 })?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let texel4 = b.ty(Type::Vector {
elem: scalar,
len: 4,
})?;
let unknown = crate::spv::ImageFormat::Unknown;
let planes_ty = copy_image(&mut b, copy, ImageUsage::Sampled, unknown, true, false)?;
let planes = b.resource(MERGE_PLANES, StorageClass::UniformConstant, planes_ty)?;
let coord = b.builtin(crate::spv::BuiltIn::FragCoord, IoDir::Input, vec4)?;
let sample = b.builtin(crate::spv::BuiltIn::SampleId, IoDir::Input, i32_)?;
let output = b.fixed_io(0, IoDir::Output, texel4, false)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let coord = f.module().global_value(coord)?;
let coord = f.load(coord, MemAccess::default())?;
let sample = f.module().global_value(sample)?;
let sample = f.load(sample, MemAccess::default())?;
let layer = f.convert(ConvOp::Bitcast, sample, u32_)?;
// A pixel's center is at `(x + 0.5, y + 0.5)`: the conversion truncates to its integer.
let x = f.composite_extract(coord, &[0])?;
let y = f.composite_extract(coord, &[1])?;
let x = f.convert(ConvOp::ConvertFToU, x, u32_)?;
let y = f.convert(ConvOp::ConvertFToU, y, u32_)?;
let at = f.composite_construct(uvec3, &[x, y, layer])?;
let planes = f.module().global_value(planes)?;
let planes = f.load(planes, MemAccess::default())?;
let level = uint(&mut f, 0)?;
let ops = ImageOperands {
lod: Some(level),
..ImageOperands::default()
};
let texel = f.fetch(planes, at, &ops)?;
let output = f.module().global_value(output)?;
f.store(output, texel, MemAccess::default())?;
f.ret(None)?;
let id = f.finish()?;
b.entry(ExecModel::Fragment, id, vec![ExecMode::OriginUpperLeft])?;
b.finalize()
}
/// The fixed binding numbers of the modules' symbols.
fn binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(0),
Symbol::Binding(s) if *s == SPLIT_SOURCE => Some(PlanesSplitModule::SOURCE_BINDING),
Symbol::Binding(s) if *s == SPLIT_PLANES => Some(PlanesSplitModule::PLANES_BINDING),
Symbol::Binding(s) if *s == MERGE_PLANES => Some(PlanesMergeModules::PLANES_BINDING),
_ => None,
}
}
/// `m` verified against `device`'s profile (requirements included), serialized, and numbered
/// with the fixed bindings; `what` names it in an internal error. Refused, `Unsupported` naming
/// the first capability, where the device lacks what `m` needs.
fn finish(
device: &Device,
m: TypedModule,
what: &str,
) -> Result<(Arc<[u32]>, Requirements), Error> {
let profile = device.profile();
profile
.check(m.requirements())
.map_err(|c| Error::Unsupported(Unsupported::needs(Feature::FramebufferFetch, c)))?;
let mut meter = Meter::new(&Budget::default());
crate::spirv::verify::verify(&m, profile, &mut meter)?;
let r = crate::spirv::serialize::serialize(m)?;
profile.check(&r.requirements).map_err(|c| {
Error::Internal(InternalError::new(
InternalKind::RequirementsExceedProfile,
format!("the {what} needs {c:?}"),
))
})?;
let words = crate::spirv::serialize::relocate(&r, &binding_of)?;
Ok((words.into(), r.requirements))
}
/// The split module of `copy` on `device`: built with the typed builder, checked by the owned
/// verifier against the device's profile (requirements included), serialized, and numbered with
/// the fixed bindings of [`PlanesSplitModule`]. Refused, `Unsupported` (feature
/// `FramebufferFetch`) naming what the device lacks, where it lacks what the split needs: an
/// extended copy format's storage without `shaderStorageImageExtendedFormats`.
pub fn planes_split_module(device: &Device, copy: PlanesCopy) -> Result<PlanesSplitModule, Error> {
let (spirv, requirements) = finish(device, split_typed_module(copy)?, "planes split")?;
Ok(PlanesSplitModule {
spirv,
requirements,
})
}
/// The merge modules of `copy` on `device`, built and checked as [`planes_split_module`] is;
/// refused likewise where the device lacks `sampleRateShading`. Every bits copy
/// ([`PlanesCopy::moves_bits`]) takes the same modules.
pub fn planes_merge_modules(
device: &Device,
copy: PlanesCopy,
) -> Result<PlanesMergeModules, Error> {
let (vertex, vertex_needs) = finish(
device,
merge_vertex_typed_module()?,
"planes merge's vertex stage",
)?;
let (fragment, fragment_needs) =
finish(device, merge_fragment_typed_module(copy)?, "planes merge")?;
let requirements = device
.profile()
.union_requirements(&vertex_needs, &fragment_needs);
Ok(PlanesMergeModules {
vertex,
fragment,
requirements,
})
}
#[cfg(test)]
mod tests;
@@ -1,113 +0,0 @@
//! The sample planes' copy modules: what each needs, valid on every committed profile that has
//! it (L3, `G-val`), refused on a device that does not.
use super::*;
use crate::device::requirements::VkFeature;
use crate::device::{DeviceDescription, DevicePolicy};
use crate::spirv::testing::assert_valid;
use std::path::PathBuf;
/// The requirements of `m` as serialized.
fn needs(m: TypedModule) -> Requirements {
crate::spirv::serialize::serialize(m)
.expect("serialize")
.requirements
}
/// Each module needs exactly what the module docs say: the split of an extended storage format
/// `shaderStorageImageExtendedFormats`, the split of `A8_UNORM`'s planes a storage write without a
/// format (the capability, which the device resolves), the merge's fragment stage
/// `sampleRateShading`, and nothing else of the device.
#[test]
fn each_module_needs_what_its_docs_say() {
let write_without = crate::device::requirements::SpirvCapability::of(
crate::spv::Capability::StorageImageWriteWithoutFormat,
);
for copy in PlanesCopy::ALL {
let r = needs(split_typed_module(copy).expect("split"));
let extended = matches!(copy, PlanesCopy::R8 | PlanesCopy::R16 | PlanesCopy::Rg32);
assert_eq!(
r.features
.contains(&VkFeature::ShaderStorageImageExtendedFormats),
extended,
"{copy:?}: {r:?}"
);
assert_eq!(
r.spirv_capabilities.contains(&write_without),
!copy.moves_bits(),
"{copy:?}: {r:?}"
);
assert!(
!r.features.contains(&VkFeature::SampleRateShading),
"{copy:?}"
);
let r = needs(merge_fragment_typed_module(copy).expect("fragment"));
assert!(r.features.contains(&VkFeature::SampleRateShading), "{r:?}");
}
let r = needs(merge_vertex_typed_module().expect("vertex"));
assert!(r.features.is_empty(), "{r:?}");
}
/// Every committed device (`validation/profiles/*.json`), derived with the resident-table domains,
/// by file stem.
fn committed_devices() -> Vec<(String, Device)> {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles");
let mut out = Vec::new();
for entry in std::fs::read_dir(&dir).expect("profiles") {
let path = entry.expect("entry").path();
if path.extension().is_none_or(|x| x != "json") {
continue;
}
let stem = path
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let text = std::fs::read_to_string(&path).expect("read");
let desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
let device = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device");
out.push((stem, device));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
/// On every committed device each module is valid where the device has what it needs, numbered
/// with the fixed bindings, and refused (`Unsupported`) where it does not, never given as words
/// it cannot run.
#[test]
fn the_modules_are_valid_where_the_device_has_what_they_need() {
let mut built = 0;
for (name, device) in committed_devices() {
let profile = device.profile();
for copy in PlanesCopy::ALL {
let fits = profile
.check(&needs(split_typed_module(copy).expect("split")))
.is_ok();
match planes_split_module(&device, copy) {
Ok(module) => {
assert!(fits, "{name} {copy:?}");
assert_valid(split_typed_module(copy).expect("split"), profile);
assert!(!module.spirv.is_empty());
built += 1;
}
Err(Error::Unsupported(_)) => assert!(!fits, "{name} {copy:?}"),
Err(other) => panic!("{name} {copy:?}: {other}"),
}
}
for copy in [PlanesCopy::R32, PlanesCopy::Alpha8] {
let fragment = || merge_fragment_typed_module(copy).expect("fragment");
let fits = profile.check(&needs(fragment())).is_ok();
match planes_merge_modules(&device, copy) {
Ok(modules) => {
assert!(fits, "{name} {copy:?}");
assert_valid(merge_vertex_typed_module().expect("vertex"), profile);
assert_valid(fragment(), profile);
assert!(!modules.vertex.is_empty() && !modules.fragment.is_empty());
}
Err(Error::Unsupported(_)) => assert!(!fits, "{name} {copy:?}"),
Err(other) => panic!("{name} {copy:?}: {other}"),
}
}
}
assert!(built > 0);
}
-147
View File
@@ -263,33 +263,6 @@ pub struct BindState {
/// the whole set.
#[cfg_attr(feature = "serde", serde(default))]
pub resident_apart: bool,
/// The color attachments the draw's render pass instance leaves out of its subpass, read and
/// written as storage images in the pixel interlock by its other draws, that the draw's
/// render pipeline does not itself read or write so: a fragment function that writes one of
/// them through its first output runs the variant that writes it through the interlocked
/// storage form, so the draw records in that instance. Its variant is part of the shape
/// (`BindShape::interlocked_colors`); empty for every other draw.
#[cfg_attr(feature = "serde", serde(default))]
pub interlocked_colors: BTreeSet<u32>,
/// The fragment texture slots the consumer reads through a snapshot, by Metal index: a draw
/// that reads a texture its render pass renders, where the consumer draws it twice, first
/// taking each fragment's texel into the slot's snapshot with every color write mask zero,
/// then with the pipeline's masks reading the snapshot. The plan keeps a slot only where the
/// draw's pipeline can (the module docs of `bind::graphics`) and runs the variant that reads
/// it so (`VariantKey::snapshot_textures`); `BindingPlan::variant`'s `snapshot_textures` says
/// which it kept, and the consumer serves every other read as it would without it. Part of the
/// shape (`BindShape::snapshot_textures`); empty for every other draw.
#[cfg_attr(feature = "serde", serde(default))]
pub snapshot_textures: BTreeSet<u32>,
/// What the draw's depth and stencil tests can do to its fragments ([`FragmentTests::of`]),
/// which decides whether a fragment function that stores a color through the interlocked
/// storage form before the tests (`RuntimeFact::TestedStorageWrites`) stores what Metal
/// stores: its plan runs it as compiled, asks for the variant that declares early tests, or
/// refuses the draw. Its default, [`FragmentTests::Any`], refuses such a draw; the consumer
/// states it for a draw of such a pipeline, and may leave it for every other, whose plan does
/// not read it. Part of the shape (`BindShape::fragment_tests`).
#[cfg_attr(feature = "serde", serde(default))]
pub fragment_tests: FragmentTests,
/// The render encoder's blend color (`setBlendColorRed:green:blue:alpha:`; Metal's default
/// `[0, 0, 0, 0]` where the encoder never set it), red first: a fragment function that
/// computes a blend in the shader under a blend that reads it takes it as push data
@@ -307,104 +280,6 @@ pub struct BindState {
pub alpha_test_reference: Option<f32>,
}
/// What a draw's depth and stencil tests can do to its fragments (`BindState::fragment_tests`).
/// Metal tests a fragment after its function runs, unless the function declares
/// `[[early_fragment_tests]]`: a function that writes a color attachment through the interlocked
/// storage form stores inside the shader, so where it discards, and so cannot be tested early
/// whatever the draw's state, whether its store is Metal's is the draw's tests' to decide.
///
/// Where the tests drop fragments and write, such a draw is refused: [`FragmentTests::Depth`] and
/// [`FragmentTests::Stencil`] name the test that acts, and so the attachment the refusal names.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FragmentTests {
/// The tests may drop a fragment and the encoder counts the fragments that pass them (a
/// visibility result mode is set); or the draw does not state them. Such a draw of a function
/// that stores before the tests is refused `NotImplemented(FramebufferFetch)`: a store before
/// them would keep what they drop, and early tests would count what the function then
/// discards. (A draw whose tests write but count nothing is [`FragmentTests::Depth`] or
/// [`FragmentTests::Stencil`].)
#[default]
Any,
/// The tests may drop a fragment, but write neither the depth nor the stencil attachment, and
/// the encoder counts nothing: early tests drop the fragments Metal's later tests drop and
/// leave the attachments as Metal's do, so such a draw runs the variant that declares them
/// (`VariantKey::read_only_tests`). (A function that may not declare them, since it writes
/// other memory or returns depth, is refused at the tested attachment.)
Drop,
/// No test can drop a fragment: a store before the tests is the store Metal makes after
/// them, so such a draw runs the pipeline as compiled.
Pass,
/// Only the depth test can drop a fragment, and it writes the depth attachment where
/// `writes`; the stencil test can neither drop nor write, and the encoder counts nothing.
/// Such a draw of a function that stores before the tests is refused
/// `NotImplemented(FramebufferFetch)` at the depth attachment, unless it writes nothing and
/// the function has the variant that declares early tests, which it runs, as
/// [`FragmentTests::Drop`].
Depth { writes: bool },
/// The stencil test can drop a fragment or write the stencil attachment, and some test
/// writes its attachment (the stencil test's operations, or the depth test's writes; where
/// none does, the tests are [`FragmentTests::Drop`]); the encoder counts nothing. Such a draw
/// of a function that stores before the tests is refused `NotImplemented(FramebufferFetch)`
/// at the stencil attachment.
Stencil,
}
impl FragmentTests {
/// The tests of `depth_stencil` in a pass with a depth attachment where `depth` and a
/// stencil attachment where `stencil`, the encoder counting the fragments that pass them
/// where `counted`: a test of an attachment the pass lacks does nothing. Depth drops a
/// fragment unless it compares `Always`, and writes where its writes are enabled; a stencil
/// face drops one unless it compares `Always`, and writes where its write mask has a bit set
/// and an operation that can apply is not `Keep` (the stencil failure operation where it
/// can fail, the depth failure operation where depth can, and the pass operation).
pub fn of(
depth_stencil: &metal::state::DepthStencilDescriptor,
depth: bool,
stencil: bool,
counted: bool,
) -> FragmentTests {
use metal::{CompareFunction, StencilOperation};
let depth_drops = depth && depth_stencil.depth_compare_function != CompareFunction::Always;
let faces = [
&depth_stencil.front_face_stencil,
&depth_stencil.back_face_stencil,
];
let stencil_drops = stencil
&& faces
.iter()
.any(|f| f.stencil_compare_function != CompareFunction::Always);
if !depth_drops && !stencil_drops {
return FragmentTests::Pass;
}
let depth_writes = depth && depth_stencil.depth_write_enabled;
let stencil_writes = stencil
&& faces.iter().any(|f| {
let fails = f.stencil_compare_function != CompareFunction::Always;
let applies = [
(fails, f.stencil_failure_operation),
(depth_drops, f.depth_failure_operation),
(true, f.depth_stencil_pass_operation),
];
f.write_mask != 0
&& applies
.iter()
.any(|&(can, op)| can && op != StencilOperation::Keep)
});
if !stencil_drops && !stencil_writes && !counted {
return FragmentTests::Depth {
writes: depth_writes,
};
}
match (counted, depth_writes || stencil_writes) {
(true, _) => FragmentTests::Any,
(false, true) => FragmentTests::Stencil,
(false, false) => FragmentTests::Drop,
}
}
}
/// Where a command's heap arrays (set 1) hold its heap members and its argument samplers. A plan
/// writes member `i` of every image array, and listed argument sampler `i` of every sampler array,
/// at its planned element `i + 1` (element 0 is each array's neutral); the command's handle and
@@ -587,9 +462,6 @@ impl BindState {
depth_clamp_range: self.depth_clamp_range.is_some(),
rotated_weights: self.rotated_weights,
line_band: self.line_band.map(|(primitive, _)| primitive),
interlocked_colors: self.interlocked_colors.clone(),
fragment_tests: self.fragment_tests,
snapshot_textures: self.snapshot_textures.clone(),
primitive_id_indices: self.primitive_id_indices,
quad_primitive_ids: self.quad_primitive_ids,
private_list: self.private_list,
@@ -672,9 +544,6 @@ impl BindState {
depth_clamp_range,
rotated_weights,
line_band,
interlocked_colors,
fragment_tests,
snapshot_textures,
primitive_id_indices,
quad_primitive_ids,
private_list,
@@ -700,9 +569,6 @@ impl BindState {
&& self.depth_clamp_range.is_some() == *depth_clamp_range
&& self.rotated_weights == *rotated_weights
&& self.line_band.map(|(primitive, _)| primitive) == *line_band
&& self.interlocked_colors == *interlocked_colors
&& self.fragment_tests == *fragment_tests
&& self.snapshot_textures == *snapshot_textures
&& self.primitive_id_indices == *primitive_id_indices
&& self.quad_primitive_ids == *quad_primitive_ids
&& self.private_list == *private_list
@@ -1666,19 +1532,6 @@ pub struct BindShape {
/// triangles' edges, so (`VariantKey::line_band`).
#[cfg_attr(feature = "serde", serde(default))]
pub line_band: Option<crate::pipeline::BandPrimitive>,
/// `BindState.interlocked_colors`: the variant whose fragment function writes those it writes
/// through the interlocked storage form (`VariantKey::interlocked_colors`).
#[cfg_attr(feature = "serde", serde(default))]
pub interlocked_colors: BTreeSet<u32>,
/// `BindState.fragment_tests`: whether a fragment function that stores before the tests runs
/// as compiled, runs the variant that declares early tests (`VariantKey::read_only_tests`),
/// or is refused.
#[cfg_attr(feature = "serde", serde(default))]
pub fragment_tests: FragmentTests,
/// `BindState.snapshot_textures`: the variant whose fragment function reads those of them
/// the pipeline can read through a snapshot so (`VariantKey::snapshot_textures`).
#[cfg_attr(feature = "serde", serde(default))]
pub snapshot_textures: BTreeSet<u32>,
/// `BindState.primitive_id_indices`: the primitive ID's de-indexed variant of an indexed
/// draw's index type (`VariantKey::primitive_id_indices`), where the pipeline writes the ID.
#[cfg_attr(feature = "serde", serde(default))]
+9 -32
View File
@@ -40,16 +40,14 @@ use crate::pipeline::artifact::{
use crate::pipeline::descriptor::TessellationDescriptor;
use crate::pipeline::facts::{Mechanism, RuntimeFact, UniformViewChoice};
use crate::pipeline::graphics::{
BandPrimitive, BlendState, ColorAttachmentState, FragmentImageblock, GraphicsState,
ImageblockMechanism, InputAttachmentUse, LineBandState, ShadowStencilUse, StorageAttachmentUse,
StorageAttachmentView, TessellationState,
BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, InputAttachmentUse,
LineBandState, TessellationState,
};
use crate::pipeline::interface::{
AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView, LevelReads,
NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement,
SampledLevels, SamplerArray, SamplerSlot, SlotInterface, SnapshotRefusal, StageDescriptor,
StageInterface, StageSpec, TessellationStage, TextureAccess, TextureSlot, ThreadgroupArgument,
Window,
SampledLevels, SamplerArray, SamplerSlot, SlotInterface, StageDescriptor, StageInterface,
StageSpec, TessellationStage, TextureAccess, TextureSlot, ThreadgroupArgument, Window,
};
use crate::pipeline::layout::{
BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange,
@@ -849,7 +847,6 @@ codec_enum! {
SyntheticBinding {
ArgumentTable, ExecutionStatus, RootTable, HandleTable, ConstantBlob, TessellationFactors, Imageblock,
SamplerTable,
ShadowStencil,
FunctionTableDirectory,
PatchIndices,
ControlPointIndices,
@@ -860,7 +857,6 @@ codec_enum! {
Buffer, Texture, Sampler, Heap(f0), Synthetic(f0), InputAttachment(f0),
CombinedTextureSampler(f0), HeapSampler(f0), AccelerationStructure(f0), TileAttachment(f0),
TileMap, SeparateTexture(f0), SeparateSampler(f0),
SnapshotTexels(f0),
YCbCrPlanes(f0),
SamplerArray { compare, integer },
}
@@ -882,17 +878,15 @@ codec_enum! {
SlotBindOffset(f0), SlotGuestBase(f0), VertexBufferStride(f0), StageInRegion,
TessellationFactorOffset, TessellationFactorInstanceStride, TessellationFactorScale,
TextureLevels(f0), InstanceCount(f0), CommandRecordsAddress, ReplayRegionAddress,
ShadowStencilState, IndexCapacity, ViewportCount, RenderTargetArrayLength,
IndexCapacity, ViewportCount, RenderTargetArrayLength,
PatchIndexOffset, PatchIndexBound, ControlPointIndexOffset, StageInStride(f0),
AmplificationId, AmplificationLayerOffset, AmplificationViewportOffset,
DepthClampRange,
CaptureLayout,
CaptureIndexAddress,
StorageKeptChannels,
TextureIntegerChannels(f0),
BicubicTexels(f0),
HalfBlendColor,
SnapshotPhase,
VerticesPerPrimitive,
MergedDrawAddress,
AlphaTestReference,
@@ -1122,7 +1116,7 @@ codec_struct! {
stage, slots, threadgroup, push, descriptors, spec, needs_pointer_translation,
needs_handle_translation, io, tessellation, writes_memory, payload, reaches_command_buffers, command_writes, writes_textures,
reads_unbound_resources, writes_unbound_resources, unbound_storage_textures,
numbered_samplers, own_pixel_textures, snapshot_textures, snapshot_refusals, level_reads,
numbered_samplers, own_pixel_textures, level_reads,
private_bytes, sampler_arrays,
}
SamplerArray { slot, samplers }
@@ -1168,10 +1162,6 @@ codec_enum! {
TypeDetail { Plain, Struct(f0), Array(f0), TextureReference(f0), Pointer(f0) }
SlotInterface { Buffer(f0), Texture(f0), Sampler(f0) }
NumberedSampler { Constexpr(f0), Read, Write }
SnapshotRefusal {
Branch, Derivative, Sample, GroupOperation, Store, Atomic, ImageWrite, UndefinedOperand,
WritesMemory, Interlock, Coherent, Other,
}
PatchDomain { Triangle, Quad }
Window { Bounded { start, len }, Whole }
BufferForm { Descriptor(f0), Psb }
@@ -1230,7 +1220,6 @@ codec_enum! {
RenderTargetArrayLength { layer_dropped }, StageInRegion,
StageInStride { layout },
UniformViewRange { slot, choice }, UniformViewAliasing { slot },
FragmentImageblock { words, writes, master, data_size, alignment },
TileFunction, TileAttachmentFormat { color, format },
StorageTextureNumericType { slot },
OutOfBoundsAlpha { slot },
@@ -1239,8 +1228,6 @@ codec_enum! {
StorageTextureLevelViews { slot },
SparseTexture { slot, sparse_arm, tile_map },
AccelerationStructureInstanceCount { slot },
InterlockedFramebufferFetch { color, format, writes, early_tests, kept, blend, rounded },
ShadowStencil { formatless, multisampled },
PredicationVote, SrgbTexture { slot },
UlongAtomicView { slot },
ViewportCount,
@@ -1265,7 +1252,6 @@ codec_enum! {
RotatedWeights,
ConstantLanes { slot },
FunctionTableRange { addressed },
TestedStorageWrites { early_tests, early_variant },
TileThreadgroup { tile_sized },
ConstexprSampled { slot, modes },
CubicSampler { slot },
@@ -1281,7 +1267,6 @@ codec_enum! {
HeapStorageReads { stage, class },
AnisotropicSampler { slot },
StorageTextureIntegerChannels { slot },
MovableStorageWrites { early_variant },
ObjectThreadgroupArena { static_bytes, payload },
MergedDraws,
QuadPrimitiveIds,
@@ -1351,7 +1336,7 @@ codec_struct! {
StageModule {
stage, entry_point, spirv, specialization, required_subgroup_size, stage_flags,
reconvergence, precision_notes, strategies, constant_blob, rounded_colors,
specialized_notes, own_pixel_textures, snapshot_textures, snapshot_refusals, level_reads,
specialized_notes, own_pixel_textures, level_reads,
private_bytes, stats,
}
SpecializedNote { note, when }
@@ -1386,22 +1371,18 @@ codec_struct! {
topology, color_attachments, depth_format, stencil_format, rasterization_samples,
alpha_to_coverage, alpha_to_one, rasterizer_discard, dynamic_states, input_attachments,
rasterization_order_attachment_access, max_vertex_amplification_count, declares_layer,
tessellation, fragment_imageblock, vertex_writes_memory, writes_viewport_index,
storage_attachments, shadow_stencil, writes_point_size, writes_depth,
tessellation, vertex_writes_memory, writes_viewport_index, writes_point_size, writes_depth,
reads_barycentric_coord, reads_primitive_id, fragment_writes_memory, color_outputs,
sample_mask, snapshot_reads, logic_op, line_band,
sample_mask, logic_op, line_band,
}
TessellationState {
patch_control_points, domain, control_points, factor_step_function, push_offset,
control_point_index_type,
}
LineBandState { push_offset, primitive }
FragmentImageblock { mechanism, words, master, data_size, alignment }
ColorAttachmentState { format, write_mask, blend }
BlendState { src_color, dst_color, color_op, src_alpha, dst_alpha, alpha_op }
InputAttachmentUse { color_index, input_attachment_index, format_class }
StorageAttachmentUse { color_index, format, writes, formatless, view, view_alias, kept }
ShadowStencilUse { format, formatless, samples }
}
codec_enum! {
@@ -1409,8 +1390,6 @@ codec_enum! {
LinkedUseGap { EndlessLoop, StackMemory, GatedOffMeshBuiltin, UnmeasuredColorWrite }
SlotWritability { Never, Maybe, Unknown(f0) }
SlotWriteGap { UnresolvedIndex, UnmeasuredPayloadStage, MemberRole }
ImageblockMechanism { StorageImageInterlock }
StorageAttachmentView { Attachment, SamplePlanes { layers } }
BandPrimitive { Lines, Triangles }
PrecisionNote {
F16FmaDoubleRounding, F16IntConvDoubleRounding, GradFromBias,
@@ -1467,7 +1446,6 @@ codec_enum! {
UnmeasuredGroupSpeculation,
DeviceSampleLevel,
CoverageReadsRoundedAlpha,
UnmeasuredFetchBlend,
DeviceVertexConversion,
DeviceAlphaCoverage,
DeviceInterpolationOffset,
@@ -1495,7 +1473,6 @@ codec_enum! {
Synthetic { stage, binding }, Heap(f0), InputAttachment(f0), HeapSampler { stage, sampler },
AccelerationStructure { slot, level }, TileAttachment(f0), TileMap(f0),
SeparateTexture { texture, sampler }, SeparateSampler { stage, sampler },
SnapshotTexels(f0),
YCbCrPlanes(f0),
SamplerArray { stage, compare, integer },
IdentityArray,
+2 -43
View File
@@ -36,7 +36,7 @@ use std::fmt;
pub use crate::air::container::Hash256;
use crate::device::Device;
use crate::pipeline::lower_inputs::StorageImageChoice;
use crate::pipeline::sym::{SlotRef, SnapshotForm};
use crate::pipeline::sym::SlotRef;
use crate::vk;
mod artifacts;
@@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2254;
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
/// bumps it says what changed; this comment keeps no history.
pub const ARTIFACT_FORMAT_VERSION: u32 = 586;
pub const ARTIFACT_FORMAT_VERSION: u32 = 587;
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
@@ -196,19 +196,6 @@ pub struct VariantKey {
/// states it.
#[cfg_attr(feature = "serde", serde(default))]
pub srgb_textures: BTreeSet<SlotRef>,
/// Fragment texture slots the draw reads through a snapshot an earlier draw of the same
/// primitives took (`LoweringInputs::snapshot_textures`), each with the form the snapshot
/// keeps its texels in (`SnapshotForm::of` the slot's bound view): the slots
/// `BindShape::snapshot_textures` names, each one of the fragment stage's
/// `StageInterface::snapshot_textures`. The plan of a pipeline compiled under it states it,
/// and binds each slot's snapshot (`WriteSource::SnapshotTexels`, an image of the form's
/// `SnapshotForm::format`) and leaves which of its draws runs to the consumer
/// (`PushHole::SnapshotPhase`).
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub snapshot_textures: BTreeMap<SlotRef, SnapshotForm>,
/// Texture slots whose function reads the two-plane YCbCr texture the shape binds there in
/// place: every slot of a `RuntimeFact::YCbCrInPlace` the shape binds a texture whose planes
/// are read so (`TextureShape::Texture::ycbcr_in_place`). Each such slot binds the planes'
@@ -376,24 +363,6 @@ pub struct VariantKey {
/// (`FunctionTablesShape::bytes_class`). The plan of a pipeline compiled under it states it.
#[cfg_attr(feature = "serde", serde(default))]
pub addressed_function_tables: bool,
/// Color attachments the draw's render pass instance leaves out of its subpass, which its
/// draws read and write as storage images in the pixel interlock, that the fragment function
/// writes through its first output (`BindShape::interlocked_colors`): the variant's function
/// writes each through the interlocked storage form, as a function that fetches the color
/// writes it, so the draw records in that instance. Not a lowering input of its own: the render
/// pipeline's compile adds the colors to the fragment function's
/// `LoweringInputs::framebuffer_fetch`, whose exactness conditions refuse what the form does
/// not keep Metal's (a blend, among others).
#[cfg_attr(feature = "serde", serde(default))]
pub interlocked_colors: BTreeSet<u32>,
/// The draw's depth and stencil tests may drop fragments but write neither attachment and
/// count no visibility result (`BindShape::fragment_tests`), and the fragment function stores
/// a color through the interlocked storage form before the tests
/// (`RuntimeFact::TestedStorageWrites`): the variant whose function declares early fragment
/// tests (`LoweringInputs::read_only_tests`). The plan of a pipeline compiled under it states
/// it.
#[cfg_attr(feature = "serde", serde(default))]
pub read_only_tests: bool,
/// The runtime sampler slots of a `RuntimeFact::CubicSampler` that the shape binds to a
/// sampler whose min or mag filter is `Cubic`, each with the bound word masked by
/// `SamplerWord::CUBIC_STATE` (`LoweringInputs::cubic_samplers`): the variant whose function
@@ -535,7 +504,6 @@ impl VariantKey {
&& self.unit_axes == 0
&& self.storage_view_slots.is_empty()
&& self.srgb_textures.is_empty()
&& self.snapshot_textures.is_empty()
&& self.ycbcr_in_place.is_empty()
&& self.ycbcr_planes_sampled.is_empty()
&& self.texel_rows.is_empty()
@@ -557,8 +525,6 @@ impl VariantKey {
&& self.line_band.is_none()
&& self.swizzled_storage.is_empty()
&& !self.addressed_function_tables
&& self.interlocked_colors.is_empty()
&& !self.read_only_tests
&& self.cubic_samplers.is_empty()
&& self.primitive_id_indices.is_none()
&& !self.quad_primitive_ids
@@ -643,12 +609,6 @@ impl VariantKey {
.filter(|s| s.stage == stage)
.copied()
.collect();
out.snapshot_textures = self
.snapshot_textures
.iter()
.filter(|(s, _)| s.stage == stage)
.map(|(s, form)| (*s, *form))
.collect();
out.ycbcr_in_place = self
.ycbcr_in_place
.iter()
@@ -720,7 +680,6 @@ impl VariantKey {
out.dropped_colors = self.dropped_colors.clone();
out.depth_clamp_range = self.depth_clamp_range;
out.rotated_weights = self.rotated_weights;
out.read_only_tests = self.read_only_tests;
}
out.primitive_id_indices = self
.primitive_id_indices
+1 -64
View File
@@ -537,31 +537,6 @@ fn the_version_190_members_round_trip() {
assert_eq!(decode::<RuntimeFact>(&encode(&fact)), Ok(fact));
}
/// The fields format version 193 adds encode and decode with the fact and the pipeline state that
/// carry them: `RuntimeFact::FragmentImageblock`'s and `FragmentImageblock`'s `data_size` and
/// `alignment`.
#[test]
fn the_version_193_fields_round_trip() {
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::{FragmentImageblock, ImageblockMechanism};
let fact = RuntimeFact::FragmentImageblock {
words: 3,
writes: true,
master: [5; 32],
data_size: 11,
alignment: 2,
};
assert_eq!(decode::<RuntimeFact>(&encode(&fact)), Ok(fact));
let state = FragmentImageblock {
mechanism: ImageblockMechanism::StorageImageInterlock,
words: 8,
master: [6; 32],
data_size: 32,
alignment: 16,
};
assert_eq!(decode::<FragmentImageblock>(&encode(&state)), Ok(state));
}
/// The members format version 187 appends encode and decode, and each decodes as itself:
/// `PushField::ViewportCount`, `RuntimeFact::ViewportCount`, and `IoRole::ViewportIndex`.
#[test]
@@ -786,8 +761,7 @@ fn the_version_535_member_round_trips() {
/// The members format versions 153, 154, 155, 157 and 161 joined from every side encode and
/// decode together in one render pipeline: `PrecisionNote::CubeGradientFootprint` and
/// `CombinedSampler`, `RuntimeFact::InterlockedFramebufferFetch` and
/// `GraphicsState::storage_attachments`, `RuntimeFact::SrgbTexture` and
/// `CombinedSampler`, `RuntimeFact::SrgbTexture` and
/// `SrgbTexture`, and `PrecisionNote::HalfTexelConversion`,
/// `HalfSampleFilter`, `SrgbTexelDecode`, and `FloatSampleFilter`,
/// `HandleClass::Sampler { compare, integer }` and
@@ -797,7 +771,6 @@ fn the_version_535_member_round_trips() {
fn the_merged_members_round_trip_in_one_render_pipeline() {
use crate::pipeline::artifact::{PrecisionNote, RuntimeDependency, SpecConstant};
use crate::pipeline::facts::{Mechanism, RuntimeFact};
use crate::pipeline::graphics::StorageAttachmentUse;
use crate::pipeline::layout::{BindingSource, DescriptorBinding, DescriptorSetLayout};
use crate::pipeline::sym::{
CombinedSampler, HandleClass, ResourceKind, SamplerRef, SpecKey, SyntheticBinding,
@@ -904,34 +877,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
if let Some(last) = p.layout.sets.last_mut() {
last.bindings.extend(argument_samplers);
}
p.graphics.storage_attachments.push(StorageAttachmentUse {
color_index: 0,
format: vk::Format::R8G8B8A8_UNORM,
writes: true,
formatless: false,
view: crate::pipeline::StorageAttachmentView::SamplePlanes { layers: 4 },
view_alias: Some(vk::Format::R32_UINT),
kept: vk::ColorComponentFlags::B,
});
p.dependencies.push(RuntimeDependency {
fact: RuntimeFact::InterlockedFramebufferFetch {
color: 0,
format: vk::Format::R8G8B8A8_UNORM,
writes: true,
early_tests: true,
kept: vk::ColorComponentFlags::A,
blend: Some(crate::pipeline::lower_inputs::BlendEquation {
source_rgb: crate::metal::BlendFactor::One,
destination_rgb: crate::metal::BlendFactor::OneMinusSourceAlpha,
rgb_operation: crate::metal::BlendOperation::Add,
source_alpha: crate::metal::BlendFactor::One,
destination_alpha: crate::metal::BlendFactor::Zero,
alpha_operation: crate::metal::BlendOperation::Add,
}),
rounded: true,
},
mechanism: Mechanism::RenderPassContract,
});
p.dependencies.push(RuntimeDependency {
fact: RuntimeFact::SrgbTexture { slot: texture },
mechanism: Mechanism::Variant,
@@ -984,14 +929,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
sealed.dependencies.iter().any(|d| d.fact == fact),
"{fact:?}"
);
assert_eq!(sealed.graphics.storage_attachments.len(), 1);
assert!(sealed.dependencies.iter().any(|d| matches!(
d.fact,
RuntimeFact::InterlockedFramebufferFetch {
early_tests: true,
..
}
)));
assert!(sealed.dependencies.iter().any(|d| d.fact == ulong_view));
}
@@ -86,8 +86,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
RuntimeFact::UniformViewRange { .. } => Mechanism::Variant,
// Instantiation compares the bound Metal addresses.
RuntimeFact::UniformViewAliasing { .. } => Mechanism::PlanTimeCheck,
// The pass's imageblock storage image, bound to every draw of the pass.
RuntimeFact::FragmentImageblock { .. } => Mechanism::RenderPassContract,
// The render area is specialized; the planner refuses a layered pass.
RuntimeFact::TileFunction => Mechanism::Specialization,
// Compiled in under the function's key; the tile pipeline checks its descriptor.
@@ -117,12 +115,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
} => Mechanism::PlanTimeCheck,
// The binder writes the bound structure's instance count per dispatch or draw.
RuntimeFact::AccelerationStructureInstanceCount { .. } => Mechanism::PushConstant,
// The consumer binds the attachment as a storage image outside the subpass's color
// attachments (`GraphicsState::storage_attachments`).
RuntimeFact::InterlockedFramebufferFetch { .. } => Mechanism::RenderPassContract,
// The consumer keeps the stencil's shadow and binds it, with the encoder's stencil state
// as push data (`GraphicsState::shadow_stencil`).
RuntimeFact::ShadowStencil { .. } => Mechanism::RenderPassContract,
// The vote word is fixed in the module; the planner counts it against the limit.
RuntimeFact::PredicationVote => Mechanism::PlanTimeCheck,
// The binder pushes the bound format's class, which selects its conversion.
@@ -209,13 +201,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
BufferAccess::Addressed => Mechanism::Variant,
BufferAccess::Floor => Mechanism::PlanTimeCheck,
},
// A separate compile that declares early tests, which a draw whose tests drop fragments
// but write and count nothing asks for; the planner refuses a draw whose tests may write
// or count.
RuntimeFact::TestedStorageWrites { .. } => Mechanism::Variant,
// The tests a draw that moves the function's color into the interlocked storage form
// selects: that variant's.
RuntimeFact::MovableStorageWrites { .. } => Mechanism::Variant,
// The binder's regions carry the tile as Metal's threadgroup; the tile pipeline checks its
// descriptor's flag.
RuntimeFact::TileThreadgroup { .. } => Mechanism::RegionSelected,
+2 -3
View File
@@ -264,9 +264,8 @@ fn unsupported_features(profile: &DeviceProfile) -> Vec<Unsupported> {
],
));
}
// Framebuffer fetch refuses on no device: ordered by rasterization-order access, by the pixel
// interlock's storage form, or, with neither, through input attachments ordered between draws
// (`PrecisionNote::UnorderedFetchWithinDraw`).
// Framebuffer fetch refuses on no device: ordered by rasterization-order access, or without
// it through input attachments ordered between draws (`PrecisionNote::UnorderedFetchWithinDraw`).
// `[[barycentric_coord]]`: the device's builtins.
if !f.fragment.barycentric {
out.push(Unsupported::needs(
@@ -313,8 +313,7 @@ pub enum VkFeature {
/// `VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT`, the image usage
/// `VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT` and the pipeline flag
/// `VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT`, under which a draw samples a
/// color attachment of its own subpass (a feedback loop). A render pipeline that reads a
/// texture its pass renders through a snapshot requires it.
/// color attachment of its own subpass (a feedback loop).
AttachmentFeedbackLoopLayout,
/// `VK_EXT_extended_dynamic_state3`'s `extendedDynamicState3ColorWriteMask`: the dynamic
/// state `VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT`, set by `vkCmdSetColorWriteMaskEXT`.
+66 -103
View File
@@ -75,13 +75,6 @@ fn every_fact() -> Vec<RuntimeFact> {
choice: UniformViewChoice::Kept,
},
RuntimeFact::UniformViewAliasing { slot },
RuntimeFact::FragmentImageblock {
words: 4,
writes: true,
master: [7; 32],
data_size: 16,
alignment: 16,
},
RuntimeFact::TileFunction,
RuntimeFact::TileAttachmentFormat {
color: 1,
@@ -109,19 +102,6 @@ fn every_fact() -> Vec<RuntimeFact> {
tile_map: false,
},
RuntimeFact::AccelerationStructureInstanceCount { slot },
RuntimeFact::InterlockedFramebufferFetch {
color: 0,
format: crate::vk::Format::R32G32B32A32_SFLOAT,
writes: true,
early_tests: true,
kept: crate::vk::ColorComponentFlags::empty(),
blend: None,
rounded: false,
},
RuntimeFact::ShadowStencil {
formatless: false,
multisampled: false,
},
RuntimeFact::PredicationVote,
RuntimeFact::SrgbTexture { slot },
RuntimeFact::UlongAtomicView { slot },
@@ -176,10 +156,6 @@ fn every_fact() -> Vec<RuntimeFact> {
RuntimeFact::DepthClampRange,
RuntimeFact::ConstantLanes { slot },
RuntimeFact::FunctionTableRange { addressed: false },
RuntimeFact::TestedStorageWrites {
early_tests: false,
early_variant: true,
},
RuntimeFact::TileThreadgroup { tile_sized: true },
RuntimeFact::ConstexprSampled {
slot,
@@ -262,9 +238,6 @@ fn every_fact() -> Vec<RuntimeFact> {
index: 0,
},
},
RuntimeFact::MovableStorageWrites {
early_variant: true,
},
RuntimeFact::ObjectThreadgroupArena {
static_bytes: 16,
payload: Some(64),
@@ -311,76 +284,71 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::StageInStride { .. } => 27,
RuntimeFact::UniformViewRange { .. } => 28,
RuntimeFact::UniformViewAliasing { .. } => 29,
RuntimeFact::FragmentImageblock { .. } => 30,
RuntimeFact::TileFunction => 31,
RuntimeFact::TileAttachmentFormat { .. } => 32,
RuntimeFact::StorageTextureNumericType { .. } => 33,
RuntimeFact::OutOfBoundsAlpha { .. } => 34,
RuntimeFact::BicubicTexels { .. } => 35,
RuntimeFact::StorageTextureLevels { .. } => 36,
RuntimeFact::StorageTextureLevelViews { .. } => 37,
RuntimeFact::SparseTexture { .. } => 38,
RuntimeFact::AccelerationStructureInstanceCount { .. } => 39,
RuntimeFact::InterlockedFramebufferFetch { .. } => 40,
RuntimeFact::ShadowStencil { .. } => 41,
RuntimeFact::PredicationVote => 42,
RuntimeFact::HeapStorageReads { .. } => 43,
RuntimeFact::SrgbTexture { .. } => 44,
RuntimeFact::UlongAtomicView { .. } => 45,
RuntimeFact::ViewportCount => 46,
RuntimeFact::AliasedImageblock { .. } => 47,
RuntimeFact::CallStackDepth { .. } => 48,
RuntimeFact::FlatGrid => 49,
RuntimeFact::SparseTextureWrites { .. } => 50,
RuntimeFact::TileThreadgroupMemory { .. } => 51,
RuntimeFact::TextureSwizzle { .. } => 52,
RuntimeFact::TileImageblock { .. } => 53,
RuntimeFact::AmplificationDraws { .. } => 54,
RuntimeFact::FoldedGroups => 56,
RuntimeFact::ZeroedColor { .. } => 59,
RuntimeFact::DroppedColor { .. } => 60,
RuntimeFact::DepthClampRange => 61,
RuntimeFact::ConstantLanes { .. } => 62,
RuntimeFact::FunctionTableRange { .. } => 63,
RuntimeFact::TestedStorageWrites { .. } => 64,
RuntimeFact::TileThreadgroup { .. } => 66,
RuntimeFact::ConstexprSampled { .. } => 67,
RuntimeFact::CubicSampler { .. } => 68,
RuntimeFact::CubicArgumentSampler { .. } => 69,
RuntimeFact::HeapRawSamples { .. } => 73,
RuntimeFact::ExtendedRangeInputBlend { .. } => 75,
RuntimeFact::CrossClassReads { .. } => 76,
RuntimeFact::StorageTextureWriteRounding { .. } => 77,
RuntimeFact::HeapWriteRounding { .. } => 78,
RuntimeFact::HeapCrossClassNeutral { .. } => 79,
RuntimeFact::AnisotropicSampler { .. } => 80,
RuntimeFact::StorageTextureIntegerChannels { .. } => 81,
RuntimeFact::MovableStorageWrites { .. } => 83,
RuntimeFact::ObjectThreadgroupArena { .. } => 85,
RuntimeFact::WordInputMerge { .. } => 87,
RuntimeFact::ReplayBindings => 88,
RuntimeFact::MergedDraws => 72,
RuntimeFact::QuadPrimitiveIds => 58,
RuntimeFact::RotatedWeights => 82,
RuntimeFact::PrivateList => 86,
RuntimeFact::YCbCrInPlace { .. } => 65,
RuntimeFact::PartialObjectThreadgroups => 89,
RuntimeFact::RotatedInputBlend { .. } => 90,
RuntimeFact::OpenClMode => 91,
RuntimeFact::RowLockstep => 92,
RuntimeFact::BorderTexels { .. } => 93,
RuntimeFact::HeapResidency { .. } => 94,
RuntimeFact::OneRow => 95,
RuntimeFact::RegionViewports => 96,
RuntimeFact::CallThreadgroups => 97,
RuntimeFact::PartialThreadgroups => 98,
RuntimeFact::TexelRows { .. } => 84,
RuntimeFact::UnitAxes { .. } => 57,
RuntimeFact::TexelBufferParts { .. } => 70,
RuntimeFact::OpenClLineTexture { .. } => 74,
RuntimeFact::AddressAlignment { .. } => 71,
RuntimeFact::GridTiles => 55,
RuntimeFact::PrivateArena { .. } => 99,
RuntimeFact::TileFunction => 30,
RuntimeFact::TileAttachmentFormat { .. } => 31,
RuntimeFact::StorageTextureNumericType { .. } => 32,
RuntimeFact::OutOfBoundsAlpha { .. } => 33,
RuntimeFact::BicubicTexels { .. } => 34,
RuntimeFact::StorageTextureLevels { .. } => 35,
RuntimeFact::StorageTextureLevelViews { .. } => 36,
RuntimeFact::SparseTexture { .. } => 37,
RuntimeFact::AccelerationStructureInstanceCount { .. } => 38,
RuntimeFact::PredicationVote => 39,
RuntimeFact::HeapStorageReads { .. } => 40,
RuntimeFact::SrgbTexture { .. } => 41,
RuntimeFact::UlongAtomicView { .. } => 42,
RuntimeFact::ViewportCount => 43,
RuntimeFact::AliasedImageblock { .. } => 44,
RuntimeFact::CallStackDepth { .. } => 45,
RuntimeFact::FlatGrid => 46,
RuntimeFact::SparseTextureWrites { .. } => 47,
RuntimeFact::TileThreadgroupMemory { .. } => 48,
RuntimeFact::TextureSwizzle { .. } => 49,
RuntimeFact::TileImageblock { .. } => 50,
RuntimeFact::AmplificationDraws { .. } => 51,
RuntimeFact::FoldedGroups => 53,
RuntimeFact::ZeroedColor { .. } => 56,
RuntimeFact::DroppedColor { .. } => 57,
RuntimeFact::DepthClampRange => 58,
RuntimeFact::ConstantLanes { .. } => 59,
RuntimeFact::FunctionTableRange { .. } => 60,
RuntimeFact::TileThreadgroup { .. } => 62,
RuntimeFact::ConstexprSampled { .. } => 63,
RuntimeFact::CubicSampler { .. } => 64,
RuntimeFact::CubicArgumentSampler { .. } => 65,
RuntimeFact::HeapRawSamples { .. } => 69,
RuntimeFact::ExtendedRangeInputBlend { .. } => 71,
RuntimeFact::CrossClassReads { .. } => 72,
RuntimeFact::StorageTextureWriteRounding { .. } => 73,
RuntimeFact::HeapWriteRounding { .. } => 74,
RuntimeFact::HeapCrossClassNeutral { .. } => 75,
RuntimeFact::AnisotropicSampler { .. } => 76,
RuntimeFact::StorageTextureIntegerChannels { .. } => 77,
RuntimeFact::ObjectThreadgroupArena { .. } => 80,
RuntimeFact::WordInputMerge { .. } => 82,
RuntimeFact::ReplayBindings => 83,
RuntimeFact::MergedDraws => 68,
RuntimeFact::QuadPrimitiveIds => 55,
RuntimeFact::RotatedWeights => 78,
RuntimeFact::PrivateList => 81,
RuntimeFact::YCbCrInPlace { .. } => 61,
RuntimeFact::PartialObjectThreadgroups => 84,
RuntimeFact::RotatedInputBlend { .. } => 85,
RuntimeFact::OpenClMode => 86,
RuntimeFact::RowLockstep => 87,
RuntimeFact::BorderTexels { .. } => 88,
RuntimeFact::HeapResidency { .. } => 89,
RuntimeFact::OneRow => 90,
RuntimeFact::RegionViewports => 91,
RuntimeFact::CallThreadgroups => 92,
RuntimeFact::PartialThreadgroups => 93,
RuntimeFact::TexelRows { .. } => 79,
RuntimeFact::UnitAxes { .. } => 54,
RuntimeFact::TexelBufferParts { .. } => 66,
RuntimeFact::OpenClLineTexture { .. } => 70,
RuntimeFact::AddressAlignment { .. } => 67,
RuntimeFact::GridTiles => 52,
RuntimeFact::PrivateArena { .. } => 94,
}
}
@@ -388,7 +356,7 @@ fn variant(f: &RuntimeFact) -> usize {
fn mechanism_is_total_over_every_fact_and_profile() {
let facts = every_fact();
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
assert_eq!(covered, (0..100).collect(), "every_fact misses a variant");
assert_eq!(covered, (0..95).collect(), "every_fact misses a variant");
for (stem, _) in super::committed_profiles() {
let dev = device(&stem);
let p = dev.profile();
@@ -473,8 +441,6 @@ fn mechanism_is_total_over_every_fact_and_profile() {
| RuntimeFact::DroppedColor { .. }
| RuntimeFact::DepthClampRange
| RuntimeFact::RotatedWeights
| RuntimeFact::TestedStorageWrites { .. }
| RuntimeFact::MovableStorageWrites { .. }
| RuntimeFact::ConstexprSampled { .. }
| RuntimeFact::CubicSampler { .. }
| RuntimeFact::AnisotropicSampler { .. } => Mechanism::Variant,
@@ -505,9 +471,6 @@ fn mechanism_is_total_over_every_fact_and_profile() {
}
}
RuntimeFact::FramebufferFetch { .. }
| RuntimeFact::FragmentImageblock { .. }
| RuntimeFact::InterlockedFramebufferFetch { .. }
| RuntimeFact::ShadowStencil { .. }
| RuntimeFact::TileImageblock { .. }
| RuntimeFact::ExtendedRangeInputBlend { .. }
| RuntimeFact::RotatedInputBlend { .. }
+8 -22
View File
@@ -657,9 +657,8 @@ pub enum Feature {
// ---- Stages and fragment (lowering B7, B9) ----
/// Raster order groups without fragment shader interlock.
RasterOrderGroups,
/// Framebuffer fetch without an ordered form on the device (rasterization-order attachment
/// access, or the pixel interlock's storage form where the pipeline's state lets it be
/// exact), or in a shape not implemented.
/// Framebuffer fetch that needs an ordered read the device lacks (rasterization-order
/// attachment access), or in a shape not implemented.
FramebufferFetch,
/// `[[primitive_id]]` in a fragment function: behind a mesh function on a device without
/// geometry or tessellation shaders, whose fragment stage reads it from a varying no mesh
@@ -974,8 +973,7 @@ pub enum Feature {
/// ([`PrivateRenderField`]). Metal's answer for each was measured; building it is open work.
PrivateRenderState(PrivateRenderField),
/// A blend the function computes in the shader, into an extended-range attachment
/// (`BGRA10_XR`, `BGR10_XR`, `RGB10A8_2P_XR10` and their `_sRGB` twins) or into a 16-bit
/// float attachment in the interlocked storage form, of the part it names
/// (`BGRA10_XR`, `BGR10_XR`, `RGB10A8_2P_XR10` and their `_sRGB` twins), of the part it names
/// ([`ExtendedRangeBlend`]).
ExtendedRangeBlend(ExtendedRangeBlend),
/// A program-scope buffer binding of MSL 3.2 (macOS 15 and later), `constant T* constant p
@@ -1004,20 +1002,14 @@ pub enum Feature {
/// The part of a blend the shader computes that [`Feature::ExtendedRangeBlend`] refuses. An
/// extended-range attachment's blend, which the shader computes by the device's arithmetic, is
/// built for every factor, operation and write mask, and refuses only [`Output`](Self::Output);
/// a 16-bit float attachment's blend in the interlocked storage form refuses the other two, the
/// generic blend taking their place where the function reads the attachment.
/// Metal's blend the shader computes refuses [`DualSource`](Self::DualSource) under fast math.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ExtendedRangeBlend {
/// Into a 16-bit float attachment in the storage form, a factor of the second source
/// (`Source1Color`, `Source1Alpha` and their one-minus forms): Metal's blend is not built.
/// (A function that writes no second output to the attachment Metal refuses:
/// [`DescriptorError::ColorAttachment`].)
/// Under fast math, a factor of the second source (`Source1Color`, `Source1Alpha` and their
/// one-minus forms): Metal's blend is not built. (A function that writes no second output to
/// the attachment Metal refuses: [`DescriptorError::ColorAttachment`].)
DualSource,
/// Into a 16-bit float attachment in the storage form under fast math, a write mask of exactly
/// one color channel: Metal blends that channel otherwise than the two or three it blends as
/// one vector, by a rule not known. (Without fast math it is built.)
OneColorChannel,
/// An output other than four `half` or `float` lanes, or a second output other than those the
/// blend reads: not built.
Output,
@@ -1029,13 +1021,7 @@ pub enum ExtendedRangeBlend {
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PrivateRenderField {
/// `sampleMask` dropping a sample, in a pipeline whose fragment function writes an
/// attachment itself (a storage attachment, a shadow stencil or an imageblock), whose writes
/// were not measured under the mask.
SampleMask,
/// `sampleCoverage` other than 1 at a sample count past 4, where Metal was not measured, or
/// in a pipeline whose fragment function writes an attachment itself (a storage attachment,
/// a shadow stencil or an imageblock), whose writes were not measured under it.
/// `sampleCoverage` other than 1 at a sample count past 4, where Metal was not measured.
SampleCoverage,
/// `alphaTestEnabled` with a test the translation has not built: an `alphaTestFunction` past
/// `MTLCompareFunctionAlways`, a pipeline without a fragment function, a fragment function
+6 -7
View File
@@ -89,9 +89,8 @@
//! is not aliased onto one. Metal keeps it in the tile memory a fragment function's
//! `[[imageblock_data]]` is in, each pixel's same bytes, for the whole pass (measured on an M4,
//! `runtime::fragment_imageblock`). Its cells are the pass's imageblock storage
//! (`SyntheticBinding::Imageblock`, a fragment imageblock's `R32Uint` 2D-array storage image,
//! layer `w` word `w` of pixel `(x, y)`'s cell at texel `(x, y)`, which covers every pixel of
//! every tile): the entry stages each word of every cell of its tile from the storage into the
//! (`SyntheticBinding::Imageblock`, an `R32Uint` 2D-array storage image, layer `w` word `w` of
//! pixel `(x, y)`'s cell at texel `(x, y)`, which covers every pixel of every tile): the entry stages each word of every cell of its tile from the storage into the
//! threadgroup cells before the function runs, and back after it where the function may write
//! them, as it stages attachments, a cell past the render area too. The function records
//! `RuntimeFact::TileImageblock`, its size and alignment, which the consumer matches against the
@@ -327,8 +326,8 @@ pub struct TilePlan {
}
/// A tile function's explicit imageblock that stands alone (`TilePlan::pass_cells`): the pass's
/// imageblock storage, `SyntheticBinding::Imageblock`, which the pass's fragment functions'
/// imageblocks are in, each cell's words staged into the tile's cells and back.
/// imageblock storage, `SyntheticBinding::Imageblock`, each cell's words staged into the tile's
/// cells and back.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PassCells {
/// The function reaches its cells: the staging loads them.
@@ -1072,8 +1071,8 @@ pub fn declare(mb: &mut ModuleBuilder, access: &super::AccessPlan) -> BResult<Ti
signed: false,
})?;
if plan.pass_cells().is_some() {
// The fragment functions' `R32Uint` 2D-array storage image (`lower::fragment::imageblock`):
// layer `w` is word `w` of every pixel's cell.
// The pass's `R32Uint` 2D-array storage image: layer `w` is word `w` of every pixel's
// cell.
let ty = mb.ty(SType::Image(ImageType {
sampled_type: u32_,
dim: Dim::D2,
@@ -2,8 +2,8 @@
//! code itself rather than leaving the conversion to the device.
//!
//! A fragment function's color output is the device's to convert (`LoweringInputs::color_writes`),
//! a unorm channel's too, also where the shader computes a blend in the storage form of framebuffer
//! fetch (`PrecisionNote::DeviceColorConversion`): these rules serve the writes whose value the
//! a unorm channel's too, also where the shader computes a blend over its input attachment
//! (`PrecisionNote::DeviceColorConversion`): these rules serve the writes whose value the
//! translation computes, Metal's `textureWriteRoundingMode` 2 (a half-float channel rounded to
//! nearest even), and the private alpha test's 8-bit code ([`unorm8_code`]):
//!
File diff suppressed because it is too large. Load diff
@@ -53,23 +53,11 @@ pub(crate) fn half_output_note(cx: &SelectCx<'_>) -> PrecisionNote {
/// under every blend and format); in a module compiled with fast math the attachment too
/// (`StageIo::half_fast_colors`), whose note the pipeline decides by whether the attachment stores
/// some channel, since one that stores none (its write mask none, or absent from the pipeline)
/// holds nothing the output could differ by, but [`half_output_note`] itself for an attachment
/// the function writes in the storage form, which the pipeline's color attachments do not show;
/// in a module naming no math mode [`half_output_note`] itself. Nothing where the function
/// computes Metal's 16-bit float blend there itself (a fetched attachment's blend), which stores
/// Metal's value, nor where it writes the attachment in the
/// storage form under a write mask that names none of the format's channels, which stores nothing.
/// holds nothing the output could differ by; in a module naming no math mode
/// [`half_output_note`] itself.
pub(crate) fn note_half_output(cx: &mut SelectCx<'_>, color: u32) {
// Metal's 16-bit float blend, computed by the function: the attachment stores Metal's value.
// A storage write of no channel stores nothing.
if crate::lower::fragment::blends_half_in_storage(cx, color)
|| crate::lower::fragment::stores_nothing_in_storage(cx, color)
{
return;
}
let math = cx.entry.compile.fast_math;
let in_storage = crate::lower::fragment::written_in_storage(cx, color);
if math.is_none() || (math == Some(true) && in_storage) {
if math.is_none() {
let note = half_output_note(cx);
cx.precision.insert(note);
return;
@@ -4083,9 +4083,7 @@ fn aggregate_leaf_total_is_capped_before_expansion() {
mod atan2;
mod bicubic;
mod blend16;
mod blend8;
mod blend_packed;
mod color_write;
mod convert_suffix;
mod divide;
@@ -4095,7 +4093,6 @@ mod libm;
mod narrow;
mod pack;
mod round_texel;
mod snapshot_codes;
mod specials;
mod texel_round;
mod wide;
@@ -1,711 +0,0 @@
//! A fetched 16-bit float attachment's blend constant differences under fast math, on the
//! interpreter (`extended_range::blend::blend_half_float`): `BlendColor` with `OneMinusBlendColor`
//! and `BlendAlpha` with `OneMinusBlendAlpha`, either as the source factor, under `Subtract` and
//! `ReverseSubtract`, for the color channels and alpha alike, against Metal's measured form. The
//! minuend's product is fused into the difference, the subtrahend's rounded first, in the
//! arithmetic of the output's type: in `half` (a `half4` output) the blend color reads `h(c)` and
//! its one minus `h(1 - h(c))`, each sum and product rounded to `half`; in `float` (a `float4`
//! output) they read `c` and `f(1 - c)`, the result the `float` the caller converts.
//!
//! Plain Metal on the M3 Max under macOS 27.0.1, our own MSL, every channel of 16,384 random pixels
//! of each such state of the 677 and 1,350 state sweeps, `half4` and `float4` outputs, under the
//! blend color (0.3, 0.6, 0.9, 0.45), where blue's `h(1 - h(c))` and `h(1 - c)` differ: this form
//! holds Metal's bits in every channel, signed zeros included (through narrower outputs too). The
//! second blend color puts every color channel where the two differ. Before the form was built, the
//! color channels' blend color difference took the rounded form (both products rounded, one minus
//! of the color's `f32`), which differs from Metal's in some channels, and neither difference
//! counted as fitted.
//!
//! Without fast math a zero factor keeps its product (`a_safe_blend_keeps_a_zero_factors_product`):
//! each product rounded, `x · 0` a NaN where `x` is an infinity or a NaN and else a zero of the
//! signed operand's sign, their IEEE 754 sum rounded (`-0` only where both terms are `-0`), every
//! NaN the quiet `0x7FC00000`, and `SourceAlphaSaturated`'s minimum Metal's: a NaN operand gives
//! the other, two zeros `+0` (plain Metal on the M3 Max under macOS 27.0.1, each
//! operation with a zero factor beside each factor, color and alpha, into `RGBA16Float` and
//! `RG16Float` from `half4` and `float4` outputs, sources and texels holding signed zeros,
//! infinities and NaNs: every lane). Before the form was built, a zero factor dropped its term,
//! which kept neither the NaN of an infinite or NaN operand nor the zero sum's sign.
//!
//! Under fast math a zero factor drops its term, and a lone term's zero takes Metal's sign
//! (`a_fast_blend_s_lone_term_takes_metal_s_zero`): `R16Float` and `RG16Float` have no alpha, so
//! one minus the destination alpha is a zero factor; and into `RG16Float` or `RGBA16Float` a
//! destination's product subtracted alone by one minus the source's color or alpha negates the
//! factor, `h(d · h(z - 1))`, as does any one minus in alpha of a `float4` output (our probes
//! `rb16b`, `rb16c` and `rb16e`, the M3 Max under macOS 27.0.1, every lane). Before, the destination
//! alpha of those formats was the texel's one, whose `1 - 1` kept the product `d · 0` in the sum,
//! and every lone term negated its operand: the zero's sign was off Metal's.
use super::*;
use crate::lower::arith::extended_range::blend::{blend_half_float, Blend, BlendArith, BlendMath};
use crate::metal::{BlendFactor as F, BlendOperation as O, ColorWriteMask, PixelFormat};
use crate::pipeline::lower_inputs::BlendEquation;
/// `x` rounded to `half`, nearest even.
fn h(x: f64) -> f64 {
f16_to_f64(f64_to_f16(x))
}
/// The `f32` bits of a random `half` of magnitude in `[2^-8, 2^4)`, or a signed zero one time in
/// 16; a random `float` of that range where `float`.
fn operand(rng: &mut Rng, float: bool) -> u64 {
let w = rng.next();
let sign = if w & 1 == 1 { -1.0f64 } else { 1.0 };
if (w >> 1) & 15 == 0 {
return u64::from((0.0 * sign as f32).to_bits());
}
let exponent = ((w >> 5) % 12) as i32 - 8;
let v = match float {
true => 1.0 + ((w >> 16) & 0x7F_FFFF) as f64 / 8_388_608.0,
false => 1.0 + ((w >> 16) & 0x3FF) as f64 / 1024.0,
};
u64::from(((sign * v * 2f64.powi(exponent)) as f32).to_bits())
}
/// Metal's difference in lane `l` (alpha the last) of source `s` over destination
/// `d`, factors `fs` and `fd` under `op`, blend color `bc`, in `arith`: the `f32` bits of the
/// `half` (`BlendArith::Half`) or the `float`.
fn metal(
arith: BlendArith,
(fs, fd, op): (F, F, O),
bc: [f32; 4],
l: usize,
(s, d): (f32, f32),
) -> u64 {
let factor = |f: F| {
let alpha = l == 3 || matches!(f, F::BlendAlpha | F::OneMinusBlendAlpha);
let c = bc[if alpha { 3 } else { l }];
let one_minus = matches!(f, F::OneMinusBlendColor | F::OneMinusBlendAlpha);
match (arith, one_minus) {
(BlendArith::Half, false) => h(f64::from(c)),
(BlendArith::Half, true) => h(1.0 - h(f64::from(c))),
(BlendArith::Float, false) => f64::from(c),
(BlendArith::Float, true) => f64::from(1.0f32 - c),
}
};
let (ks, kd) = (factor(fs), factor(fd));
// The minuend's product fused, the subtrahend's rounded first.
let ((x, kx), (y, ky)) = match op {
O::Subtract => ((s, ks), (d, kd)),
_ => ((d, kd), (s, ks)),
};
match arith {
// Products and sums of these `half`s are exact in `f64`.
BlendArith::Half => {
let r = f64::from(x).mul_add(kx, -h(f64::from(y) * ky));
u64::from((h(r) as f32).to_bits())
}
BlendArith::Float => {
let (kx, ky) = (kx as f32, ky as f32);
u64::from(x.mul_add(kx, -(y * ky)).to_bits())
}
}
}
#[test]
fn a_fetched_blend_constant_difference_is_metals() {
let f4 = vec(float(32), 4);
let u4 = vec(int(32), 4);
let colors: [[f32; 4]; 2] = [[0.3, 0.6, 0.9, 0.45], [0.7, 0.55, 0.321, 0.8]];
let pairs = [
(F::BlendColor, F::OneMinusBlendColor),
(F::OneMinusBlendColor, F::BlendColor),
(F::BlendAlpha, F::OneMinusBlendAlpha),
(F::OneMinusBlendAlpha, F::BlendAlpha),
];
for arith in [BlendArith::Half, BlendArith::Float] {
let float = arith == BlendArith::Float;
let mut rng = Rng(0xD1FF_B1E0 ^ u64::from(float));
let mut cases: Vec<Case> = Vec::new();
for bc in colors {
let color: Vec<u64> = bc.iter().map(|c| u64::from(c.to_bits())).collect();
for _ in 0..300 {
let s = (0..4).map(|_| operand(&mut rng, float)).collect();
let d = (0..4).map(|_| operand(&mut rng, false)).collect();
cases.push(vec![s, d, color.clone()]);
}
}
for (fs, fd) in pairs {
for op in [O::Subtract, O::ReverseSubtract] {
let eq = BlendEquation {
source_rgb: fs,
destination_rgb: fd,
rgb_operation: op,
source_alpha: fs,
destination_alpha: fd,
alpha_operation: op,
};
let what = format!("{arith:?} {fs:?} {fd:?} {op:?}");
let b = Blend::half_float(
&eq,
PixelFormat::RGBA16Float,
ColorWriteMask::ALL,
BlendMath::Fast,
)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert!(b.fitted(), "{what}: {b:?}");
for q in HALF_FORMS {
check(
&format!("the fetched blend's {what}, half by {q:?}"),
&[f4, f4, u4],
f4,
&|fb, x| {
fb.module().set_quantize_form(q);
blend_half_float(fb, &b, arith, (x[0], x[1]), Some(x[2]))
},
&cases,
&|c| {
let bc: [f32; 4] = std::array::from_fn(|l| f32v(c[2][l]));
Some(
(0..4)
.map(|l| {
let sd = (f32v(c[0][l]), f32v(c[1][l]));
metal(arith, (fs, fd, op), bc, l, sd)
})
.collect(),
)
},
false,
);
}
}
}
}
}
/// The `f32` bits of a special `half` (a signed zero, an infinity, a NaN of either sign, one, the
/// smallest subnormal and normal, the largest finite) one time in three, else a random `half` (or
/// `float` where `float`) of [`operand`].
fn special(rng: &mut Rng, float: bool) -> u64 {
const SPECIALS: [u32; 12] = [
0x0000_0000,
0x8000_0000,
0x7F80_0000,
0xFF80_0000,
0x7FC0_0000,
0xFFC0_0000,
0x3F80_0000,
0xBF80_0000,
0x3380_0000,
0x3880_0000,
0x477F_E000,
0xC77F_E000,
];
let w = rng.next();
match w % 3 {
0 => u64::from(SPECIALS[((w >> 2) % 12) as usize]),
_ => operand(rng, float),
}
}
/// `x` rounded in `arith`: to `half`, nearest even, or to `float`.
fn rounded(arith: BlendArith, x: f64) -> f64 {
match arith {
BlendArith::Half => h(x),
BlendArith::Float => f64::from(x as f32),
}
}
/// Metal's `min` in `SourceAlphaSaturated`: a NaN operand gives the other, two
/// zeros `+0`.
fn metal_min(x: f64, y: f64) -> f64 {
match (x.is_nan(), y.is_nan()) {
(true, _) => y,
(_, true) => x,
_ if x == 0.0 && y == 0.0 => 0.0,
_ => x.min(y),
}
}
/// Metal's blend without fast math in lane `l` (alpha the last) of source `s` over
/// destination `d`, factors `fs` and `fd` under `op`, blend color `bc`, in `arith`: each product
/// rounded, a zero factor's kept, the IEEE 754 sum rounded; the `f32` bits of the `half` or the
/// `float`, every NaN `0x7FC00000`.
fn metal_safe(
arith: BlendArith,
(fs, fd, op): (F, F, O),
bc: [f32; 4],
l: usize,
(s, d): ([f32; 4], [f32; 4]),
) -> u64 {
let alpha = l == 3;
let r = |x: f64| rounded(arith, x);
let (sl, dl) = (f64::from(s[l]), f64::from(d[l]));
let (sa, da) = (f64::from(s[3]), f64::from(d[3]));
let factor = |f: F| match f {
F::Zero => 0.0,
F::One => 1.0,
F::SourceColor => sl,
F::OneMinusSourceAlpha => r(1.0 - sa),
F::DestinationColor => dl,
F::OneMinusDestinationAlpha => r(1.0 - da),
F::SourceAlphaSaturated if alpha => 1.0,
F::SourceAlphaSaturated => metal_min(sa, r(1.0 - da)),
F::BlendColor => r(f64::from(bc[l])),
_ => panic!("no factor {f:?} here"),
};
// Every product of two `half`s or two `float`s is exact in `f64`.
let (ps, pd) = (r(sl * factor(fs)), r(dl * factor(fd)));
let v = r(match op {
O::Add => ps + pd,
O::Subtract => ps - pd,
O::ReverseSubtract => pd - ps,
_ => panic!("no operation {op:?} here"),
});
match v.is_nan() {
true => 0x7FC0_0000,
false => u64::from((v as f32).to_bits()),
}
}
#[test]
fn a_safe_blend_keeps_a_zero_factors_product() {
let f4 = vec(float(32), 4);
let u4 = vec(int(32), 4);
let bc: [f32; 4] = [0.3, 0.6, 0.9, 0.45];
let others = [
F::One,
F::SourceColor,
F::OneMinusSourceAlpha,
F::DestinationColor,
F::OneMinusDestinationAlpha,
F::SourceAlphaSaturated,
F::BlendColor,
];
let pairs: Vec<(F, F)> = (others.iter())
.flat_map(|&o| [(F::Zero, o), (o, F::Zero)])
.chain([(F::Zero, F::Zero)])
.collect();
for arith in [BlendArith::Half, BlendArith::Float] {
let float = arith == BlendArith::Float;
let mut rng = Rng(0x2E80_FAC7 ^ u64::from(float));
let color: Vec<u64> = bc.iter().map(|c| u64::from(c.to_bits())).collect();
let mut cases: Vec<Case> = Vec::new();
// The saturated factor's zeros: a source alpha of `-0` beside a destination alpha of one.
for z in [0x8000_0000u64, 0] {
let s = vec![0xBF80_0000, 0x3F80_0000, 0x8000_0000, z];
let d = vec![0x3F80_0000, 0x8000_0000, 0xBF80_0000, 0x3F80_0000];
cases.push(vec![s, d, color.clone()]);
}
for _ in 0..400 {
let s = (0..4).map(|_| special(&mut rng, float)).collect();
let d = (0..4).map(|_| special(&mut rng, false)).collect();
cases.push(vec![s, d, color.clone()]);
}
for &(fs, fd) in &pairs {
for op in [O::Add, O::Subtract, O::ReverseSubtract] {
let eq = BlendEquation {
source_rgb: fs,
destination_rgb: fd,
rgb_operation: op,
source_alpha: fs,
destination_alpha: fd,
alpha_operation: op,
};
let what = format!("{arith:?} {fs:?} {fd:?} {op:?}");
let b = Blend::half_float(
&eq,
PixelFormat::RGBA16Float,
ColorWriteMask::ALL,
BlendMath::Rounded,
)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
for q in HALF_FORMS {
check_accept(
&format!("the safe blend's {what}, half by {q:?}"),
&[f4, f4, u4],
f4,
&|fb, x| {
fb.module().set_quantize_form(q);
blend_half_float(fb, &b, arith, (x[0], x[1]), Some(x[2]))
},
&cases,
&|c| {
let s: [f32; 4] = std::array::from_fn(|l| f32v(c[0][l]));
let d: [f32; 4] = std::array::from_fn(|l| f32v(c[1][l]));
Some(
(0..4)
.map(|l| metal_safe(arith, (fs, fd, op), bc, l, (s, d)))
.collect(),
)
},
&|got, want| {
let nan = |w: u64| f32v(w).is_nan();
got == want || (q == QuantizeForm::Controlled && nan(got) && nan(want))
},
);
}
}
}
}
}
/// The values of [`a_fast_blend_s_lone_term_takes_metal_s_zero`]'s grid: the signed zeros, one,
/// -1, 2.5, -0.75, the infinities and a NaN, each exact in `half` and every product and `1 - x` of
/// them too.
const GRID: [f32; 9] = [
0.0,
-0.0,
1.0,
-1.0,
2.5,
-0.75,
f32::INFINITY,
-f32::INFINITY,
f32::NAN,
];
/// Metal's blend under fast math (our probes `rb16b`, `rb16c`, `rb16e`) in lane `l` (alpha the
/// last) of an attachment of `channels` channels, of source `s` over destination `d`, factors `fs`
/// and `fd` under `op`, blend color one, one of whose terms is dropped by a zero factor (`None`
/// where neither is), in `arith`: the remaining term, its operand negated or, a destination's
/// product subtracted by one minus a source value into two or more channels (any one minus in
/// alpha in `float`), its factor; both dropped `+0`.
fn metal_fast_term(
arith: BlendArith,
(fs, fd, op): (F, F, O),
channels: u32,
l: usize,
(s, d): ([f32; 4], [f32; 4]),
) -> Option<f64> {
let alpha = l == 3;
let (sl, dl) = (f64::from(s[l]), f64::from(d[l]));
let sa = f64::from(s[3]);
let da = if channels == 4 { f64::from(d[3]) } else { 1.0 };
// Each factor: `None` where it is zero by the state, else its `1 - z` (`Some(z)`) or value;
// the blend color one.
let factor = |f: F| -> Option<(Option<f64>, f64)> {
let z = match f {
F::Zero => return None,
F::OneMinusDestinationAlpha if channels < 4 => return None,
F::One | F::BlendColor => return Some((None, 1.0)),
F::SourceColor => return Some((None, sl)),
F::SourceAlpha => return Some((None, sa)),
F::DestinationColor => return Some((None, dl)),
F::DestinationAlpha => return Some((None, da)),
F::SourceAlphaSaturated if alpha => return Some((None, 1.0)),
F::SourceAlphaSaturated => return Some((None, metal_min(sa, 1.0 - da))),
F::OneMinusBlendColor | F::OneMinusBlendAlpha => 1.0,
F::OneMinusSourceAlpha => sa,
F::OneMinusSourceColor if alpha => sa,
F::OneMinusSourceColor => sl,
F::OneMinusDestinationAlpha => da,
F::OneMinusDestinationColor if alpha => da,
F::OneMinusDestinationColor => dl,
_ => panic!("no factor {f:?} here"),
};
Some((Some(z), 1.0 - z))
};
let source_value = |f: F| matches!(f, F::OneMinusSourceAlpha | F::OneMinusSourceColor);
let (ks, kd) = (factor(fs), factor(fd));
let (x, k, f, sign) = match (ks, kd) {
(None, None) => return Some(0.0),
(Some(_), Some(_)) => return None,
(Some(k), None) => (sl, k, fs, if op == O::ReverseSubtract { -1.0 } else { 1.0 }),
(None, Some(k)) => (dl, k, fd, if op == O::Subtract { -1.0 } else { 1.0 }),
};
let destination = kd.is_some();
let into = destination
&& sign < 0.0
&& channels > 1
&& k.0.is_some()
&& (source_value(f) || (alpha && arith == BlendArith::Float));
Some(match (into, k.0) {
(true, Some(z)) => x * (z - 1.0),
_ => sign * (x * k.1),
})
}
#[test]
fn a_fast_blend_s_lone_term_takes_metal_s_zero() {
let f4 = vec(float(32), 4);
let u4 = vec(int(32), 4);
// The probes' states with a zero factor.
let states = [
(F::One, F::OneMinusDestinationAlpha, O::Add),
(F::One, F::OneMinusDestinationAlpha, O::Subtract),
(F::One, F::OneMinusDestinationAlpha, O::ReverseSubtract),
(F::SourceAlpha, F::OneMinusDestinationAlpha, O::Add),
(F::SourceAlpha, F::OneMinusDestinationAlpha, O::Subtract),
(F::OneMinusDestinationAlpha, F::One, O::Subtract),
(
F::OneMinusDestinationAlpha,
F::SourceAlpha,
O::ReverseSubtract,
),
(
F::OneMinusDestinationAlpha,
F::OneMinusDestinationAlpha,
O::Subtract,
),
(F::Zero, F::OneMinusSourceAlpha, O::Add),
(F::Zero, F::OneMinusSourceAlpha, O::Subtract),
(F::Zero, F::OneMinusSourceColor, O::Subtract),
(F::Zero, F::OneMinusDestinationAlpha, O::Subtract),
(F::Zero, F::OneMinusDestinationColor, O::Subtract),
(F::Zero, F::OneMinusBlendColor, O::Subtract),
(F::Zero, F::OneMinusBlendAlpha, O::Subtract),
(F::Zero, F::BlendColor, O::Subtract),
(F::Zero, F::SourceColor, O::Subtract),
(F::Zero, F::SourceAlpha, O::Subtract),
(F::Zero, F::SourceAlphaSaturated, O::Subtract),
(F::Zero, F::One, O::Subtract),
(F::Zero, F::DestinationAlpha, O::Add),
(F::Zero, F::DestinationAlpha, O::Subtract),
(F::Zero, F::DestinationColor, O::Subtract),
(F::OneMinusSourceAlpha, F::Zero, O::Subtract),
(F::OneMinusSourceAlpha, F::Zero, O::ReverseSubtract),
(F::OneMinusSourceColor, F::Zero, O::ReverseSubtract),
(F::OneMinusDestinationAlpha, F::Zero, O::ReverseSubtract),
(F::OneMinusDestinationColor, F::Zero, O::ReverseSubtract),
(F::OneMinusBlendColor, F::Zero, O::ReverseSubtract),
(F::SourceAlpha, F::Zero, O::Subtract),
(F::SourceAlpha, F::Zero, O::ReverseSubtract),
(F::SourceAlphaSaturated, F::Zero, O::ReverseSubtract),
(F::DestinationColor, F::Zero, O::ReverseSubtract),
(F::DestinationAlpha, F::Zero, O::ReverseSubtract),
(F::One, F::Zero, O::ReverseSubtract),
(F::Zero, F::Zero, O::Add),
(F::Zero, F::Zero, O::Subtract),
];
let formats = [
(PixelFormat::R16Float, 1),
(PixelFormat::RG16Float, 2),
(PixelFormat::RGBA16Float, 4),
];
let bits = |x: f32| u64::from(x.to_bits());
for arith in [BlendArith::Half, BlendArith::Float] {
for (pf, channels) in formats {
// Each source of color `GRID[a]` and alpha `GRID[b]` over a texel of color `GRID[c]`
// and alpha `GRID[e]`, or one, the texel's, where the format has no alpha.
let n = GRID.len();
let alphas = if channels == 4 { n } else { 1 };
let mut cases: Vec<Case> = Vec::new();
for i in 0..n * n * n * alphas {
let (a, b, c, e) = (
i / (n * n * alphas),
(i / (n * alphas)) % n,
(i / alphas) % n,
i % alphas,
);
let da = if channels == 4 { GRID[e] } else { 1.0 };
let s = [GRID[a], GRID[a], GRID[a], GRID[b]].map(bits).to_vec();
let d = [GRID[c], GRID[c], GRID[c], da].map(bits).to_vec();
cases.push(vec![s, d, vec![bits(1.0); 4]]);
}
// A zero factor of the state or the format's, which drops its term.
let dropped = |f: F| f == F::Zero || (f == F::OneMinusDestinationAlpha && channels < 4);
for (fs, fd, op) in states
.into_iter()
.filter(|&(fs, fd, _)| dropped(fs) || dropped(fd))
{
let eq = BlendEquation {
source_rgb: fs,
destination_rgb: fd,
rgb_operation: op,
source_alpha: fs,
destination_alpha: fd,
alpha_operation: op,
};
let what = format!("{arith:?} {pf:?} {fs:?} {fd:?} {op:?}");
let b = Blend::half_float(&eq, pf, ColorWriteMask::ALL, BlendMath::Fast)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert!(b.fitted(), "{what}: {b:?}");
// The channels the format stores: the store drops the others.
let stored = channels as usize;
for q in HALF_FORMS {
check_accept(
&format!("the fast blend's {what}, half by {q:?}"),
&[f4, f4, u4],
f4,
&|fb, x| {
fb.module().set_quantize_form(q);
blend_half_float(fb, &b, arith, (x[0], x[1]), Some(x[2]))
},
&cases,
&|c| {
let s: [f32; 4] = std::array::from_fn(|l| f32v(c[0][l]));
let d: [f32; 4] = std::array::from_fn(|l| f32v(c[1][l]));
let lanes = (0..4).map(|l| match l < stored {
true => metal_fast_term(arith, (fs, fd, op), channels, l, (s, d))
.map(|v| bits(v as f32)),
// A lane the store drops: any answer.
false => Some(u64::MAX),
});
lanes.collect()
},
&|got, want| {
let nan = |w: u64| f32v(w).is_nan();
want == u64::MAX || got == want || (nan(got) && nan(want))
},
);
}
}
}
}
}
/// The source values `half-output-blends-*` sweeps: `k / 16 - 2` for `k` in 0 to 63, every
/// sixteenth between -2 and 2, each exact in `half`.
fn blend_source(index: usize) -> f64 {
index as f64 / 16.0 - 2.0
}
/// The destination codes `half-output-blends-*` draws for a 16-bit float format: xorshift64\*
/// seeded from the format's Metal value, a multiple of 2^-10 in [0, 1] per channel per pixel,
/// each exact in `half`. Restated here so this test owns its inputs; the words are the words of
/// that family's recordings.
struct BlendRng(u64);
impl BlendRng {
fn new(seed: u64) -> Self {
let mut state = seed
.wrapping_mul(0x9e37_79b9_7f4a_7c15)
.wrapping_add(0x632b_e59b_d9b4_e019);
if state == 0 {
state = 1;
}
let mut generator = Self(state);
for _ in 0..8 {
generator.next();
}
generator
}
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(2_685_821_657_736_338_717)
}
}
/// Metal's rounding in a fast-math `half` output's blend into a 16-bit float attachment at the
/// states [`Blend::fitted`] holds by measurement (`blend::MEASURED_SIXTEEN`), on the interpreter,
/// over the very sources and destinations `half-output-blends-r16f`, `-rg16f` and `-rgba16f`
/// compare against plain Metal.
///
/// **The rule, off those sites' recordings:** Metal rounds the **source** product to the
/// attachment's precision and carries the **destination** product into the sum unrounded,
/// `h(h(Sf · S) + Df · D)` -- one fused multiply-add on the destination term -- where the device's
/// own blend is the mirror image, `h(Sf · S + h(Df · D))`. `SourceColor` over `DestinationColor`
/// is the state that shows it: the source product `S · S` is exact in the attachment, so only the
/// destination product's rounding is left, and the two orders part by a code.
///
/// `DestinationAlpha` over `OneMinusDestinationAlpha` adds the alpha class, which is neither
/// order: `h(da · h(h(1 + sa) - da))`, the common factor's form ([`plan`]).
///
/// 2,560 words: 256 of `R16Float`, 512 of `RG16Float` and 1,024 of `RGBA16Float` at
/// `SourceColor`/`DestinationColor`, and 768 color words of `RGBA16Float` at
/// `DestinationAlpha`/`OneMinusDestinationAlpha`, whose 256 alpha words this test holds too.
#[test]
fn a_measured_fast_blend_rounds_the_source_product_first() {
let f4 = vec(float(32), 4);
// The sweep's stride: how far apart two channels of one pixel are, so each source value lands
// at every channel position across the pixels.
const STRIDE: usize = 7;
const SOURCES: usize = 64;
const PIXELS: usize = 256;
let states = [
(F::SourceColor, F::DestinationColor),
(F::DestinationAlpha, F::OneMinusDestinationAlpha),
];
let formats = [
(PixelFormat::R16Float, 1u32, 25u64),
(PixelFormat::RG16Float, 2, 65),
(PixelFormat::RGBA16Float, 4, 115),
];
let mut words = 0usize;
for (pf, channels, raw) in formats {
// The case's destination codes, one row a pixel, and a missing alpha channel's one, as
// Metal's blend and Vulkan's both read it.
let mut rng = BlendRng::new(raw);
let destinations: Vec<[f64; 4]> = (0..PIXELS)
.map(|_| {
std::array::from_fn(|c| match c < channels as usize {
true => (rng.next() % 1025) as f64 / 1024.0,
false => 1.0,
})
})
.collect();
let cases: Vec<Case> = (0..PIXELS)
.map(|pixel| {
let s: Vec<u64> = (0..4)
.map(|c| {
let v = blend_source((pixel + STRIDE * c as usize) % SOURCES);
u64::from((v as f32).to_bits())
})
.collect();
let d: Vec<u64> = destinations[pixel]
.iter()
.map(|&v| u64::from((v as f32).to_bits()))
.collect();
vec![s, d]
})
.collect();
for (fs, fd) in states {
let eq = BlendEquation {
source_rgb: fs,
destination_rgb: fd,
rgb_operation: O::Add,
source_alpha: fs,
destination_alpha: fd,
alpha_operation: O::Add,
};
let what = format!("{pf:?} {fs:?} {fd:?}");
let b = Blend::half_float(&eq, pf, ColorWriteMask::ALL, BlendMath::Fast)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert!(b.fitted(), "{what}: {b:?}");
// Metal's value in lane `l` of the blend: the color class in the three color lanes,
// and in alpha the attachment's own class, where it holds one.
let metal = |s: [f64; 4], d: [f64; 4], l: usize| -> u64 {
let alpha = l == 3;
let has_alpha = channels == 4;
let (sl, dl) = (s[l], d[l]);
let (sa, da) = (s[3], d[3]);
if alpha && !has_alpha {
// The lane the attachment does not hold keeps the texel's.
return u64::from((dl as f32).to_bits());
}
let value = match (fs, alpha) {
// The alpha of the destination alpha over its one minus: the common factor's
// form, `h(da · h(h(1 + sa) - da))`.
(F::DestinationAlpha, true) => h(da * h(h(1.0 + sa) - da)),
_ => {
let (ks, kd) = match fs {
F::SourceColor => (sl, dl),
F::DestinationAlpha => (da, h(1.0 - da)),
other => panic!("no factor {other:?} here"),
};
// Every product of two of these `half`s is exact in `f64`: the source's
// rounded to the attachment, the destination's fused into the sum.
h(h(sl * ks) + dl * kd)
}
};
u64::from((value as f32).to_bits())
};
for q in HALF_FORMS {
check(
&format!("the measured blend's {what}, by {q:?}"),
&[f4, f4],
f4,
&|fb, x| {
fb.module().set_quantize_form(q);
blend_half_float(fb, &b, BlendArith::Half, (x[0], x[1]), None)
},
&cases,
&|c| {
let s: [f64; 4] = std::array::from_fn(|l| f64::from(f32v(c[0][l])));
let d: [f64; 4] = std::array::from_fn(|l| f64::from(f32v(c[1][l])));
Some((0..4).map(|l| metal(s, d, l)).collect())
},
false,
);
}
// The words of the site: one pixel a row, the channels the format holds.
words += PIXELS * channels as usize;
}
}
// The states' sites in the three formats: 1,792 a state, the 2,560 of the five sites the
// family's recordings measure among them.
assert_eq!(words, 3_584, "every word of the measured states' sites");
}
@@ -4,7 +4,7 @@
//! reads the destination's code `c` as `h(c / 255)` (`f(c / 255)` for a `float4` output) and the
//! blend color clamped to `[0, 1]` (as `half` in `half` arithmetic), blends in the output's type,
//! and stores the result's code by its unorm write (a NaN 0, clamped, the exact product with 255
//! rounded to nearest). The function writes the blend's result, which the storage image's store
//! rounded to nearest). The function writes the blend's result, which the color attachment's write
//! converts (the device's conversion, `PrecisionNote::DeviceColorConversion`): each lane is checked
//! through Vulkan's conversion of it ([`stored`]: a NaN 0, clamped, the product with 255 rounded to
//! nearest), which gives Metal's code.
@@ -178,41 +178,6 @@ fn a_code_s_half_is_its_product_s() {
}
}
/// The `half` nearest `n / d` (a quotient in `[2^-14, 1]`, or zero), from the exact quotient:
/// `n` scaled to eleven significant bits over `d`, rounded to nearest even by the remainder.
fn exact_half(n: u64, d: u64) -> f64 {
if n == 0 {
return 0.0;
}
// No quotient but 1 lies near a power of two, so the `f64`'s exponent is the quotient's.
let e = (n as f64 / d as f64).log2().floor() as i32;
assert!(e >= -14, "{n} / {d} is no normal half");
let scaled = n << (10 - e);
let (mut q, r) = (scaled / d, scaled % d);
if 2 * r > d || (2 * r == d && q % 2 == 1) {
q += 1;
}
q as f64 * 2f64.powi(e - 10)
}
/// An 8-bit sRGB destination read in `half` (`blend_srgb8`): the `half` of the `f32` nearest each
/// twelve-bit step over 4095 (the decode of a color byte) and each byte over 255 (alpha's), as the
/// decode gives it correctly rounded, is the `half` nearest the exact quotient: for every step and
/// byte, so the read rounds once, as Metal's.
#[test]
fn an_srgb_step_s_half_is_its_quotient_s() {
for d in [4095u64, 255] {
for n in 0..=d {
let near = n as f32 / d as f32;
assert_eq!(
f64_to_f16(f64::from(near)),
f64_to_f16(exact_half(n, d)),
"{n} / {d}"
);
}
}
}
/// `half_of` rounds to `half` as Metal does under each `half` rounding: to nearest even, half
/// denormals kept, an infinity from 65520 up, the sign of a zero kept. Over every finite `half` of
/// either sign: the `half` itself, the `f32`s beside it, the midpoint to the next `half` up in
@@ -1,330 +0,0 @@
//! A packed 16-bit word attachment's blend on the interpreter: the word read as Metal's blend
//! reads it (`stage_io::word_color::decode`), blended (`extended_range::blend::blend_packed16`),
//! encoded as Metal's word (`stage_io::word_color::encode`), and the fields of the channels the
//! write mask keeps taken from the word read, against words Metal stored. The words are the M3
//! Max's under macOS 27.0.1 (plain Metal, our own MSL, a target loaded with the destination's
//! words): nine states of the packed 16-bit blend sweep (`Blend::packed16`) of every form the
//! planner names (a fused product, a contracted pair, a common factor, a lerp of the blend color,
//! minimum and maximum, write masks of one color channel, of red and alpha, and of all but red),
//! each into every packed 16-bit format from `half4` and `float4` outputs under fast and safe math,
//! over six pixels of the sweep: one with an infinite lane, one past both ends of `[0, 1]`, four
//! inside it.
use super::*;
use crate::lower::arith::extended_range::blend::{blend_packed16, Blend, BlendMath};
use crate::metal::format::WordAttachment;
use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat as P};
use crate::pipeline::lower_inputs::BlendEquation;
/// The pixels: the output's four lanes (as `f32` bits) and the destination's word.
const PIXELS: [([u32; 4], u16); 6] = [
([0x3f2dcb14, 0x3d46318c, 0x3df3cf3d, 0xff800000], 0x4955),
([0x3f2cee30, 0xbe679b5a, 0x3eefbefc, 0x3ff7099d], 0xcae6),
([0x3f1b0000, 0x3df42000, 0x3f54c000, 0x3f362000], 0x68b4),
([0x3eb7870d, 0x3ebb68d0, 0x3ebcc000, 0x3f2b2000], 0x06ad),
([0x3e082000, 0x3f665d72, 0x3f5fa000, 0x3f7aa000], 0x844b),
([0x3d088889, 0x3f154000, 0x3e972000, 0x3f02c000], 0x3165),
];
/// The states: source and destination factors and operation of color, then alpha (Metal's
/// enumerations), the write mask, and the blend color (as `f32` bits).
const STATES: [([u32; 7], [u32; 4]); 9] = [
(
[1, 5, 0, 1, 5, 0, 15],
[0x3e99999a, 0x3f19999a, 0x3f666666, 0x3ee66666],
),
(
[4, 5, 0, 1, 5, 0, 15],
[0x3e99999a, 0x3f19999a, 0x3f666666, 0x3ee66666],
),
(
[14, 14, 0, 14, 1, 3, 4],
[0x3f76ceb7, 0x3e9e8f0f, 0x3ec3fe9a, 0x3da46ba8],
),
(
[11, 3, 0, 7, 14, 4, 15],
[0x3ee6c29e, 0x3f92f0c0, 0x3f3abf47, 0x3e9e5b86],
),
(
[5, 6, 2, 14, 7, 1, 15],
[0x3ec91e09, 0x3f2e55d9, 0xbe263f9d, 0x3f9d77bb],
),
(
[11, 2, 2, 11, 13, 1, 15],
[0x3e9b4ea9, 0x3f017c31, 0x3e62035b, 0x3df4d713],
),
(
[1, 1, 4, 1, 1, 4, 15],
[0x3e99999a, 0x3f19999a, 0x3f666666, 0x3ee66666],
),
(
[13, 12, 4, 14, 13, 0, 9],
[0x3e9b462a, 0xbdd04230, 0x3f403c27, 0x3eb75716],
),
(
[11, 11, 2, 9, 2, 1, 7],
[0x3f10cf42, 0x3e591def, 0xbe1e5284, 0x3f7b28e6],
),
];
/// Metal's words, one row each: the state, the format, the output (`half4` or `float4`), the math
/// (fast or safe), and the word each pixel stored, in hex.
const WORDS: &str = "\
0 B5G6R5 half fast f1b9 a80f b93f 5d30 273b 254c
0 B5G6R5 half safe f1b9 a80f b93f 5d30 273b 254c
0 B5G6R5 float fast f1b9 a80f b93f 5d30 273b 254c
0 B5G6R5 float safe f1b9 a80f b93f 5d30 273b 254c
0 A1BGR5 half fast f1dd a81f b93f 5d27 2737 2565
0 A1BGR5 half safe f1dd a81f b93f 5d27 2737 2565
0 A1BGR5 float fast f1dd a81f b93f 5d27 2737 2565
0 A1BGR5 float safe f1dd a81f b93f 5d27 2737 2565
0 ABGR4 half fast ea75 a07f b4fc 579e 2edf 297a
0 ABGR4 half safe ea75 a07f b4fc 579e 2edf 297a
0 ABGR4 float fast ea75 a07f b4fc 579e 2edf 297a
0 ABGR4 float safe ea75 a07f b4fc 579e 2edf 297a
0 BGR5A1 half fast 7d79 d40f e8bf ae50 939b 9eec
0 BGR5A1 half safe 7d79 d40f e8bf ae50 939b 9eec
0 BGR5A1 float fast 7d79 d40f e8bf ae50 939b 9eec
0 BGR5A1 float safe 7d79 d40f e8bf ae50 939b 9eec
1 B5G6R5 half fast 4955 a80f 88f8 3c2c 271b 1b07
1 B5G6R5 half safe 4955 a80f 88f8 3c2c 271b 1b07
1 B5G6R5 float fast 4955 a80f 88f8 3c2c 271b 1b07
1 B5G6R5 float safe 4955 a80f 88f8 3c2c 271b 1b07
1 A1BGR5 half fast 4955 a81f 88f5 3c1f 2737 1b1b
1 A1BGR5 half safe 4955 a81f 88f5 3c1f 2737 1b1b
1 A1BGR5 float fast 4955 a81f 88f5 3c1f 2737 1b1b
1 A1BGR5 float safe 4955 a81f 88f5 3c1f 2737 1b1b
1 ABGR4 half fast 4955 a07f 84cc 467e 2ddf 255a
1 ABGR4 half safe 4955 a07f 84cc 467e 2ddf 255a
1 ABGR4 float fast 4955 a07f 84cc 467e 2ddf 255a
1 ABGR4 float safe 4955 a07f 84cc 467e 2ddf 255a
1 BGR5A1 half fast 4955 d40f d498 a1ec 937b 99e7
1 BGR5A1 half safe 4955 d40f d498 a1ec 937b 99e7
1 BGR5A1 float fast 4955 d40f d498 a1ec 937b 99e7
1 BGR5A1 float safe 4955 d40f d498 a1ec 937b 99e7
2 B5G6R5 half fast 4995 caa6 6994 07ed 87eb 3585
2 B5G6R5 half safe 4995 caa6 6994 07ed 87eb 3585
2 B5G6R5 float fast 4995 caa6 6994 07ed 87eb 3585
2 B5G6R5 float safe 4995 caa6 6994 07ed 87eb 3585
2 A1BGR5 half fast 4995 caa6 6974 07ed 87cb 3565
2 A1BGR5 half safe 4995 caa6 6974 07ed 87cb 3565
2 A1BGR5 float fast 4995 caa6 6974 07ed 87cb 3565
2 A1BGR5 float safe 4995 caa6 6974 07ed 87cb 3565
2 ABGR4 half fast 4955 c9e6 69b4 0bad 8f4b 3965
2 ABGR4 half safe 4955 c9e6 69b4 0bad 8f4b 3965
2 ABGR4 float fast 4955 c9e6 69b4 0bad 8f4b 3965
2 ABGR4 float safe 4955 c9e6 69b4 0bad 8f4b 3965
2 BGR5A1 half fast 4975 caa6 6914 07cd 878b 3365
2 BGR5A1 half safe 4975 caa6 6914 07cd 878b 3365
2 BGR5A1 float fast 4975 caa6 6914 07cd 878b 3365
2 BGR5A1 float safe 4975 caa6 6914 07cd 878b 3365
3 B5G6R5 half fast 61b5 92ee 7196 2f31 8795 352a
3 B5G6R5 half safe 61b5 92ee 7196 2f31 8795 352a
3 B5G6R5 float fast 61b5 92ee 7196 2f31 8795 352a
3 B5G6R5 float safe 61b5 92ee 7196 2f31 8795 352a
3 A1BGR5 half fast 6197 92eb 716f 2f2d 87a9 3527
3 A1BGR5 half safe 6199 92eb 716f 2f2d 87a9 3527
3 A1BGR5 float fast 6197 92eb 716f 2f2d 87a9 3527
3 A1BGR5 float safe 6199 92eb 716f 2f2d 87a9 3527
3 ABGR4 half fast 6965 8adf 69bb 29ad 8eaf 3978
3 ABGR4 half safe 6965 8adf 69bb 29ad 8eaf 3978
3 ABGR4 float fast 6965 8adf 69bb 29ad 8eaf 3978
3 ABGR4 float safe 6965 8adf 69bb 29ad 8eaf 3978
3 BGR5A1 half fast 3d75 beee cd16 9b31 8f95 b2ea
3 BGR5A1 half safe 3d75 beee cd16 9b31 8f95 b2ea
3 BGR5A1 float fast 3d75 beee cd16 9b31 8f95 b2ea
3 BGR5A1 float safe 3d75 beee cd16 9b31 8f95 b2ea
4 B5G6R5 half fast 000b a101 0005 04a2 4223 0800
4 B5G6R5 half safe 000b a101 0005 04a2 4223 0800
4 B5G6R5 float fast 000b a101 0005 04a2 4223 0800
4 B5G6R5 float safe 000b a101 0005 04a2 4223 0800
4 A1BGR5 half fast 0000 a118 001c 0498 4240 080c
4 A1BGR5 half safe 0000 a118 001c 0498 4240 080c
4 A1BGR5 float fast 0000 a118 001c 0498 4240 080c
4 A1BGR5 float safe 0000 a118 001c 0498 4240 080c
4 ABGR4 half fast 0500 a7d0 0440 0150 4110 0000
4 ABGR4 half safe 0500 a7d0 0440 0150 4110 0000
4 ABGR4 float fast 0500 a7d0 0440 0150 4110 0000
4 ABGR4 float safe 0500 a7d0 0440 0150 4110 0000
4 BGR5A1 half fast 004b 2a21 4005 0142 0003 1000
4 BGR5A1 half safe 004b 2a21 4005 0142 0003 1000
4 BGR5A1 float fast 004b 2a21 4005 0142 0003 1000
4 BGR5A1 float safe 004b 2a21 4005 0142 0003 1000
5 B5G6R5 half fast 0002 5800 100b 0102 0844 0000
5 B5G6R5 half safe 0002 5800 100b 0102 0844 0000
5 B5G6R5 float fast 0002 5800 100b 0102 0844 0000
5 B5G6R5 float safe 0002 5800 100b 0102 0844 0000
5 A1BGR5 half fast 0000 580c 1020 010c 0840 0006
5 A1BGR5 half safe 0000 580c 1020 010c 0840 0006
5 A1BGR5 float fast 0000 580c 1020 010c 0840 0006
5 A1BGR5 float safe 0000 580c 1020 010c 0840 0006
5 ABGR4 half fast 0000 5051 1061 0020 0010 0010
5 ABGR4 half safe 0000 5051 1061 0020 0010 0010
5 ABGR4 float fast 0000 5051 1061 0020 0010 0010
5 ABGR4 float safe 0000 5051 1061 0020 0010 0010
5 BGR5A1 half fast 1802 1800 280b 0042 0004 0000
5 BGR5A1 half safe 1802 1800 280b 0042 0004 0000
5 BGR5A1 float fast 1802 1800 280b 0042 0004 0000
5 BGR5A1 float safe 1802 1800 280b 0042 0004 0000
6 B5G6R5 half fast a955 caef 991a 5ead 873b 34a9
6 B5G6R5 half safe a955 caef 991a 5ead 873b 34a9
6 B5G6R5 float fast a955 caef 991a 5ead 873b 34a9
6 B5G6R5 float safe a955 caef 991a 5ead 873b 34a9
6 A1BGR5 half fast a955 cae7 9935 5ead 8737 34a5
6 A1BGR5 half safe a955 cae7 9935 5ead 8737 34a5
6 A1BGR5 float fast a955 cae7 9935 5ead 8737 34a5
6 A1BGR5 float safe a955 cae7 9935 5ead 8737 34a5
6 ABGR4 half fast a955 caef 98cb 56ad 8ddf 3968
6 ABGR4 half safe a955 caef 98cb 56ad 8ddf 3968
6 ABGR4 float fast a955 caef 98cb 56ad 8ddf 3968
6 ABGR4 float safe a955 caef 98cb 56ad 8ddf 3968
6 BGR5A1 half fast 5555 d6ef e8ba aead 939b b249
6 BGR5A1 half safe 5555 d6ef e8ba aead 939b b249
6 BGR5A1 float fast 5555 d6ef e8ba aead 939b b249
6 BGR5A1 float safe 5555 d6ef e8ba aead 939b b249
7 B5G6R5 half fast a955 cae6 98b4 5ead 844b 3165
7 B5G6R5 half safe a955 cae6 98b4 5ead 844b 3165
7 B5G6R5 float fast a955 cae6 98b4 5ead 844b 3165
7 B5G6R5 float safe a955 cae6 98b4 5ead 844b 3165
7 A1BGR5 half fast a954 cae7 98b4 5ead 844b 3165
7 A1BGR5 half safe a954 cae7 98b4 5ead 844b 3165
7 A1BGR5 float fast a954 cae7 98b4 5ead 844b 3165
7 A1BGR5 float safe a954 cae7 98b4 5ead 844b 3165
7 ABGR4 half fast a952 caec 98b8 56ab 844d 3167
7 ABGR4 half safe a952 caec 98b8 56ab 844d 3167
7 ABGR4 float fast a952 caec 98b8 56ab 844d 3167
7 ABGR4 float safe a952 caec 98b8 56ab 844d 3167
7 BGR5A1 half fast 5555 d6e6 68b4 2ead 904b 3165
7 BGR5A1 half safe 5555 d6e6 68b4 2ead 904b 3165
7 BGR5A1 float fast 5555 d6e6 68b4 2ead 904b 3165
7 BGR5A1 float safe 5555 d6e6 68b4 2ead 904b 3165
8 B5G6R5 half fast 4820 c8a0 6800 00c0 8000 3000
8 B5G6R5 half safe 4820 c8a0 6800 00c0 8000 3000
8 B5G6R5 float fast 4820 c8a0 6800 00c0 8000 3000
8 B5G6R5 float safe 4820 c8a0 6800 00c0 8000 3000
8 A1BGR5 half fast 4840 c881 6801 00c0 8000 3000
8 A1BGR5 half safe 4840 c881 6801 00c0 8000 3000
8 A1BGR5 float fast 4840 c881 6801 00c0 8000 3000
8 A1BGR5 float safe 4840 c881 6801 00c0 8000 3000
8 ABGR4 half fast 4200 c203 6105 0000 8000 3003
8 ABGR4 half safe 4200 c203 6105 0000 8000 3003
8 ABGR4 float fast 4200 c203 6105 0000 8000 3003
8 ABGR4 float safe 4200 c203 6105 0000 8000 3003
8 BGR5A1 half fast 4840 48a0 e800 8440 0400 b000
8 BGR5A1 half safe 4840 48a0 e800 8440 0400 b000
8 BGR5A1 float fast 4840 48a0 e800 8440 0400 b000
8 BGR5A1 float safe 4840 48a0 e800 8440 0400 b000
";
#[test]
fn a_packed_word_attachment_blend_stores_metals_words() {
let f4 = vec(float(32), 4);
let u4 = vec(int(32), 4);
let factor = |x: u32| BlendFactor::try_from(x).expect("a factor");
let operation = |x: u32| BlendOperation::try_from(x).expect("an operation");
for row in WORDS.lines() {
let cols: Vec<&str> = row.split_whitespace().collect();
let state: usize = cols[0].parse().expect("a state");
let pf = match cols[1] {
"B5G6R5" => P::B5G6R5Unorm,
"A1BGR5" => P::A1BGR5Unorm,
"ABGR4" => P::ABGR4Unorm,
_ => P::BGR5A1Unorm,
};
let (half, fast) = (cols[2] == "half", cols[3] == "fast");
let words: Vec<u16> = (cols[4..].iter())
.map(|w| u16::from_str_radix(w, 16).expect("a word"))
.collect();
assert_eq!(words.len(), PIXELS.len(), "{row}");
let (st, color) = STATES[state];
let eq = BlendEquation {
source_rgb: factor(st[0]),
destination_rgb: factor(st[1]),
rgb_operation: operation(st[2]),
source_alpha: factor(st[3]),
destination_alpha: factor(st[4]),
alpha_operation: operation(st[5]),
};
let mask = ColorWriteMask::try_from(st[6]).expect("a mask");
let word = WordAttachment::layout(pf).expect("a word layout");
// A channel the format lacks counts as written, as the storage form plans it.
let written = [
ColorWriteMask::RED,
ColorWriteMask::GREEN,
ColorWriteMask::BLUE,
ColorWriteMask::ALPHA,
]
.into_iter()
.zip(word.fields())
.filter(|&(c, f)| mask.contains(c) || f.is_none())
.fold(ColorWriteMask::NONE, |m, (c, _)| m.union(c));
let kept: u32 = [
ColorWriteMask::RED,
ColorWriteMask::GREEN,
ColorWriteMask::BLUE,
ColorWriteMask::ALPHA,
]
.into_iter()
.zip(word.fields())
.filter_map(|(c, f)| f.filter(|_| !mask.contains(c)))
.fold(0, |m, f| m | (((1u32 << f.bits) - 1) << f.shift));
let math = match fast {
true => BlendMath::Fast,
false => BlendMath::Rounded,
};
let what = format!("state {state} {pf:?} half {half} fast {fast}");
let b = Blend::packed16(&eq, written, math).unwrap_or_else(|e| panic!("{what}: {e:?}"));
let cases: Vec<Case> = PIXELS
.iter()
.map(|(s, d)| {
let s =
s.iter()
.map(|&x| match half {
true => (f16_to_f64(f64_to_f16(f64::from(f32::from_bits(x)))) as f32)
.to_bits(),
false => x,
})
.map(u64::from)
.collect();
let c = color.iter().map(|&x| u64::from(x)).collect();
vec![s, vec![u64::from(*d)], c]
})
.collect();
let expected = words;
for q in HALF_FORMS {
check_accept(
&format!("the packed word blend, {what}, half by {q:?}"),
&[f4, int(32), u4],
int(32),
&|fb, x| {
fb.module().set_quantize_form(q);
let d = crate::lower::stage_io::word_color::decode(fb, word, x[1])?;
let color = b.reads_constant().then_some(x[2]);
let v = blend_packed16(fb, &b, (x[0], d), color)?;
let w = crate::lower::stage_io::word_color::encode(fb, word, (f4, v))?;
let u = Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes: 1,
};
let keep = crate::lower::arith::ops::splat(fb, u, u64::from(kept))?;
let write = crate::lower::arith::ops::splat(fb, u, u64::from(!kept))?;
let old = fb.binary(crate::spirv::ir::BinOp::BitwiseAnd, x[1], keep)?;
let new = fb.binary(crate::spirv::ir::BinOp::BitwiseAnd, w, write)?;
fb.binary(crate::spirv::ir::BinOp::BitwiseOr, old, new)
},
&cases,
&|c| {
let i = PIXELS
.iter()
.position(|(_, d)| u64::from(*d) == c[1][0])
.expect("a pixel");
Some(vec![u64::from(expected[i])])
},
&|g, w| g == w,
);
}
}
}
@@ -1,259 +0,0 @@
//! Interpreter tests of a snapshot's codes (`lower::fragment`'s `snapshot`, `SnapshotForm`): the
//! copy's encode of a fetched texel and a read's decode give back every value a fetch of a texel
//! of the form's formats returns: bit for bit but a normalized code's, which a read decodes by the
//! device's arithmetic (`c` times the `f32` nearest `1 / D`, `PrecisionNote::DevicePackConversion`),
//! from the fetch's exact value and from a device's decode an ulp off.
use super::*;
use crate::lower::fragment::{snapshot_decode, snapshot_encode};
use crate::pipeline::sym::SnapshotForm;
fn v4f() -> Form {
vec(float(32), 4)
}
fn v4u() -> Form {
vec(int(32), 4)
}
/// The copy's encode and a read's decode of `form`, back to the input's type.
fn round_trip(form: SnapshotForm) -> impl Fn(&mut FunctionBuilder<'_>, &[Value]) -> BResult<Value> {
move |fb, x| {
let texel = fb.value_ty(x[0])?;
let codes = snapshot_encode(fb, form, x[0])?;
snapshot_decode(fb, form, codes, texel)
}
}
/// `c / d` correctly rounded to `f32`: IEEE division of two integers `f32` holds exactly.
fn exact(c: u32, d: u32) -> u32 {
(c as f32 / d as f32).to_bits()
}
/// A read's decode of code `c` of scale `d`: `c` times the `f32` nearest `1 / d`, at least `-1`.
fn native(c: i64, d: u32) -> u64 {
u64::from((c as f32 * (1.0 / d as f32)).max(-1.0).to_bits())
}
/// Every lane value in `values`, four to a case, the last case padded with the first values.
fn cases(values: &[u64]) -> Vec<Case> {
values
.chunks(4)
.map(|c| {
let mut lanes = c.to_vec();
lanes.extend(values.iter().take(4 - c.len()));
vec![lanes]
})
.collect()
}
/// Bit-for-bit agreement, NaNs included.
fn same(g: u64, w: u64) -> bool {
g == w
}
/// An unsigned normalized code's value, exact or a device's an ulp off its code's (lavapipe's
/// reciprocal), comes back as the device's product `c · fl(1 / (2^b - 1))`, which is not Metal's
/// correctly rounded quotient at some codes.
#[test]
fn unsigned_normalized_codes_come_back() {
for (form, d) in [
(SnapshotForm::Unorm8, 255u32),
(SnapshotForm::Unorm16, 65535),
] {
let step = if d > 255 { 7 } else { 1 };
let codes: Vec<u32> = (0..=d).step_by(step).chain([d - 1, d]).collect();
let values: Vec<u64> = codes.iter().map(|&c| u64::from(exact(c, d))).collect();
let wanted: Vec<u64> = codes.iter().map(|&c| native(i64::from(c), d)).collect();
assert_ne!(
values, wanted,
"{form:?}: the product is the quotient at every code"
);
let body = round_trip(form);
let exact_cases = cases(&values);
let wanted_cases = cases(&wanted);
check_accept(
&format!("{form:?}"),
&[v4f()],
v4f(),
&body,
&exact_cases,
&|c| {
let i = exact_cases.iter().position(|o| o == c)?;
Some(wanted_cases[i][0].clone())
},
&same,
);
// The reciprocal's product, an ulp off on some codes.
let recip = (1.0f32 / d as f32).to_bits();
let off: Vec<u64> = codes
.iter()
.map(|&c| u64::from((c as f32 * f32::from_bits(recip)).to_bits()))
.collect();
let off_cases = cases(&off);
check_accept(
&format!("{form:?} off an ulp"),
&[v4f()],
v4f(),
&body,
&off_cases,
&|c| {
let i = off_cases.iter().position(|o| o == c)?;
Some(wanted_cases[i][0].clone())
},
&same,
);
}
}
/// A signed normalized code's value comes back as the device's product: `max(c · fl(1 /
/// (2^(b-1) - 1)), -1)` for every code, the lowest `-1`.
#[test]
fn signed_normalized_codes_come_back() {
for (form, d) in [
(SnapshotForm::Snorm8, 127u32),
(SnapshotForm::Snorm16, 32767),
] {
let step = if d > 127 { 7 } else { 1 };
let lowest = -(d as i64) - 1;
let codes: Vec<i64> = (lowest..=i64::from(d))
.step_by(step)
.chain([lowest, lowest + 1, -1, 0, 1, i64::from(d)])
.collect();
let values: Vec<u64> = codes
.iter()
.map(|&c| {
let m = exact(c.unsigned_abs().min(u64::from(d)) as u32, d);
let v = if c < 0 { m | 0x8000_0000 } else { m };
u64::from(v)
})
.collect();
let wanted: Vec<u64> = codes
.iter()
.map(|&c| native(c.max(-i64::from(d)), d))
.collect();
let body = round_trip(form);
let value_cases = cases(&values);
let wanted_cases = cases(&wanted);
check_accept(
&format!("{form:?}"),
&[v4f()],
v4f(),
&body,
&value_cases,
&|c| {
let i = value_cases.iter().position(|o| o == c)?;
Some(wanted_cases[i][0].clone())
},
&same,
);
}
}
/// Every half value widened comes back bit for bit, zeros, denormals and infinities, and each NaN a
/// NaN: a read's widening of the code is the device's, whose NaN bits it records
/// (`PrecisionNote::NativeNanEncoding`).
#[test]
fn half_codes_come_back() {
let values: Vec<u64> = (0..=u16::MAX)
.map(|h| {
let b = crate::lower::arith::narrow::f32_of_half_bits(u32::from(h));
u64::from(b)
})
.collect();
let body = round_trip(SnapshotForm::Half);
check_accept(
"Half",
&[v4f()],
v4f(),
&body,
&cases(&values),
&|c| Some(c[0].clone()),
&|g, w| same(g, w) || (is_nan(float(32), g) && is_nan(float(32), w)),
);
}
/// Every integer code comes back: an unsigned one as it is, a signed one sign-extended.
#[test]
fn integer_codes_come_back() {
for (form, bits, signed) in [
(SnapshotForm::Uint8, 8u32, false),
(SnapshotForm::Sint8, 8, true),
(SnapshotForm::Uint16, 16, false),
(SnapshotForm::Sint16, 16, true),
] {
let step = if bits > 8 { 3 } else { 1 };
let values: Vec<u64> = (0..1u64 << bits)
.step_by(step)
.map(|c| match signed {
// Sign-extended into the 32-bit lane.
true => u64::from((((c as u32) << (32 - bits)) as i32 >> (32 - bits)) as u32),
false => c,
})
.collect();
let body = round_trip(form);
check_accept(
&format!("{form:?}"),
&[v4u()],
v4u(),
&body,
&cases(&values),
&|c| Some(c[0].clone()),
&same,
);
}
}
/// The bits form keeps any lanes, NaNs included.
#[test]
fn bits_come_back() {
let values: Vec<u64> = [
0u32,
1,
0x7FC0_0000,
0xFFFF_FFFF,
0x8000_0000,
0x3F80_0000,
0x7F80_0001,
]
.iter()
.map(|&b| u64::from(b))
.collect();
let body = round_trip(SnapshotForm::Bits);
check_accept(
"Bits",
&[v4f()],
v4f(),
&body,
&cases(&values),
&|c| Some(c[0].clone()),
&same,
);
}
/// What the copy's fetch of the slot's own image loses on a device whose `f32` decode
/// canonicalizes a NaN: every NaN code's texel arrives as `0x7fc00000`, which `encode` stores as
/// the one code `0x7e00`, so the read hands back that one quiet positive NaN for all 2,046 of
/// them: the bound `PrecisionNote::DeviceNanEncoding` states for a 16-bit float texel's read.
#[test]
fn a_canonicalized_nan_loses_its_code() {
let canonical = u64::from(f32::NAN.to_bits());
assert_eq!(canonical, 0x7FC0_0000);
let body = round_trip(SnapshotForm::Half);
let widened = crate::lower::arith::narrow::f32_of_half_bits(0x7E00);
check_accept(
"a canonicalized NaN",
&[v4f()],
v4f(),
&body,
&[vec![vec![canonical; 4]]],
&|_| Some(vec![u64::from(widened); 4]),
&same,
);
// No NaN code's own widening is that value, so the code is gone, not merely requantized.
let kept = (0..=u16::MAX)
.filter(|h| h & 0x7C00 == 0x7C00 && h & 0x3FF != 0)
.filter(|h| crate::lower::arith::narrow::f32_of_half_bits(u32::from(*h)) == widened)
.count();
assert_eq!(kept, 1, "only `0x7e00` widens to the canonical NaN");
}
+1 -8
View File
@@ -219,11 +219,6 @@ pub struct EmitCx<'a> {
/// `stage_io::emit_draw_entry` finds before the body and before any other hook reads it
/// (`stage_io::StageIoPlan::merged_fragment`), defined in the function's straight-line entry.
pub(crate) merged_fragment_table: Option<SValue>,
/// The texel of each storage-form color attachment a fragment function reads, by Metal
/// color index, at the invocation's pixel (and sample), which `fragment::emit_entry` reads
/// before the body: defined in the function's straight-line entry, inside the interlock, so
/// every use of the color in a later block takes the one texel (`fragment::fetch::value`).
pub(crate) fetched: Vec<(u32, SValue)>,
}
/// A value that is the same wherever an invocation computes it, so a block computes it once, and
@@ -286,7 +281,6 @@ impl<'a> EmitCx<'a> {
sampling: Default::default(),
merged_draw: None,
merged_fragment_table: None,
fetched: Vec::new(),
}
}
@@ -864,7 +858,6 @@ impl<'a> Emitter<'a> {
sampling: Default::default(),
merged_draw: None,
merged_fragment_table: None,
fetched: Vec::new(),
},
vars: None,
phis,
@@ -1471,7 +1464,7 @@ impl CodeEmitter for Emitter<'_> {
fn on_return(&mut self, v: Option<ValueId>, fb: &mut FunctionBuilder<'_>) -> BResult<()> {
stage_io::emit_return(&mut self.cx, fb, v)?;
fragment::emit_return(&mut self.cx, fb, v)
fragment::emit_return(&mut self.cx, fb)
}
}
+13 -83
View File
@@ -38,9 +38,9 @@
//!
//! **An extended-range attachment** (`metal::format::ExtendedRange`) holds Metal's raw texels in
//! its raw unsigned format: its input attachment is of `uint` texels, and a read decodes the texel
//! to Metal's tile value (`arith::extended_range::tile_value`), as the storage form's does. A read
//! to Metal's tile value (`arith::extended_range::tile_value`). A read
//! of one of Apple's extended-range forms (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their
//! `_sRGB` twins) is not implemented, on either device (`Feature::Format`, at the attachment):
//! `_sRGB` twins) is not implemented, on every device (`Feature::Format`, at the attachment):
//! Metal's tile holds such an attachment as `half` through the pass, which the codes an earlier
//! draw stored do not keep (`fetch::codes_round_the_tile`); a padded one's is built. The
//! interface records the attachment (`StageIo::extended_range_colors`), so link holds a stage
@@ -53,8 +53,7 @@
//! precision, where Metal decodes a color byte to its twelve-bit step over 4095. The interface
//! records each `float` color it reads so (`StageIo::decoded_fetches`), and a render pipeline whose
//! attachment there has such a format records `PrecisionNote::SrgbTexelDecode`
//! (`color_writes::pipeline_writes`). The interlocked storage form reads the attachment's bytes, no
//! sRGB view of them, and decodes them by Metal's table itself (`fetch`).
//! (`color_writes::pipeline_writes`).
//!
//! **An `A8Unorm` attachment whose image holds Metal's alpha in red** (`R8_UNORM` on a device
//! without `A8_UNORM`, `LoweringInputs::alpha_in_red_colors`) reads `(r, 0, 0, 1)` through its
@@ -71,13 +70,10 @@
use std::collections::BTreeMap;
use crate::air::abi::{AbiInt, OutputRole, ParamBinding, ParamRole};
use crate::air::abi::{AbiInt, ParamBinding, ParamRole};
use crate::air::ir::{ArgIdx, TypeId as AirTypeId, Value};
use crate::device::requirements::VkFeature;
use crate::error::{
Attachment, Capability, DescriptorError, Error, Feature, MetalAnswer, Unsupported,
};
use crate::error::{Attachment, DescriptorError, Error, Feature, MetalAnswer, Unsupported};
use crate::lower::arith::legal::{form_on, refuse_int64_interface};
use crate::lower::arith::{extended_range, narrow, ops, Form, Held};
use crate::lower::emit::EmitCx;
@@ -159,11 +155,9 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<Co
};
let form = param_form(cx, b)?;
let extended = cx.inputs.extended_range_colors.get(&color).copied();
// A word attachment's input reads the word. Where the interlocked storage form took the
// attachment, its read decodes a packed 16-bit word, Metal's value, and refuses the other two
// kinds (`fetch::select_read`); the input attachment form, whose attachment is the word
// itself, decodes none.
if cx.inputs.word_colors.contains_key(&color) && !super::fetch::is_storage(cx, color) {
// A word attachment's input reads the word: the input attachment form, whose attachment is the
// word itself, decodes none.
if cx.inputs.word_colors.contains_key(&color) {
let refused = Unsupported::not_implemented(Feature::Format);
return Err(refused.at_attachment(Attachment::Color(color)).into());
}
@@ -192,18 +186,9 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<Co
extended: extended.map(|e| e.form),
alpha_red: cx.inputs.alpha_in_red_colors.contains(&color),
};
// The interlocked storage form `fetch::plan` chose.
if super::fetch::is_storage(cx, color) {
super::fetch::select_read(cx, input)?;
return Ok(input);
}
// On a device with the pixel interlock `fetch::plan` refused a blocked attachment already. On
// one with neither ordered form the input attachment is ordered between draws alone, by the
// consumer's barriers: overlapping fragments of one draw are not.
// On a device without rasterization-order access the input attachment is ordered between
// draws alone, by the consumer's barriers: overlapping fragments of one draw are not.
if !frag.rasterization_order_color_access {
if !super::fetch::fetch_unordered(cx.profile) {
return Err(unordered(cx, color));
}
cx.precision.insert(PrecisionNote::UnorderedFetchWithinDraw);
}
// Under the identity domains on such a device no descriptor holds the attachment: the function
@@ -306,40 +291,6 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<Co
Ok(input)
}
/// The refusal of a read of color attachment `color` that no ordered form serves on the device:
/// either rasterization-order access, or the pixel interlock (with fragment stores where the
/// function writes the attachment) for the storage form.
fn unordered(cx: &SelectCx<'_>, color: u32) -> Error {
let f = cx.profile.fields();
let writes = cx.entry.ep.outputs.iter().any(|o| {
matches!(
o.role,
OutputRole::RenderTarget {
attachment: AbiInt::Const(a),
index: 0,
..
} if a == color
)
});
let mut interlock = Vec::new();
if !super::fetch::interlock_forms(cx.profile) {
interlock.push(Capability::Feature(VkFeature::FragmentShaderPixelInterlock));
}
if writes && !f.leaf.fragment_stores_and_atomics {
interlock.push(Capability::Feature(VkFeature::FragmentStoresAndAtomics));
}
Unsupported::needs_any_of(
Feature::FramebufferFetch,
vec![
vec![Capability::Feature(
VkFeature::RasterizationOrderColorAttachmentAccess,
)],
interlock,
],
)
.into()
}
/// The set-1 class of the element a color input of `form` reads attachment `color` through under
/// the identity domains (`PushField::FetchedColor`): a sampled 2D image, multisampled in a
/// multisampled pipeline, of `float` texels for a float read and of the attachment's own integer
@@ -393,9 +344,7 @@ pub(crate) fn texture_decl(class: ImageHandleClass) -> ImageDecl {
}
/// Declare one input attachment per color index the plan reads, multisampled for a per-sample
/// function (`multisampled`), or its storage image in the interlocked storage form (`fetch`), which
/// holds the samples as its view states; the storage image of every other attachment in that form
/// (one the function only writes); the input attachment of every extended-range attachment whose
/// function (`multisampled`); the input attachment of every extended-range attachment whose
/// blend the function computes over it (`input_blend`) and that of every word attachment whose
/// word the function merges into the texel's (`word_input`), of `uint` texels; and that of every
/// attachment held with its channels rotated whose blend the function computes over it
@@ -405,11 +354,7 @@ pub(crate) fn texture_decl(class: ImageHandleClass) -> ImageDecl {
pub(super) fn declare(
mb: &mut ModuleBuilder,
colors: &[ColorInput],
(storage, blends, merges): (
&BTreeMap<u32, super::fetch::StorageColor>,
&BTreeMap<u32, super::InputBlend>,
&BTreeMap<u32, u32>,
),
(blends, merges): (&BTreeMap<u32, super::InputBlend>, &BTreeMap<u32, u32>),
(rotated, logic): (
&BTreeMap<u32, super::RotatedInputBlend>,
&BTreeMap<u32, super::LogicInput>,
@@ -424,21 +369,10 @@ pub(super) fn declare(
if out.contains_key(&c.color) || textured.contains_key(&c.color) {
continue;
}
if let Some(sc) = storage.get(&c.color) {
out.insert(c.color, super::fetch::declare(mb, c.color, sc)?);
continue;
}
// An extended-range attachment's image holds the raw format's `uint` texels.
let float = c.form.is_float() && c.extended.is_none();
out.insert(c.color, input_attachment(mb, c.color, float, multisampled)?);
}
// A storage-form attachment the function writes without reading it: an extended-range
// attachment whose blend the shader computes from the texel.
for (&color, sc) in storage {
if let std::collections::btree_map::Entry::Vacant(e) = out.entry(color) {
e.insert(super::fetch::declare(mb, color, sc)?);
}
}
let blended = blends.iter().filter(|(_, ib)| ib.reads()).map(|(&c, _)| c);
for color in blended.chain(merges.keys().copied()) {
if let std::collections::btree_map::Entry::Vacant(e) = out.entry(color) {
@@ -497,16 +431,12 @@ fn input_attachment(
/// The value of color input `c` in its lowered representation, at the invocation's sample for a
/// per-sample function: an input attachment's read at each use (the use may sit in a construct
/// whose values do not dominate the rest of the block), a storage-form attachment's from the
/// texel the function read before its body (`fetch::value`).
/// whose values do not dominate the rest of the block).
pub(super) fn value(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
c: ColorInput,
) -> BResult<SValue> {
if cx.plan.families.fragment.fetch.contains_key(&c.color) {
return super::fetch::value(cx, fb, c);
}
let texel = match c.extended {
Some(form) => {
let texel = input_texel(cx, fb, c.color)?;
@@ -172,13 +172,6 @@ fn contribution(cx: &SelectCx<'_>, id: InstId, inst: &Inst) -> Reach {
Reach(r)
}
/// Whether instruction `id` writes memory another invocation or a later command can read: a
/// store, atomic, image write, or copy outside `Thread` memory, or a call the walk cannot see
/// into (the interlocked framebuffer fetch's early-test rule).
pub(super) fn side_effect(cx: &SelectCx<'_>, id: InstId, inst: &Inst) -> bool {
contribution(cx, id, inst).has(Reach::SIDE_EFFECT)
}
/// Whether instruction `id` is tangled (a derivative, an implicit-LOD sample, a quad or subgroup
/// operation, a barrier) or a non-quad subgroup operation: what tells the invocations of a quad
/// apart from each other (the loop over the covered samples). Valid once every instruction is
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,914 +0,0 @@
//! Fragment imageblocks: `[[imageblock_data]]` inputs and outputs of a fragment function.
//!
//! **What Metal gives.** A render pass keeps an imageblock in tile memory: one cell per pixel for
//! the whole pass, of the explicit layout's `air.imageblock_data_size` bytes, undefined when the
//! pass begins, and shared by every pipeline of the pass. A fragment function reads a *view* of
//! its pixel's cell as a struct parameter (`air.imageblock_data` input) and writes a view as a
//! member of its returned struct (`air.imageblock_data` output). A view's members name members of
//! the *master* layout (`air.imageblock_master`; the view's own layout when it has none) by their
//! user key, the fifth string of each member tuple (`Member::key`; MSL §4.7.1: `[[user(name)]]`,
//! else the declared name, "must match a data member declared in the master"), and each member
//! lives at its master offset. The master's fingerprint (SHA-256 of its data size and its
//! layout's Merkle digest over each member's offset, size, array length, key, and nested
//! layout's digest, each shared layout hashed once) is the fact's and
//! `FragmentImageblock::master`: a consumer draws only pipelines of one master in a pass.
//! Explicit imageblock layouts cannot alias color attachments (no `[[color(n)]]` member, MSL
//! §4.7), and in a fragment function every master member names a raster order group, which
//! orders the accesses of overlapping fragments in primitive order.
//!
//! **The representation** (`ImageblockMechanism::StorageImageInterlock`). The pass's imageblock
//! is one coherent `R32Uint` 2D-array storage image, `SyntheticBinding::Imageblock`: layer `w`
//! holds word `w` of every pixel's cell, the cell of pixel `(x, y)` at texel `(x, y)`, which the
//! function takes from `FragCoord`. The input view is read once, member by member, in the
//! function's first block ([`emit_entry`]); the output view is written member by member at the
//! return ([`emit_return`]), each member a leaf of the cell's words (`memory::leaf`, a sub-word
//! member replaces only its bytes). The whole body runs inside the ordered pixel-interlock critical
//! section (`fragment::rog`), so the read, the body, and the write of each fragment are one step in
//! primitive order against every other fragment of the pixel, across draws, and its accesses'
//! device-scope coherence (the `Coherent` image under `GLSL450`, `MakeTexel*` under the Vulkan
//! model: `sync::memory_model`) makes each critical section's writes visible to the next one. That
//! is Metal's raster order group ordering, and more (groups only relax it).
//!
//! A discarded fragment writes nothing: a demoted invocation's image writes have no effect, a
//! terminate-form discard returns before the write, and a predicated one skips the write
//! (`discarded`). Nor does a fragment whose returned `[[sample_mask]]` does not cover its one
//! sample (bit 0 clear; the mask's other bits do not keep it): Metal drops the fragment and its
//! imageblock write with it (measured on the M3 Max and an M4), so the write is guarded by the
//! returned mask's bit 0 ([`ImageblockPlan::mask`]).
//!
//! **Two masters.** The input and output views may view different masters: each view's members
//! live at its own master's offsets of the one cell, which spans the largest master (measured on
//! the M3 Max and an M4, a `half` read at byte 0 of one master and written through a smaller master
//! that keys it at byte 2, and back, each reached those bytes and kept the rest). The fact's master
//! is the largest's.
//!
//! **Refused.** A profile without `fragmentShaderPixelInterlock` is
//! `Unsupported{Imageblocks, Feature(FragmentShaderPixelInterlock)}`; an output without
//! `fragmentStoresAndAtomics` names that feature. Not implemented: a second input or output view,
//! an output aliasing the implicit imageblock (`air.alias_implicit_imageblock`: it is the color
//! attachments' storage; an aliased input never reaches this family, `select::param_family`
//! refuses it as `TileShading`), a member that is an array or a struct, names a color
//! attachment, or whose value is wider than its slot, a view member without exactly one master
//! member of its size, a view struct field no member covers, and a view without a data size.
//! Link refuses what the one plane does not
//! model (multisampling, and a write that alpha to coverage, or a late depth or stencil test, can
//! drop: `pipeline::link::imageblock`), and the binder a layered or amplified pass. A packed
//! pixel-format member (`_pixel_type`) is refused before this family plans it, by its conversion
//! (`Lowering(Arith)` or `UnknownIntrinsic`).
use std::collections::BTreeMap;
use sha2::{Digest, Sha256};
use crate::air::abi::{ImageblockArg, ImageblockKind, Member, OutputRole, StructInfo, StructRef};
use crate::air::container::Hash256;
use crate::air::ir::{ArgIdx, Type, TypeId as AirTypeId, Value};
use crate::device::requirements::VkFeature;
use crate::error::{Capability, Error, Feature, Unsupported};
use crate::lower::emit::EmitCx;
use crate::lower::select::SelectCx;
use crate::lower::stage_io::{self, Returned};
use crate::lower::sync::memory_model;
use crate::memory::leaf::{self, k32, Coherence, Leaf, WordMem};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, SyntheticBinding};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{DemoteTy, GlobalId, Value as SValue};
use crate::spirv::ir::{
BinOp, ConvOp, Dim, ImageOperands, ImageType, ImageUsage, MemAccess, StorageClass,
Type as SType, UnOp,
};
fn not_implemented() -> Error {
Unsupported::not_implemented(Feature::Imageblocks).into()
}
/// The device capabilities a function that reads (and, when `writes`, writes) the imageblock
/// needs: the ordered pixel interlock, and stores in the fragment stage for a write. A missing
/// one refuses the function naming every missing one.
fn require(cx: &SelectCx<'_>, writes: bool) -> Result<(), Error> {
let f = cx.profile.fields();
let mut missing = Vec::new();
if !super::fetch::interlock_forms(cx.profile) {
missing.push(Capability::Feature(VkFeature::FragmentShaderPixelInterlock));
}
if writes && !f.leaf.fragment_stores_and_atomics {
missing.push(Capability::Feature(VkFeature::FragmentStoresAndAtomics));
}
if missing.is_empty() {
return Ok(());
}
Err(Unsupported::needs_any_of(Feature::Imageblocks, vec![missing]).into())
}
/// One member of a view: the view struct's field that holds it, its leaf, and its byte offset
/// in the cell (the master layout's).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ViewMember {
pub field: u32,
pub leaf: Leaf,
pub offset: u32,
}
/// A view of the imageblock: the members of its struct value, and the struct's lowered type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct View {
pub members: Vec<ViewMember>,
pub ty: DemoteTy,
}
/// The fragment imageblock part of the fragment family's plan.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ImageblockPlan {
/// The 32-bit words of a cell the views reach: the largest data size, rounded up to a word.
pub words: u32,
/// The bytes of a cell (`air.imageblock_data_size`), the largest over the views.
pub data_size: u32,
/// The alignment Metal states for the views (`air.arg_type_align_size`, their master
/// layout's), the largest: what Metal's pipeline aligns the color attachments' bytes beside
/// the cell to (`FragmentImageblock::alignment`).
pub alignment: u32,
/// The input view and the LLVM parameter that holds it.
pub input: Option<(u32, View)>,
/// The output view and the returned struct's field that holds it.
pub output: Option<(u32, View)>,
/// The stage interface's `FragCoord` object, which gives the pixel.
pub coord: usize,
/// The fingerprint of the master layout of the most bytes the function's views view
/// (`fingerprint`; the first planned of equal size).
pub master: Option<Hash256>,
/// The returned struct's field holding the `[[sample_mask]]` the function returns beside an
/// output view: the write is kept only where the mask covers the invocation's sample.
pub mask: Option<u32>,
/// The stage interface's `SampleId` object of a function compiled for a multisampled
/// pipeline (`LoweringInputs::multisampled`), which runs once per covered sample and reaches
/// its own sample's cell: words `sample * words` on.
pub sample: Option<usize>,
/// The module declares early fragment tests, which the function does not, so that a depth or
/// stencil test the fragment fails drops its write as Metal's does ([`plan_tests`]).
pub early_tests: bool,
}
/// The alignment a constant byte offset guarantees (at most 16).
fn offset_align(offset: u32) -> u64 {
1u64 << offset.trailing_zeros().min(4)
}
/// The layout of struct reference `r`.
fn layout<'a>(cx: &'a SelectCx<'_>, r: StructRef) -> Result<&'a StructInfo, Error> {
cx.entry
.structs
.get(r.0 as usize)
.ok_or_else(|| cx.invariant("an imageblock layout out of range"))
}
/// The master member view member `m` names: the one whose user key equals `m`'s (MSL §4.7.1,
/// the Metal view-matching ABI), which must be unique and of `m`'s size.
fn master_member<'a>(master: &'a StructInfo, m: &Member) -> Result<&'a Member, Error> {
let mut named = master.members.iter().filter(|x| x.key == m.key);
match (named.next(), named.next()) {
(Some(x), None) if x.size == m.size && x.array_len == 0 && x.layout.is_none() => Ok(x),
_ => Err(not_implemented()),
}
}
/// The fingerprint of master layout `master` of a cell of `data_size` bytes, over the module's
/// layouts `structs`, and how many layouts it hashed; `None` when a layout reference is out of
/// range or the layouts nest in a cycle.
///
/// It is SHA-256 over the data size and the master's Merkle digest: a layout's digest is SHA-256
/// over its member count and, in declaration order, each member's offset, size, array length,
/// and user key, and a nested member's layout digest. Decoded layouts are shared by reference (a
/// DAG), so each is hashed once (`memo`): the work is linear in the distinct layouts the master
/// reaches, however deep they nest. Equal fingerprints are structurally equal masters, whatever
/// metadata nodes state them.
fn fingerprint(
structs: &[StructInfo],
master: StructRef,
data_size: u32,
) -> Option<(Hash256, usize)> {
let mut memo: BTreeMap<StructRef, Hash256> = BTreeMap::new();
// Each frame is a layout and its first member whose nested layout is not hashed yet.
let mut stack = vec![(master, 0usize)];
while let Some(&(r, next)) = stack.last() {
let s = structs.get(usize::try_from(r.0).ok()?)?;
let pending = s
.members
.iter()
.enumerate()
.skip(next)
.find_map(|(i, m)| m.layout.filter(|l| !memo.contains_key(l)).map(|l| (i, l)));
if let Some((at, child)) = pending {
// A layout on the stack twice nests in itself.
if stack.len() > structs.len() {
return None;
}
if let Some(top) = stack.last_mut() {
top.1 = at;
}
stack.push((child, 0));
continue;
}
stack.pop();
if memo.contains_key(&r) {
continue;
}
let mut h = Sha256::new();
h.update((s.members.len() as u64).to_le_bytes());
for m in &s.members {
for n in [m.offset, m.size, m.array_len] {
h.update(n.to_le_bytes());
}
h.update((m.key.0.len() as u64).to_le_bytes());
h.update(&m.key.0);
match m.layout.and_then(|l| memo.get(&l)) {
Some(d) => {
h.update([1]);
h.update(d);
}
None => h.update([0]),
}
}
memo.insert(r, h.finalize().into());
}
let mut h = Sha256::new();
h.update(data_size.to_le_bytes());
h.update(memo.get(&master)?);
Some((h.finalize().into(), memo.len()))
}
/// The cell a view reaches: its master's data size, the alignment Metal states for the view
/// (`air.arg_type_align_size`: its master layout's, a view of part of a master included), and
/// the master's `fingerprint`.
#[derive(Clone, Copy)]
struct Reached {
data_size: u32,
alignment: u32,
master: Hash256,
}
/// The view of AIR struct type `ty` that imageblock argument `ib` of stated alignment `align`
/// (`air.arg_type_align_size`) describes, and the cell it reaches. Metal's compiler states the
/// alignment of every view, its master layout's; a view that states none (hand-written AIR)
/// takes its own layout's ABI alignment, which is the master's where the view is its master.
/// A stated alignment that is not a power of two is not implemented.
fn view(
cx: &SelectCx<'_>,
ty: AirTypeId,
ib: &ImageblockArg,
align: Option<u32>,
) -> Result<(View, Reached), Error> {
if ib.kind != ImageblockKind::Data {
return Err(cx.invariant("a fragment imageblock of another kind"));
}
// An imageblock aliasing the implicit one is the color attachments' own storage, which the
// side image is not.
if ib.alias_implicit {
return Err(not_implemented());
}
let data_size = ib
.data_size
.filter(|n| *n > 0)
.ok_or_else(not_implemented)?;
let own = ib.layout.ok_or_else(not_implemented)?;
let view_layout = layout(cx, own)?;
let master_ref = ib.master.unwrap_or(own);
let master = layout(cx, master_ref)?;
// An explicit layout holds no color attachment (MSL §4.7); a member that names one is the
// implicit imageblock's, which the side image is not.
let color = |s: &StructInfo| s.members.iter().any(|m| m.render_target.is_some());
if color(view_layout) || color(master) {
return Err(not_implemented());
}
let fields = match cx.entry.module.types().get(ty) {
Some(Type::Struct {
fields,
packed: false,
..
}) => fields.clone(),
_ => return Err(not_implemented()),
};
let offsets = cx
.memory
.layouts
.field_offsets(ty)
.ok_or_else(not_implemented)?
.to_vec();
if view_layout.members.len() != fields.len() {
return Err(not_implemented());
}
let mut members = Vec::with_capacity(fields.len());
for m in &view_layout.members {
if m.array_len != 0 || m.layout.is_some() {
return Err(not_implemented());
}
// The view member is the struct field at its offset in the view.
let field = offsets
.iter()
.position(|o| *o == u64::from(m.offset))
.ok_or_else(not_implemented)?;
if members
.iter()
.any(|x: &ViewMember| x.field as usize == field)
{
return Err(not_implemented());
}
let field_ty = *fields.get(field).ok_or_else(not_implemented)?;
let at = master_member(master, m)?;
let leaf = leaf::leaf_of(
cx.entry,
cx.profile,
&cx.memory.layouts,
field_ty,
offset_align(at.offset),
offset_align(at.offset),
)?;
// A value wider than its slot is a packed pixel-format member, which Metal converts.
if leaf.bytes > at.size
|| at
.offset
.checked_add(leaf.bytes)
.is_none_or(|e| e > data_size)
{
return Err(not_implemented());
}
members.push(ViewMember {
field: field as u32,
leaf,
offset: at.offset,
});
}
let alignment = match align {
Some(stated) => stated,
None => cx
.memory
.layouts
.abi_align(ty)
.and_then(|a| u32::try_from(a).ok())
.ok_or_else(not_implemented)?,
};
if !alignment.is_power_of_two() {
return Err(not_implemented());
}
let lowered = crate::lower::arith::lowered_type(cx.entry, cx.profile, ty)?;
let (master, _) = fingerprint(&cx.entry.structs, master_ref, data_size)
.ok_or_else(|| cx.invariant("an imageblock master whose layouts do not resolve"))?;
let cell = Reached {
data_size,
alignment,
master,
};
Ok((
View {
members,
ty: lowered,
},
cell,
))
}
/// Plan the imageblock storage the function reaches with a view of `cell`. Views of structurally
/// different masters each reach their own master's offsets of the one cell, which spans the
/// largest of them (measured on the M3 Max and an M4).
fn reach(cx: &mut SelectCx<'_>, cell: Reached) -> Result<(), Error> {
if cx.stage != Stage::Fragment {
return Err(cx.invariant("a fragment imageblock outside a fragment function"));
}
let known = cx.families.fragment.imageblock.is_some();
let coord = stage_io::frag_coord(cx);
// Metal keeps a multisampled pass's imageblock per sample, and runs a function that reaches
// it once per covered sample, each run its own sample's cell (measured on the M3 Max).
let sample = if cx.inputs.multisampled {
if !cx.profile.fields().fragment.sample_rate_shading {
return Err(Unsupported::needs(
Feature::Imageblocks,
Capability::Feature(VkFeature::SampleRateShading),
)
.into());
}
Some(stage_io::sample_id(cx))
} else {
None
};
let ib = cx
.families
.fragment
.imageblock
.get_or_insert_with(ImageblockPlan::default);
if ib.master.is_none() || cell.data_size > ib.data_size {
ib.master = Some(cell.master);
}
ib.coord = coord;
ib.sample = sample;
ib.words = ib.words.max(cell.data_size.div_ceil(4));
ib.data_size = ib.data_size.max(cell.data_size);
ib.alignment = ib.alignment.max(cell.alignment);
if !known {
cx.descriptors.storage_images = cx.descriptors.storage_images.saturating_add(1);
}
Ok(())
}
/// Plan the imageblock input parameter `param` of role `ib` and stated alignment `align`.
pub(super) fn select_input(
cx: &mut SelectCx<'_>,
param: u32,
ib: &ImageblockArg,
align: Option<u32>,
) -> Result<(), Error> {
let v = Value::Arg(ArgIdx::new(param));
let ty = cx
.value_ty(v)
.ok_or_else(|| cx.invariant("an imageblock parameter without a type"))?;
let (view, cell) = view(cx, ty, ib, align)?;
require(cx, false)?;
reach(cx, cell)?;
let plan = cx
.families
.fragment
.imageblock
.as_mut()
.ok_or_else(|| invariant_error("an imageblock without its plan"))?;
if plan.input.is_some() {
return Err(not_implemented());
}
plan.input = Some((param, view));
Ok(())
}
/// Plan the imageblock output of role `ib` and stated alignment `align` held in field `field` of
/// the returned value, of AIR type `ty` (`stage_io` plans the entry's other outputs).
pub fn select_output(
cx: &mut SelectCx<'_>,
field: u32,
ib: &ImageblockArg,
align: Option<u32>,
ty: AirTypeId,
) -> Result<(), Error> {
let (view, cell) = view(cx, ty, ib, align)?;
require(cx, true)?;
reach(cx, cell)?;
let plan = cx
.families
.fragment
.imageblock
.as_mut()
.ok_or_else(|| invariant_error("an imageblock without its plan"))?;
if plan.output.is_some() {
return Err(not_implemented());
}
plan.output = Some((field, view));
let early = plan_tests(cx)?;
if let Some(plan) = cx.families.fragment.imageblock.as_mut() {
plan.early_tests = early;
}
Ok(())
}
/// The entry declares `[[early_fragment_tests]]`.
fn declared_early(cx: &SelectCx<'_>) -> bool {
matches!(
cx.entry.ep.stage,
crate::air::abi::Stage::Fragment {
early_fragment_tests: true
}
)
}
/// Plan how the depth and stencil tests bear on the imageblock write of a function that writes
/// one, before the stage interface is complete; whether the module declares early fragment tests
/// that the function does not.
///
/// A fragment its depth or stencil test fails drops its imageblock write, as does one alpha to
/// coverage drops (measured on the M3 Max, at one sample and at four). Tested early, a fragment
/// that fails never writes; tested late, the storage already holds its write. So:
///
/// - a function whose only effects are its outputs and its imageblock write, which neither
/// discards nor returns depth, stencil or a sample mask, leaves the attachments under early
/// tests as Metal's late tests leave them: the module declares them;
/// - any other writes before Vulkan's tests and states `RuntimeFact::TestedStorageWrites`, as the
/// framebuffer fetch's storage form does: a draw whose tests drop no fragment runs it as
/// compiled, one whose tests drop some but write and count nothing the variant that declares
/// early tests (where only a discard kept them away, `early_variant`); the binder refuses a draw
/// whose depth or stencil test acts (`bind::graphics`).
fn plan_tests(cx: &mut SelectCx<'_>) -> Result<bool, Error> {
if declared_early(cx) {
return Ok(false);
}
let exported = cx.entry.ep.outputs.iter().any(|o| {
matches!(
o.role,
OutputRole::Depth(_) | OutputRole::Stencil | OutputRole::SampleMask
)
});
let body = super::fetch::body_facts(cx);
let only_outputs = !exported && !body.side_effects;
let fp = &cx.families.fragment;
// A framebuffer fetch's storage form that declares early tests holds the function to them,
// which keeps the write Metal's: it declares them only where the function would here.
if fp.fetch_early_tests {
return Ok(false);
}
if only_outputs && !body.discards {
return Ok(true);
}
let stated = cx.facts.iter().find_map(|f| match *f {
RuntimeFact::TestedStorageWrites { early_variant, .. } => Some(early_variant),
_ => None,
});
if stated.is_none() {
cx.facts.insert(RuntimeFact::TestedStorageWrites {
early_tests: only_outputs && cx.inputs.read_only_tests,
early_variant: only_outputs,
});
}
Ok(stated.is_none() && only_outputs && cx.inputs.read_only_tests)
}
fn invariant_error(detail: &str) -> Error {
Error::Internal(crate::error::InternalError::new(
crate::error::InternalKind::Invariant,
detail,
))
}
/// Complete the imageblock plan once the function is selected: its fact.
pub(super) fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
// A sample mask the function returns that does not cover the invocation's sample drops its
// imageblock write with the fragment (measured on the M3 Max and an M4 at one sample, and on
// the M3 Max at four, where each sample's run writes where the mask has its bit).
let mask = cx
.entry
.ep
.outputs
.iter()
.find(|o| matches!(o.role, OutputRole::SampleMask))
.map(|o| o.field);
let Some(plan) = cx.families.fragment.imageblock.as_mut() else {
return Ok(());
};
let writes = plan.output.is_some();
plan.mask = mask.filter(|_| writes);
let Some(master) = plan.master else {
return Err(invariant_error("an imageblock plan without its master"));
};
let fact = RuntimeFact::FragmentImageblock {
words: plan.words,
writes,
master,
data_size: plan.data_size,
alignment: plan.alignment,
};
cx.facts.insert(fact);
Ok(())
}
/// Declare the imageblock storage image when the plan reaches it.
pub(super) fn declare(
mb: &mut ModuleBuilder,
plan: Option<&ImageblockPlan>,
) -> BResult<Option<GlobalId>> {
if plan.is_none() {
return Ok(None);
}
let sampled_type = mb.ty(SType::Int {
width: 32,
signed: false,
})?;
let ty = mb.ty(SType::Image(ImageType {
sampled_type,
dim: Dim::D2,
depth: false,
arrayed: true,
multisampled: false,
usage: ImageUsage::Storage,
format: crate::spv::ImageFormat::R32ui,
}))?;
let slot = ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::Synthetic(SyntheticBinding::Imageblock),
index: 0,
};
mb.resource(slot, StorageClass::UniformConstant, ty)
.map(Some)
}
/// The cell of one pixel as a word memory: word `w` is texel `(x, y, w)` of the image, and
/// in a function that runs once per sample texel `(x, y, sample * words + w)`, accessed with the
/// function's coherence (`sync::memory_model`).
struct Cell {
image: SValue,
x: SValue,
y: SValue,
/// The first layer of the invocation's sample's cell, in a function that runs per sample.
base: Option<SValue>,
coherence: Coherence,
}
impl Cell {
/// The cell of the invocation's pixel.
fn of_pixel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<Cell> {
let Some(plan) = &cx.plan.families.fragment.imageblock else {
return Err(cx.fail("an imageblock access without its plan"));
};
let (coord, words) = (plan.coord, plan.words);
let Some(g) = cx.decl.families.fragment.imageblock else {
return Err(cx.fail("the imageblock storage is not declared"));
};
let p = fb.module().global_value(g)?;
let image = fb.load(p, MemAccess::default())?;
let frag = stage_io::object_global(cx, coord)?;
let frag = fb.module().global_value(frag)?;
let frag = fb.load(frag, MemAccess::default())?;
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
// `FragCoord` is the pixel's center (or a sample's position inside the pixel): its
// integer part is the pixel.
let fx = fb.composite_extract(frag, &[0])?;
let fy = fb.composite_extract(frag, &[1])?;
let x = fb.convert(ConvOp::ConvertFToU, fx, u32_)?;
let y = fb.convert(ConvOp::ConvertFToU, fy, u32_)?;
let base = match sample_of(cx, fb)? {
Some(sample) => {
let words = k32(fb, words)?;
Some(fb.binary(BinOp::IMul, sample, words)?)
}
None => None,
};
Ok(Cell {
image,
x,
y,
base,
coherence: memory_model::coherence(cx.plan),
})
}
fn texel(&self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let uvec3 = fb.module().ty(SType::Vector { elem: u32_, len: 3 })?;
let layer = match self.base {
Some(base) => fb.binary(BinOp::IAdd, base, word)?,
None => word,
};
fb.composite_construct(uvec3, &[self.x, self.y, layer])
}
}
/// The invocation's sample (`SampleId`) in a function that runs once per sample.
fn sample_of(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<Option<SValue>> {
let Some(object) = cx
.plan
.families
.fragment
.imageblock
.as_ref()
.and_then(|p| p.sample)
else {
return Ok(None);
};
let g = stage_io::object_global(cx, object)?;
let p = fb.module().global_value(g)?;
fb.load(p, MemAccess::default()).map(Some)
}
impl WordMem for Cell {
fn read(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
let at = self.texel(fb, word)?;
let mem = self.coherence.texel(fb)?;
let t = fb.read(self.image, at, &ImageOperands::default(), mem)?;
fb.composite_extract(t, &[0])
}
fn write(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue, value: SValue) -> BResult<()> {
let at = self.texel(fb, word)?;
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let uvec4 = fb.module().ty(SType::Vector { elem: u32_, len: 4 })?;
let zero = k32(fb, 0)?;
let t = fb.composite_construct(uvec4, &[value, zero, zero, zero])?;
let mem = self.coherence.texel(fb)?;
fb.write(self.image, at, t, &ImageOperands::default(), mem)
}
/// Inside the critical section no other invocation touches the pixel's cell, so a plain
/// read-modify-write replaces exactly the bits `mask`.
fn write_bits(
&mut self,
fb: &mut FunctionBuilder<'_>,
word: SValue,
mask: SValue,
bits: SValue,
) -> BResult<()> {
let old = self.read(fb, word)?;
let keep = match leaf::known(fb, mask)? {
Some(m) => k32(fb, !m)?,
None => fb.unary(UnOp::Not, mask)?,
};
let kept = fb.binary(BinOp::BitwiseAnd, old, keep)?;
let new = fb.binary(BinOp::BitwiseOr, kept, bits)?;
self.write(fb, word, new)
}
}
/// Read the input view, in the function's first block, and hold it for every use: Metal's input
/// is the cell's value when the fragment's critical section begins.
pub(super) fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> {
let Some((param, view)) = cx
.plan
.families
.fragment
.imageblock
.as_ref()
.and_then(|p| p.input.clone())
else {
return Ok(());
};
let Some(v) = cx.plan.values.id(Value::Arg(ArgIdx::new(param))) else {
return Err(cx.fail(format!("imageblock parameter {param} is out of range")));
};
let mut cell = Cell::of_pixel(cx, fb)?;
let mut parts = vec![None; view.members.len()];
for m in &view.members {
let off = k32(fb, m.offset)?;
let x = leaf::load(fb, &mut cell, &m.leaf, off)?;
match parts.get_mut(m.field as usize) {
Some(slot) => *slot = Some(x),
None => return Err(cx.fail("an imageblock member past its struct")),
}
}
let parts: Vec<SValue> = parts
.into_iter()
.collect::<Option<_>>()
.ok_or_else(|| cx.fail("an imageblock field without a member"))?;
let Some(ty) = crate::lower::arith::spirv_type(fb.module(), &view.ty)? else {
return Err(cx.fail("an imageblock view without a lowered type"));
};
let x = fb.composite_construct(ty, &parts)?;
cx.hold(v, x);
Ok(())
}
/// Write the output view of returned value `v` (in the entry's returned shape) at the return,
/// unless a predicated discard set `discarded` or the returned sample mask does not cover the
/// pixel's one sample (bit 0: the fragment is dropped, and its write with it).
pub(super) fn emit_return(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
v: Option<crate::air::ir::ValueId>,
) -> BResult<()> {
let Some((field, view, mask)) = cx
.plan
.families
.fragment
.imageblock
.as_ref()
.and_then(|p| p.output.clone().map(|(f, v)| (f, v, p.mask)))
else {
return Ok(());
};
let Some(v) = v else {
return Err(cx.fail("an imageblock output without a returned value"));
};
let whole = cx.operand(fb, v)?;
let (x, covered) = match (cx.plan.families.stage_io.returned, mask) {
(Returned::Struct, mask) => {
let x = fb.composite_extract(whole, &[field])?;
let covered = match mask {
Some(m) => {
let m = fb.composite_extract(whole, &[m])?;
// The invocation's own sample's bit; bit 0 at one sample.
let m = match sample_of(cx, fb)? {
Some(sample) => fb.binary(BinOp::ShiftRightLogical, m, sample)?,
None => m,
};
let one = k32(fb, 1)?;
let zero = k32(fb, 0)?;
let bit = fb.binary(BinOp::BitwiseAnd, m, one)?;
Some(fb.binary(BinOp::INotEqual, bit, zero)?)
}
None => None,
};
(x, covered)
}
(Returned::Value, None) => (whole, None),
(Returned::Value, Some(_)) => {
return Err(cx.fail("a sample mask beside an imageblock output that is the value"))
}
(Returned::Void, _) => return Err(cx.fail("an imageblock output of a void entry")),
};
let mut values = Vec::with_capacity(view.members.len());
for m in &view.members {
values.push(fb.composite_extract(x, &[m.field])?);
}
let cell = Cell::of_pixel(cx, fb)?;
let write = move |fb: &mut FunctionBuilder<'_>, cell: &mut Cell| -> BResult<()> {
for (m, x) in view.members.iter().zip(values) {
let off = k32(fb, m.offset)?;
leaf::store(fb, cell, &m.leaf, off, x)?;
}
Ok(())
};
let mut cell = cell;
let kept = if cx.plan.families.fragment.records_discards() {
let Some(g) = cx.decl.families.fragment.discarded else {
return Err(cx.fail("a recorded discard without its predicate"));
};
let p = fb.module().global_value(g)?;
let discarded = fb.load(p, MemAccess::default())?;
Some(fb.unary(UnOp::LogicalNot, discarded)?)
} else {
None
};
let kept = match (kept, covered) {
(None, None) => return write(fb, &mut cell),
(Some(k), None) | (None, Some(k)) => k,
(Some(k), Some(c)) => fb.binary(BinOp::LogicalAnd, k, c)?,
};
let arm: ArmFn<'_, Cell> = Box::new(move |fb, cell| {
write(fb, cell)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut cell, kept, arm, None)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::air::abi::{MemberKind, UserKey};
use crate::air::error::DiagName;
fn member(offset: u32, key: &str, layout: Option<u32>) -> Member {
Member {
offset,
size: 4,
array_len: 0,
layout: layout.map(StructRef),
kind: MemberKind::Plain,
render_target: None,
raster_order_group: Some(0),
type_name: DiagName::new("t"),
name: DiagName::new(key),
key: UserKey(key.as_bytes().into()),
}
}
/// Layouts `0..=depth` where each of layout `l`'s `width` members nests layout `l + 1` (the
/// last is plain), numbered from `base`: a DAG whose in-place expansion has `width^depth`
/// leaves.
fn dag(base: u32, depth: u32, width: u32, deep_key: &str) -> Vec<StructInfo> {
(0..=depth)
.map(|l| StructInfo {
members: (0..width)
.map(|i| {
let nested = (l < depth).then_some(base + l + 1);
let key = if l == depth && i == 0 { deep_key } else { "m" };
member(i * 4, key, nested)
})
.collect(),
})
.collect()
}
/// The fingerprint hashes each distinct layout once: a 32-wide DAG 20 levels deep (32^20
/// leaves in place) is 21 layouts. Structurally equal masters at other references hash
/// equal; a different key 20 levels down, or a different data size, does not.
#[test]
fn the_fingerprint_hashes_each_shared_layout_once() {
let a = dag(0, 20, 32, "deep");
let (fa, hashed) = fingerprint(&a, StructRef(0), 16).expect("fingerprint");
assert_eq!(hashed, 21);
// The same structure behind a layout it does not reach, at other references.
let mut b = vec![StructInfo {
members: vec![member(0, "unreached", None)],
}];
b.extend(dag(1, 20, 32, "deep"));
let (fb, _) = fingerprint(&b, StructRef(1), 16).expect("fingerprint");
assert_eq!(fa, fb);
let c = dag(0, 20, 32, "other");
assert_ne!(
fingerprint(&c, StructRef(0), 16).expect("fingerprint").0,
fa
);
assert_ne!(
fingerprint(&a, StructRef(0), 32).expect("fingerprint").0,
fa
);
// A reference out of range, and a layout nesting itself, have none.
assert!(fingerprint(&a, StructRef(99), 16).is_none());
let cycle = vec![StructInfo {
members: vec![member(0, "self", Some(0))],
}];
assert!(fingerprint(&cycle, StructRef(0), 16).is_none());
}
}
@@ -3,21 +3,21 @@
//! extended-range forms is refused, `fetch::codes_round_the_tile`).
//!
//! Such an attachment holds Metal's raw texels in its raw unsigned format, which no device blends.
//! On a device that fetches in the pixel interlock the storage form computes the blend in the
//! shader (`fetch`); on one that fetches through input attachments with rasterization-order access
//! (lavapipe) the function computes it over the attachment's input attachment instead: its first
//! On a device that fetches through input attachments with rasterization-order access (lavapipe)
//! the function computes the blend over the attachment's input attachment: its first
//! output's write reads the pixel's raw texel there (at the invocation's sample in a multisampled
//! pipeline), decodes it to Metal's tile value (`extended_range::tile_value`, as a fetch reads it),
//! blends the output over that by the device's arithmetic (`extended_range::blend::native`, the
//! second source and blend color as the storage form reads them, `fetch::blend_second`,
//! `fetch::blend_constant`),
//! second source the function's index-1 output and the blend color push data,
//! `fetch::blend_second`, `fetch::blend_constant`),
//! and writes the kernel write's encode of the result as the raw texel through the output variable
//! (`extended_range::encode`), the channels a write mask keeps taken from the texel read
//! (`extended_range::encode_keeping`). The attachment then takes no Vulkan blend and every raw
//! component is written (link, from `RuntimeFact::ExtendedRangeInputBlend`). Rasterization-order
//! attachment access orders each fragment's read after every earlier fragment's write of the pixel,
//! so each blend reads the codes the one before stored, as a draw of the storage form does (the
//! announcement, `extended-range-blends-stored-codes`, stays the runtime's there).
//! so each blend reads the codes the one before stored (the announcement,
//! `extended-range-blends-stored-codes`, stays the runtime's there). On a device that does not
//! order fetch so, the blend is refused (`fetch::unordered_extended_fetch`).
//!
//! There too an unblended write of some of the codes one word holds (`BGR10_XR`'s word, the
//! two-plane forms' color word, `color_writes::merged_extended`), which no mask of the raw
@@ -31,16 +31,15 @@
//! too ([`RotatedInputBlend`]): Metal blends the format as `RGBA8Unorm` with its channels rotated, so
//! the first output's write reads the pixel's texel through the input attachment, rotates it into
//! Metal's order, computes Metal's 8-bit unorm blend of the clamped output over it
//! (`extended_range::Blend::unorm8`, `extended_range::blend::blend_unorm8`, as the storage form
//! computes it), and writes the result through the output variable, which the stage interface
//! (`extended_range::Blend::unorm8`, `extended_range::blend::blend_unorm8`), and writes the result through the output variable, which the stage interface
//! rotates into the image's order as every output to such an attachment
//! (`stage_io::output_part`); the device's conversion stores its code
//! (`PrecisionNote::DeviceColorConversion`), and the descriptor's write mask, rotated, keeps the
//! channels it leaves out. It states `RuntimeFact::RotatedInputBlend`, and link gives the
//! attachment no Vulkan blend.
//!
//! The blend takes a `half4` or `float4` output under every factor, operation and write mask, as
//! the storage form does (another output is refused, `Feature::ExtendedRangeBlend` `Output`); its
//! The blend takes a `half4` or `float4` output under every factor, operation and write mask
//! (another output is refused, `Feature::ExtendedRangeBlend` `Output`); its
//! second source is the function's index-1 output, read from the returned value and stored nowhere
//! else ([`select_second_output`]). A write of none of the format's channels stores nothing and
//! blends nothing. A padded attachment's blend is built so too; a bfloat attachment's is Metal's
@@ -122,8 +121,8 @@ impl RotatedInputBlend {
}
/// Whether the device orders framebuffer fetch through rasterization-order input attachments,
/// where this module computes an extended-range blend (on one that orders it through the pixel
/// interlock, the storage form does, `fetch::interlock_orders`).
/// where this module computes an extended-range blend (on another it is refused,
/// `fetch::unordered_extended_fetch`).
fn through_inputs(cx: &SelectCx<'_>) -> bool {
fetch::inputs_order(cx.profile)
}
@@ -384,7 +383,7 @@ fn rotated(
cx.facts.insert(RuntimeFact::FramebufferFetch { color });
// The result is the device's to convert to its code; the blend is Metal's where the
// module states its math (Metal clamps the output first, so none of the output's
// arithmetic folds into it), as the storage form's is.
// arithmetic folds into it).
cx.precision.insert(PrecisionNote::DeviceColorConversion);
if cx.entry.compile.fast_math.is_none() {
let note = crate::lower::arith::output_precision::half_output_note(cx);
@@ -4,9 +4,9 @@
//! Metal applies the operation to the code of each channel of a normalized or integer attachment
//! the function writes, the fragment's code against the stored one, blending ignored and the write
//! mask kept after it (`pipeline::private_state`'s module docs). On a device that orders
//! framebuffer fetch, the function's first output's write to such an attachment reads the pixel's
//! texel, in the interlocked storage form (`fetch`) or through the attachment's input attachment
//! under rasterization-order access, and stores the operation's result itself ([`operated`]):
//! framebuffer fetch through rasterization-order input attachments, the function's first output's
//! write to such an attachment reads the pixel's texel through the attachment's input attachment,
//! and stores the operation's result itself ([`operated`]):
//!
//! - the stored codes from the texel the read gives: a normalized channel's value times its
//! largest code, rounded to nearest even (exact: the read's value is a code over that largest
@@ -44,14 +44,12 @@
//! code past the rounded product), nor is `RGB10A2Uint`'s (it saturates the operation's 32-bit
//! result), and is refused there (`pipeline::private_state::logic_operation`). So is a write the
//! operation would read otherwise than as the format's codes: a narrower integer output than 32
//! bits ([`takes`]), an attachment held through a word view, under alpha to coverage in the storage
//! form, and, through an input attachment, one held with its channels rotated or with Metal's alpha
//! in red.
//! bits ([`takes`]), an attachment held through a word view, and one held with its channels
//! rotated or with Metal's alpha in red.
//!
//! The write mask applies after the operation: the storage form takes the kept channels back from
//! the texel it read (`fetch`), and over an input attachment the device's write mask keeps them.
//! Each read is ordered after every earlier fragment's write of the pixel (the pixel interlock, or
//! rasterization-order attachment access), so overlapping fragments operate in primitive order, as
//! The write mask applies after the operation: the device's write mask keeps the channels it leaves
//! out. Each read is ordered after every earlier fragment's write of the pixel (rasterization-order
//! attachment access), so overlapping fragments operate in primitive order, as
//! Metal's do; a multisampled pipeline's function runs per sample and operates on its own sample's
//! codes.
@@ -454,8 +452,7 @@ pub struct LogicInput {
/// input attachment, and states `RuntimeFact::FramebufferFetch`; a normalized one's codes are the
/// device's conversion (`PrecisionNote::DeviceColorConversion`). An attachment held through a
/// word, with its channels rotated, or with Metal's alpha in red, and an output the operation does
/// not take ([`takes`]), are refused naming the operation. (On a device that orders fetch through
/// the pixel interlock, the storage form computes it, `fetch`.)
/// not take ([`takes`]), are refused naming the operation.
pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> {
let Some(op) = cx.inputs.logic_operation else {
return Ok(());
+33 -193
View File
@@ -5,30 +5,23 @@
//! reachability, and the profile). A predicated site sets the `Private bool discarded` this
//! family declares, and [`emit_return`] kills a discarded invocation before `OpReturn`.
//! - **Framebuffer fetch** (`[[color(n)]]` inputs): each color index is one input attachment
//! (`color`), read at every use; on a device that orders the read only through the pixel
//! interlock, a storage image of the attachment read and written inside the interlock where the
//! pipeline's state lets that be exact (`fetch`). Compiled for a multisampled pipeline, either
//! form reads (and writes) the invocation's own sample at `SampleId`, which runs the function
//! once per covered sample, as Metal does. On a device that orders the read through
//! (`color`), read at every use. Compiled for a multisampled pipeline, it reads the invocation's
//! own sample at `SampleId`, which runs the function once per covered sample, as Metal does. On a device that orders the read through
//! rasterization-order input attachments, a blend into an extended-range attachment is computed
//! over its input attachment (`input_blend`).
//! - **Raster order groups** (`rog`): a function that names a group runs its body as a function
//! called from `main` between `Begin/EndInvocationInterlockEXT` ([`wrap_entry`], the
//! entry-wrapper hook of `lower::emit`); inside it a discard only records `discarded`, and `main`
//! kills after the critical section.
//! - **Imageblocks** (`imageblock`): an `[[imageblock_data]]` input is read from the pass's
//! imageblock storage image at the pixel in the function's first block ([`emit_entry`]), an
//! output written at the return ([`emit_return`]), both inside the interlock critical section,
//! which a function that reaches the imageblock always has.
//! - **Imageblocks**: an `[[imageblock_data]]` input or output is not implemented
//! (`Unsupported{Imageblocks, NotImplemented}`).
//! - **Sample count** (`get_num_samples`): Metal's header spells `get_num_samples()` as the call
//! with operand 0, the pipeline's rasterization sample count. It reads the `SpecKey::SampleCount`
//! specialization constant (`RuntimeFact::SampleCount`, default 1), which the binder sets to the
//! pipeline's `rasterizationSamples`. A call with another operand is refused: no other operand's
//! meaning is established.
//! - **Shader-side stencil** (`stencil`): on a device without stencil export, a `[[stencil]]`
//! output is tested and written by the function itself against a shadow of the stencil, inside
//! the interlock critical section, at each return; a failing fragment is recorded as discarded
//! and killed after the critical section.
//! - **Stencil output**: a `[[stencil]]` output needs `VK_EXT_shader_stencil_export`
//! (`stage_io`), refused naming it on a device without the extension.
//! - **Coverage at sample rate** (`coverage`): a function that reads `[[sample_mask]]` and that
//! Metal runs once per covered sample runs, compiled for a multisampled pipeline, once per pixel,
//! and its body once per covered sample from a loop over the pixel's coverage ([`wrap_entry`]),
@@ -38,11 +31,6 @@
//! a `Private u32` before it calls the body, and the body reads that copy
//! (`stage_io::coverage_in`). SPIRV-Cross (MoltenVK) declares the input a scalar in the entry
//! but passes it to a function as an array, which Metal refuses.
//! - **Snapshot reads** (`snapshot`): a function compiled to read textures through snapshots
//! (`LoweringInputs::snapshot_textures`) opens with an ordered pixel interlock's critical section
//! in which, in the draw that takes the snapshot, each non-helper fragment copies its pixel's
//! texel, and that draw returns after it; in the draw that reads it, each read of the slot reads
//! the snapshot, and a helper reads 0. The body runs outside the critical section.
//! - **Pull-model interpolation** (`interpolate`): each `interpolate_at_*` call of an
//! `interpolant` reads the interpolant's variable where it says (`stage_io::interpolate`); the
//! interpolant itself is planned by `lower::stage_io`.
@@ -53,13 +41,10 @@ mod color;
mod coverage;
mod discard;
pub(crate) mod fetch;
mod imageblock;
mod input_blend;
mod interpolate;
mod logic;
mod rog;
mod snapshot;
mod stencil;
mod word_input;
pub(crate) use color::texture_decl;
@@ -95,14 +80,8 @@ pub use color::ColorInput;
pub use coverage::CoveragePlan;
pub use discard::DiscardForm;
pub(crate) use fetch::{
compiled_write_mask, extended_range_blend, half_float_format, inputs_order, interlock_forms,
interlock_orders, kept_channels, storage_form, ColorUse, StorageSamples,
compiled_write_mask, extended_range_blend, half_float_format, inputs_order, kept_channels,
};
pub use fetch::{
select_output as select_storage_output, select_second_output as select_storage_second_output,
StorageColor,
};
pub use imageblock::{select_output as select_imageblock_output, ImageblockPlan};
pub(crate) use input_blend::{rotated_texel as rotated_input_texel, texel as input_blend_texel};
pub use input_blend::{
select_second_output as select_input_second_output, InputBlend, RotatedInputBlend,
@@ -112,11 +91,6 @@ pub(crate) use logic::{
channels as logic_channels, input_operated as logic_input_operated,
vulkan_differs as logic_vulkan_differs,
};
#[cfg(test)]
pub(crate) use snapshot::{decode as snapshot_decode, encode as snapshot_encode};
pub(crate) use snapshot::{prepare as snapshot_prepare, read as snapshot_read};
pub(crate) use stencil::{face_word, SHADOW_FORMAT};
pub use stencil::{select_output as select_stencil_output, ShadowStencil};
pub(crate) use word_input::merge as word_input_merge;
fn not_lowered() -> Error {
@@ -191,11 +165,6 @@ pub struct FragmentPlan {
/// The function is in a raster order group: its body runs inside this interlock mode's
/// critical section, called from the entry [`wrap_entry`] builds.
pub interlock: Option<ExecMode>,
/// The function's views of the render pass's imageblock.
pub imageblock: Option<ImageblockPlan>,
/// The color attachments the function reads in the interlocked storage form, by index
/// (`fetch`).
pub fetch: BTreeMap<u32, StorageColor>,
/// The extended-range attachments whose blend the function computes over their input
/// attachments, on a device that orders fetch through them (`input_blend`), by index.
pub input_blends: BTreeMap<u32, InputBlend>,
@@ -210,33 +179,19 @@ pub struct FragmentPlan {
/// The attachments whose private logic operation the function computes over their input
/// attachments, on a device that orders fetch through them (`logic`), by index.
pub logic_inputs: BTreeMap<u32, LogicInput>,
/// The stage interface's `FragCoord` object, which gives the pixel of the storage form and
/// of the shader-side stencil.
/// The stage interface's `FragCoord` object, which gives the pixel a color read through a
/// pushed texture fetches (`texture_fetches`).
pub fetch_coord: Option<usize>,
/// The module declares early fragment tests for the storage form, which the function itself
/// does not.
pub fetch_early_tests: bool,
/// The stage interface's `SampleId` object, at which a function compiled for a multisampled
/// pipeline (`LoweringInputs::multisampled`) reads each color it fetches, in either form, and
/// writes each storage-form color: Metal runs such a function once per covered sample and
/// reads its own sample.
/// pipeline (`LoweringInputs::multisampled`) reads each color it fetches: Metal runs such a
/// function once per covered sample and reads its own sample.
pub fetch_sample: Option<usize>,
/// The field of the returned value holding the function's `[[sample_mask]]` output, which
/// gates each storage-form write of a per-sample function on the invocation's own sample bit,
/// and of a function at one sample on bit 0.
pub fetch_mask: Option<u32>,
/// The function's `[[stencil]]` output is a shader-side stencil (`stencil`).
pub stencil: Option<ShadowStencil>,
/// The function reads `[[sample_mask]]` and runs once per covered sample on Metal: its loop
/// over the covered samples, or why it has none (`coverage`).
pub coverage: Option<CoveragePlan>,
/// The function returns a `[[depth(...)]]` output (`StageIoPlan::depth_clamp`). Inside an
/// interlocked body each return records a positive NaN depth as discarded.
pub depth_output: bool,
/// The texture slots the function reads through a snapshot (`snapshot`,
/// `LoweringInputs::snapshot_textures`), by Metal index, each with its snapshot's form.
/// Filled by [`finish`].
pub snapshot: BTreeMap<u32, crate::pipeline::sym::SnapshotForm>,
}
impl FragmentPlan {
@@ -255,19 +210,17 @@ impl FragmentPlan {
/// sites, or for a helper query where no site demotes.
fn reads_helper_input(&self) -> bool {
(self.predicated() && !self.quad_exits.is_empty())
|| ((self.helper_queries || !self.snapshot.is_empty()) && !self.demotes())
|| (self.helper_queries && !self.demotes())
}
/// The function declares `discarded`: a predicated site, inside an interlocked body a
/// The function declares `discarded`: a predicated site, or inside an interlocked body a
/// terminate-form site (which records the discard and returns to the entry) or a depth output
/// (whose returns record a positive NaN), or a shader-side stencil, which records a failing
/// fragment.
/// (whose returns record a positive NaN).
pub fn records_discards(&self) -> bool {
self.predicated()
|| (self.interlock.is_some()
&& (self.depth_output
|| self.discards.values().any(|f| *f == DiscardForm::Terminate)))
|| self.stencil.is_some()
}
fn kill_form(&self) -> KillForm {
@@ -312,20 +265,11 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> {
cx.precision.insert(PrecisionNote::QuadsSplitByClipping);
}
let looped = coverage::finish(cx)?;
imageblock::finish(cx)?;
fetch::finish(cx)?;
stencil::finish(cx)?;
// An imageblock, an attachment in the storage form and the shadow of a shader-side stencil
// are read and written inside the critical section whether or not the function names a raster
// order group.
let shadow = cx.families.fragment.stencil.is_some();
let storage = !cx.families.fragment.fetch.is_empty() || shadow;
let interlock = if rog::declared(cx) || cx.families.fragment.imageblock.is_some() || storage {
let interlock = if rog::declared(cx) {
Some(rog::mode(cx)?)
} else {
None
};
let snapshot = snapshot::finish(cx, interlock.is_some(), looped)?;
let sites: Vec<InstId> = cx.families.fragment.discards.keys().copied().collect();
let discard::DiscardPlan {
forms,
@@ -353,7 +297,6 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> {
fp.guarded = guarded;
fp.terminate_invocation = terminate;
fp.interlock = interlock;
fp.snapshot = snapshot;
Ok(())
}
@@ -366,20 +309,13 @@ pub struct Declared {
/// The `HelperInvocation` input the whole-quad exits and helper queries where no discard
/// demotes read.
pub helper: Option<GlobalId>,
/// The input attachment of each color index read, or its storage image in the interlocked
/// storage form.
/// The input attachment of each color index read.
pub attachments: BTreeMap<u32, GlobalId>,
/// The render pass's imageblock storage image.
pub imageblock: Option<GlobalId>,
/// The shadow of a shader-side stencil.
pub shadow_stencil: Option<GlobalId>,
/// The `Private u32` holding the sample of the loop's pass over the covered samples.
pub loop_sample: Option<GlobalId>,
/// The `Private u32` copy of the `SampleMask` input's word, which the entry stores before it
/// calls the body it wraps, and the body reads for every read of the input.
pub coverage_copy: Option<GlobalId>,
/// The snapshots the function reads textures through, and the helper's copy.
pub snapshot: snapshot::Declared,
}
/// Declare the fragment family's module-scope objects and modes: the discard predicate, the
@@ -391,14 +327,9 @@ pub fn declare(
) -> BResult<Declared> {
let fp = &plan.families.fragment;
let mut d = Declared::default();
if let Some(m) = fp.interlock.or(snapshot::mode(&fp.snapshot)) {
if let Some(m) = fp.interlock {
modes.push(m);
}
// The storage form's writes, and the imageblock's, are Metal's under early tests.
let imageblock_early = fp.imageblock.as_ref().is_some_and(|p| p.early_tests);
if fp.fetch_early_tests || imageblock_early {
modes.push(ExecMode::EarlyFragmentTests);
}
if fp.records_discards() {
let bool_ = mb.ty(SType::Bool)?;
let no = mb.constant(Constant::Scalar {
@@ -414,15 +345,12 @@ pub fn declare(
d.attachments = color::declare(
mb,
&fp.colors,
(&fp.fetch, &fp.input_blends, &fp.word_merges),
(&fp.input_blends, &fp.word_merges),
(&fp.rotated_blends, &fp.logic_inputs),
fp.fetch_sample.is_some(),
&fp.texture_fetches,
)?;
d.imageblock = imageblock::declare(mb, fp.imageblock.as_ref())?;
d.shadow_stencil = stencil::declare(mb, fp.stencil.as_ref())?;
d.loop_sample = coverage::declare(mb, plan)?;
d.snapshot = snapshot::declare(mb, &fp.snapshot)?;
if wraps_body(fp) && sample_mask_input(plan).is_some() {
let u32_ = mb.ty(SType::Int {
width: 32,
@@ -500,11 +428,11 @@ pub(super) fn load_coverage(
Ok(Some(covered))
}
/// Plan a used parameter this family owns (`select::param_family`): a color input, or an
/// imageblock input.
/// Plan a used parameter this family owns (`select::param_family`): a color input. An imageblock
/// input is not implemented.
pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> {
if let ParamRole::Imageblock(ib) = &b.role {
return imageblock::select_input(cx, b.param, ib, b.ty.align);
if let ParamRole::Imageblock(_) = &b.role {
return Err(Unsupported::not_implemented(Feature::Imageblocks).into());
}
let c = color::select_param(cx, b).map_err(|e| match b.role {
ParamRole::ColorInput {
@@ -517,11 +445,10 @@ pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error
Ok(())
}
/// Plan the entry's framebuffer-fetch forms before its stage interface: an output to an attachment
/// in the storage form is no interface variable. Then the loop over the covered samples, which
/// decides how the stage interface reads `[[sample_id]]` and the sample-qualified varyings.
/// Plan the entry's framebuffer-fetch forms before its stage interface. Then the loop over the
/// covered samples, which decides how the stage interface reads `[[sample_id]]` and the
/// sample-qualified varyings.
pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
fetch::plan(cx)?;
input_blend::plan(cx)?;
word_input::plan(cx)?;
logic::plan(cx)?;
@@ -534,55 +461,8 @@ pub fn loops_samples(cx: &SelectCx<'_>) -> bool {
cx.families.fragment.coverage.is_some_and(|c| c.looped)
}
/// Whether the function reads color attachment `color` in the interlocked storage form, so an
/// output to it is written there, not to an interface variable.
pub fn writes_through_storage(cx: &SelectCx<'_>, color: u32) -> bool {
fetch::is_storage(cx, color)
}
/// Whether the function writes color attachment `color` in the storage form under Metal's
/// 16-bit float, 8-bit unorm or 8-bit sRGB blend, which the shader computes, and that blend is
/// Metal's exactly: the attachment stores Metal's value.
pub fn blends_half_in_storage(cx: &SelectCx<'_>, color: u32) -> bool {
fetch::blends_in_shader(cx, color, true)
}
/// Whether the function writes color attachment `color` in the storage form under a write mask
/// that names none of its format's channels: the write stores nothing.
pub fn stores_nothing_in_storage(cx: &SelectCx<'_>, color: u32) -> bool {
(cx.families.fragment.fetch.get(&color)).is_some_and(|sc| sc.writes && sc.view.stores_nothing())
}
/// Whether the function writes (or reads) color attachment `color` in the storage form, which the
/// pipeline's color attachments do not hold.
pub fn written_in_storage(cx: &SelectCx<'_>, color: u32) -> bool {
cx.families.fragment.fetch.contains_key(&color)
}
/// Whether the function writes color attachment `color` in the storage form under Metal's
/// 16-bit float blend, which the shader computes, exactly or not: the write stores a `half` in
/// every channel, whose conversion by the device is exact.
pub fn blends_sixteen_in_storage(cx: &SelectCx<'_>, color: u32) -> bool {
fetch::blends_half(cx, color)
}
/// Whether the function writes color attachment `color` in the storage form under a blend the
/// shader computes of a format held directly (Metal's 16-bit float, 8-bit unorm or 8-bit sRGB
/// blend), exactly or not: the write stores the value the blend gives, which no conversion of the
/// device's changes (an 8-bit unorm channel's code is rounded by Metal's rule in the shader, an
/// sRGB one's encoded by Metal's table).
pub fn blends_in_storage(cx: &SelectCx<'_>, color: u32) -> bool {
fetch::blends_in_shader(cx, color, false)
}
/// Whether the function's second (index-1) output to `color` is the second source of the
/// extended-range blend the shader computes in the storage form, outside the stage interface.
pub fn blends_second_through_storage(cx: &SelectCx<'_>, color: u32) -> bool {
fetch::blends_second(cx, color)
}
/// The extended-range write of attachment `color` the shader computes, in the storage form
/// (`fetch`) or over the input attachment (`input_blend`): the pipeline's blend there (`None`
/// The extended-range write of attachment `color` the shader computes over the input attachment
/// (`input_blend`): the pipeline's blend there (`None`
/// for an unblended write and for a write that stores none of the format's channels), the
/// attachment's form, and whether the write stores none of its channels. `None` where the
/// function writes the attachment otherwise (or not at all).
@@ -595,12 +475,6 @@ pub(crate) fn shader_blend(
bool,
)> {
let fp = &cx.families.fragment;
if let Some(sc) = fp.fetch.get(&color) {
return sc
.view
.extended
.map(|form| (sc.view.blend, form, sc.view.stores_nothing()));
}
fp.input_blends.get(&color).map(|ib| {
let blends = ib.blend.is_some();
(
@@ -618,35 +492,10 @@ pub fn blends_second_through_inputs(cx: &SelectCx<'_>, color: u32) -> bool {
input_blend::blends_second(cx, color)
}
/// Whether the function writes an output the returned value holds outside the stage interface:
/// an imageblock output, an output to an attachment in the storage form, or a shader-side stencil.
pub fn writes_outside_interface(cx: &SelectCx<'_>) -> bool {
let fp = &cx.families.fragment;
fp.imageblock.as_ref().is_some_and(|p| p.output.is_some())
|| fp.fetch.values().any(|sc| sc.writes)
|| fp.stencil.is_some()
}
/// The work before the body, in the function's first block: read the imageblock input, place the
/// fragment's tile in the pass's tile memory, copy the textures read through snapshots
/// (`snapshot`), and read the texel of each storage-form color the function reads
/// (`EmitCx::fetched`), which every use of the color then takes.
/// The work before the body, in the function's first block: place the fragment's tile in the
/// pass's tile memory.
pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> {
imageblock::emit_entry(cx, fb)?;
crate::lower::access::tile_memory::emit_entry(cx, fb)?;
snapshot::emit_entry(cx, fb)?;
let fp = &cx.plan.families.fragment;
let read: BTreeSet<u32> = fp
.colors
.iter()
.map(|c| c.color)
.filter(|color| fp.fetch.contains_key(color))
.collect();
for color in read {
let texel = fetch::texel(cx, fb, color)?;
cx.fetched.push((color, texel));
}
Ok(())
crate::lower::access::tile_memory::emit_entry(cx, fb)
}
/// The value of parameter `b` in its lowered representation, read by an instruction or a
@@ -777,18 +626,9 @@ pub fn not_discarded(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResu
}
/// Emit the entry's return terminator after `stage_io::emit_return` stored the outputs: a
/// shader-side stencil tests and writes its shadow, recording a failing fragment as discarded; the
/// outputs of returned value `v` to attachments in the storage form and its imageblock output are written, then a predicated discard kills a discarded
/// invocation, which drops its outputs. An interlocked body only returns; its caller kills after
/// the critical section.
pub fn emit_return(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
v: Option<crate::air::ir::ValueId>,
) -> BResult<()> {
stencil::emit_return(cx, fb, v)?;
fetch::emit_return(cx, fb, v)?;
imageblock::emit_return(cx, fb, v)?;
/// predicated discard kills a discarded invocation, which drops its outputs. An interlocked body
/// only returns; its caller kills after the critical section.
pub fn emit_return(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> {
let fp = &cx.plan.families.fragment;
if fp.interlock.is_none() && fp.predicated() {
let Some(g) = cx.decl.families.fragment.discarded else {
@@ -27,12 +27,10 @@
//! output alone does not interlock the function, so a function whose groups hold nothing else
//! compiles on every device, the ones without an interlock included.
//!
//! **Color inputs without an ordered fetch form**. On a device with neither rasterization-order
//! color attachment access nor the pixel interlock's storage form (`fetch::fetch_unordered`), a
//! color input reads its input attachment ordered between draws alone, by the consumer's barriers
//! (under the identity domains, the attachment's pushed texture, on every device without
//! rasterization-order access: there the interlock chooses no fetch form,
//! `fetch::interlock_forms`). A group on such an input, or on a color output of an attachment the
//! **Color inputs without an ordered fetch**. On a device without rasterization-order color
//! attachment access (`fetch::fetch_unordered`), a color input reads its input attachment ordered
//! between draws alone, by the consumer's barriers (under the identity domains, the attachment's
//! pushed texture). A group on such an input, or on a color output of an attachment the
//! function reads, asks for the order of that read, which is the read's own there: it does not
//! interlock the function, since the interlock cannot order the attachment's own write, which
//! happens after the function, and the read's fragments of one draw stay unordered
@@ -1,674 +0,0 @@
//! Reads of a texture through a snapshot (`LoweringInputs::snapshot_textures`).
//!
//! A draw that reads a texture `T` its own subpass renders, at the fragment's own pixel alone
//! (`StageInterface::snapshot_textures`), runs twice with one pipeline (`PushField::SnapshotPhase`,
//! the binder's `bind::graphics`). The first draw, every color write mask 0 and the phase 1, copies
//! each non-helper fragment's texel of `T` into the slot's snapshot `S` (`ResourceKind::
//! SnapshotTexels`) and returns; the second, the pipeline's own masks and the phase 0, copies
//! nothing and runs the function, whose every read of `T` reads `S`, or nothing in a helper
//! invocation. The entry opens, before the body:
//!
//! ```text
//! helper ← this invocation is a helper
//! OpBeginInvocationInterlockEXT
//! if phase ≠ 0 && !helper { for each slot: S[p] ← bits(fetch T[p], level 0) } p = uint(FragCoord.xy)
//! OpEndInvocationInterlockEXT
//! if phase ≠ 0 { return }
//! ```
//!
//! **Why one draw is not enough.** The function's read of `T[p]` must happen before the same
//! draw's color write of `T[p]`. Vulkan states only an execution order there: "Most operations in
//! the fragment shader are not performed in rasterization order, with exceptions called out in the
//! following sections" (Fragment Shading), and blending and color writes execute in rasterization
//! order (Rasterization Order). Its memory model relates a shader instruction to another only
//! through program order, the interlock's synchronizes-with ("If A is an
//! OpEndInvocationInterlockEXT instruction and B is an OpBeginInvocationInterlockEXT instruction,
//! then A synchronizes-with B if the agent that executes A is ordered before the agent that executes
//! B"), and execution dependencies ("If there is an execution dependency between two operations A
//! and B, then the operation in the first synchronization scope system-synchronizes-with the
//! operation in the second synchronization scope"), none of which reaches the fixed-function color
//! write. So no single-draw form, interlocked or not, orders the read before the write; a form that
//! "simplifies" this back into one draw relies on behaviour the specification does not state.
//!
//! **Why two draws are exact.** Each link rests on a sentence of the specification:
//!
//! - *The copy reads `T` as the draws before left it.* The consumer records a by-region barrier
//! from the color attachment writes to fragment-shader reads before the first draw, with `T`'s
//! attachment in the feedback-loop layout: "A vkCmdPipelineBarrier inside a subpass can
//! synchronize prior attachment writes in the subpass with subsequent non-attachment reads if
//! feedback loop is enabled for the attachment", "In that case the overlap is defined to occur at
//! a per-pixel granularity", and each region "covers a single (x,y,layer) position". The copy
//! reads `T` at its own pixel alone.
//! - *Nothing writes `T` during the first draw.* Every color write mask is 0: "VK_COLOR_COMPONENT_R_BIT
//! specifies that the R value is written to the color attachment for the appropriate sample.
//! Otherwise, the value in memory is unmodified" (Color Write Mask), and likewise for G, B and A.
//! The function writes no memory (the interface fact), and the first draw runs nothing of it past
//! the copy, so the outputs it leaves unwritten reach nothing.
//! - *The two draws shade the same fragments.* They differ only in the write masks, dynamic state of
//! one pipeline: "Rule 2 Changes to the following state values have no side effects ... Write
//! masks (color, depth, stencil)", and "Corollary 1 Fragment generation is invariant with respect
//! to the state values listed in Rule 2" (Invariance). A second pipeline would be another state
//! vector, which those rules do not cover; the side-effect relaxation lifts only "rule 1,
//! corollary 2, and rule 4". Each fragment of the first draw runs the copy: "Otherwise, at least
//! one fragment shader must be executed" (Fragment Shading), which covers each pixel the second
//! draw's fragments read; no fragment operation before shading discards one (no depth or stencil
//! attachment, and the same scissor).
//! - *Fragments that cover one pixel in the first draw write `S[p]` in order.* The entry declares
//! `PixelInterlockOrderedEXT`: "any interlocked operations in a fragment shader must happen before
//! interlocked operations in fragment shader invocations that execute later in rasterization order
//! and cover at least one sample in the same pixel", the End/Begin synchronizes-with above, and
//! `S` is decorated `Coherent`, whose per-instruction availability and visibility the interlock
//! needs ("shaders using fragment shader interlock will declare the relevant resources as
//! coherent", Memory Model). Every such write stores the same bits, since `T` does not change.
//! - *The second draw reads `S` after the first wrote it.* The consumer records a by-region barrier
//! from the first draw's fragment-shader writes to the second draw's fragment-shader reads, which
//! also orders the copy's read of `T` before the second draw's color writes.
//! - *No other access races.* "Data races can only occur due to instructions that are actually
//! executed" (Memory Model): the second draw executes no copy, and the first no read of `S`. A
//! helper invocation copies nothing and reads nothing; its codes of the slot are 0, which reaches
//! no fragment's result, since no value read from the slot reaches a derivative, a quad or
//! subgroup operation or a branch (but a selection whose arms leave through its merge alone and
//! hold none of those, no loop and no undefined operand, which a helper may take either arm of),
//! nor an integer divisor or a dynamic component index, whose behavior SPIR-V leaves undefined
//! at some values (`spirv::requirements::snapshot_textures`):
//! "Stores and atomics performed by helper invocations must not have any effect on memory except
//! for the Function, Private and Output storage classes" (Helper Invocations).
//!
//! **The snapshot's form** (`SnapshotForm`, the binder's choice by the slot's bound view): the
//! copy stores the texel's codes, which it takes from the fetched value, and a read decodes them.
//!
//! - `Bits`: the fetched `vec4`'s 32 bits a lane in an `R32G32B32A32_UINT` image, which come back
//! bit for bit, whatever the texel.
//! - A normalized form: each lane's code `c = RoundEven(clamp(v) * D)` (`D = 2^b - 1`, a signed
//! form's `2^(b-1) - 1` and its clamp `[-1, 1]`), in an `R8G8B8A8_UINT` or `R16G16B16A16_UINT`
//! image, two's complement where signed. The fetched value of a normalized code `c` is "f =
//! c / (2^b - 1)" (a signed one's "f = max(c / (2^(b-1) - 1), -1.0)", Fixed-Point Data
//! Conversions), so `v * D` lies within far less than half of one of `c`, and "OpFMul ...
//! Correctly rounded" with `RoundEven` exact (Precision and Operation of SPIR-V Instructions)
//! give `c` back; a signed form's `-2^(b-1)`, whose value is `-1` as the code above it's is, comes
//! back as that code. A read decodes `c` by the device's arithmetic, `c` times the `f32` nearest
//! `1 / D` (a signed code's at least `-1`), within an `f32` rounding or two of `c / D`
//! (`PrecisionNote::DevicePackConversion`; Metal reads `c / D` correctly rounded).
//! - `Half`: each lane's half-float code (`narrow::to_bits`: the device's narrowing, every half
//! value's bits but a NaN's and, where the device may flush a 16-bit denormal, a denormal's,
//! each recorded, `narrow::encodes_bits`; a code loaded unchanged keeps its bits), in an
//! `R16G16B16A16_UINT` image; a read widens it back as a `half` read
//! from memory widens (`narrow::from_bits`): the device's widening on every device, every code's
//! value but a NaN's bits and, where the device may flush a 16-bit denormal, a denormal, each
//! recorded (`narrow::widens_bits`).
//! - An integer form: each lane's code (the fetched integer lane, a code of the format), its low 8
//! or 16 bits in an `R8G8B8A8_UINT` or `R16G16B16A16_UINT` image; a read extends it, with its
//! sign where signed.
//!
//! A narrower format's channels the texel lacks are the fetch's constants (0, or 1 in alpha),
//! whose codes the form holds too, and a swizzled view's lanes are channels or those constants.
//!
//! **The view the copy fetches through** is the one the read it stands for would have fetched, and
//! the one the binder names the form by: the slot's own image.
use std::collections::BTreeMap;
use crate::device::requirements::VkFeature;
use crate::error::{Capability, Error, Feature, LowerFamily, Unsupported};
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::narrow;
use crate::lower::arith::ops::{splat, ty};
use crate::lower::emit::EmitCx;
use crate::lower::select::SelectCx;
use crate::lower::stage_io;
use crate::lower::sync::barrier::BarrierModel;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, SlotClass, SnapshotForm, Stage};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{GlobalId, TypeId, Value as SValue};
use crate::spirv::ir::{
BinOp, ConstBits, Constant, ConvOp, Dim, ExecMode, GlslOp, ImageOperands, ImageType,
ImageUsage, MemAccess, StorageClass, TexelMemory, Type as SType, UnOp,
};
/// The fragment texture slots function `cx` reads through a snapshot, from its lowering inputs:
/// the stage interface's `FragCoord`, the phase's push field and each snapshot's storage image are
/// planned for them. A function with another interlock or a loop over its covered samples has none
/// (the binder asks for neither), and a device without `fragmentShaderPixelInterlock` refuses them.
pub(super) fn finish(
cx: &mut SelectCx<'_>,
interlocked: bool,
looped: bool,
) -> Result<BTreeMap<u32, SnapshotForm>, Error> {
let slots: BTreeMap<u32, SnapshotForm> = cx
.inputs
.snapshot_textures
.iter()
.filter(|(s, _)| s.stage == Stage::Fragment && s.class == SlotClass::Texture)
.map(|(s, form)| (s.index, *form))
.collect();
if slots.is_empty() || cx.stage != Stage::Fragment {
return Ok(BTreeMap::new());
}
if interlocked || looped {
return Err(cx.invariant(
"a snapshot read in a function with another critical section or a sample loop",
));
}
if !super::fetch::interlock_forms(cx.profile) {
return Err(Unsupported::needs(
Feature::RasterOrderGroups,
Capability::Feature(VkFeature::FragmentShaderPixelInterlock),
)
.into());
}
// `S` is `Coherent`, a `GLSL450` decoration; a storage image beside the `GLSL450` form of a
// coherent access, or under the Vulkan model, is not implemented (`sync::memory_model`).
let model = &cx.families.memory_model;
if model.model == BarrierModel::Vulkan || model.coherent_resources {
return Err(Unsupported::not_implemented(Feature::Lowering(LowerFamily::Fragment)).into());
}
cx.families.fragment.fetch_coord = Some(stage_io::frag_coord(cx));
cx.push.insert(PushField::SnapshotPhase);
// A normalized form's read decodes its codes by the device's arithmetic.
if slots.values().any(|f| normalized(*f)) {
cx.precision.insert(PrecisionNote::DevicePackConversion);
}
let n = u32::try_from(slots.len()).unwrap_or(u32::MAX);
cx.descriptors.storage_images = cx.descriptors.storage_images.saturating_add(n);
Ok(slots)
}
/// The interlock mode of a function with snapshot slots `slots`.
pub(super) fn mode(slots: &BTreeMap<u32, SnapshotForm>) -> Option<ExecMode> {
(!slots.is_empty()).then_some(ExecMode::PixelInterlockOrdered)
}
/// The module-scope objects of the snapshot reads.
#[derive(Clone, Debug, Default)]
pub struct Declared {
/// Each slot's snapshot, `Coherent`.
pub images: BTreeMap<u32, GlobalId>,
/// The `Private bool` the entry stores whether the invocation is a helper in.
pub helper: Option<GlobalId>,
}
/// Declare each of `slots`' snapshot, an image of its form's format, and the helper's copy.
pub(super) fn declare(
mb: &mut ModuleBuilder,
slots: &BTreeMap<u32, SnapshotForm>,
) -> BResult<Declared> {
let mut d = Declared::default();
if slots.is_empty() {
return Ok(d);
}
let sampled_type = mb.ty(SType::Int {
width: 32,
signed: false,
})?;
for (&index, &form) in slots {
let format = match form.code() {
None => crate::spv::ImageFormat::Rgba32ui,
Some((8, _)) => crate::spv::ImageFormat::Rgba8ui,
Some(_) => crate::spv::ImageFormat::Rgba16ui,
};
let ty = mb.ty(SType::Image(ImageType {
sampled_type,
dim: Dim::D2,
depth: false,
arrayed: false,
multisampled: false,
usage: ImageUsage::Storage,
format,
}))?;
let slot = ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::SnapshotTexels(index),
index,
};
let g = mb.resource(slot, StorageClass::UniformConstant, ty)?;
mb.coherent(g)?;
d.images.insert(index, g);
}
let bool_ = mb.ty(SType::Bool)?;
let no = mb.constant(Constant::Scalar {
ty: bool_,
bits: ConstBits(0),
})?;
d.helper = Some(mb.plain_global(StorageClass::Private, bool_, Some(no))?);
Ok(d)
}
/// The image variable the copy of slot `index` fetches from, with its image type: the slot's
/// image.
fn source(cx: &EmitCx<'_>, index: u32) -> Option<(GlobalId, TypeId)> {
cx.decl.families.texture.images.get(&index).copied()
}
/// Whether `form`'s codes hold every lane an image of sampled type `sampled` returns: a float
/// lane's every form but an integer one's, an integer lane's [`SnapshotForm::Bits`] or an integer
/// form of its signedness. The binder names a form of the slot's class (`SnapshotForm::of`), so a
/// pairing this rejects is an invariant failure.
fn holds(fb: &mut FunctionBuilder<'_>, form: SnapshotForm, sampled: TypeId) -> BResult<bool> {
let integer = matches!(
form,
SnapshotForm::Uint8 | SnapshotForm::Uint16 | SnapshotForm::Sint8 | SnapshotForm::Sint16
);
let signed_form = matches!(form, SnapshotForm::Sint8 | SnapshotForm::Sint16);
Ok(match fb.module().types().get(sampled)? {
SType::Float { width: 32 } => !integer,
SType::Int { width: 32, signed } => {
form == SnapshotForm::Bits || (integer && *signed == signed_form)
}
_ => false,
})
}
/// The sampled type of image type `ty`, or `None` where `ty` is no image.
fn sampled_type(fb: &mut FunctionBuilder<'_>, ty: TypeId) -> BResult<Option<TypeId>> {
Ok(match fb.module().types().get(ty)? {
SType::Image(i) => Some(i.sampled_type),
_ => None,
})
}
/// One slot's copy ([`emit_entry`]): the image the slot's reads fetch, the slot's snapshot, and
/// the form its codes are in.
#[derive(Clone, Copy, Debug)]
struct SlotCopy {
image: GlobalId,
snapshot: GlobalId,
form: SnapshotForm,
}
/// The texel of image variable `g` at `pixel`, level 0: the plain fetch the slot's reads make.
fn fetch(fb: &mut FunctionBuilder<'_>, g: GlobalId, pixel: SValue) -> BResult<SValue> {
let ptr = fb.module().global_value(g)?;
let img = fb.load(ptr, MemAccess::default())?;
let zero = fb.u32_const(0)?;
let zero = fb.module().const_value(zero)?;
let ops = ImageOperands {
lod: Some(zero),
..ImageOperands::default()
};
fb.fetch(img, pixel, &ops)
}
/// The codes of `form` of the texel image variable `g` returns at `pixel` ([`encode`]).
fn fetched_codes(
fb: &mut FunctionBuilder<'_>,
g: GlobalId,
form: SnapshotForm,
pixel: SValue,
) -> BResult<SValue> {
let texel = fetch(fb, g, pixel)?;
encode(fb, form, texel)
}
/// Store codes `bits` in snapshot variable `g` at `pixel`.
fn store(fb: &mut FunctionBuilder<'_>, g: GlobalId, pixel: SValue, bits: SValue) -> BResult<()> {
let ptr = fb.module().global_value(g)?;
let snapshot = fb.load(ptr, MemAccess::default())?;
fb.write(
snapshot,
pixel,
bits,
&ImageOperands::default(),
TexelMemory::PRIVATE,
)
}
/// The entry's block before the body ([module docs](self)), in the function's first block.
pub(super) fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> {
let fp = &cx.plan.families.fragment;
if fp.snapshot.is_empty() {
return Ok(());
}
let decl = &cx.decl.families.fragment.snapshot;
let Some(helper_copy) = decl.helper else {
return Err(cx.fail("a snapshot read without its helper's copy"));
};
let mut copies: Vec<SlotCopy> = Vec::with_capacity(fp.snapshot.len());
for (&index, &form) in &fp.snapshot {
let (Some(&s), Some((t, ty))) = (decl.images.get(&index), source(cx, index)) else {
return Err(cx.fail(format!("snapshot slot {index} is not declared")));
};
// The form's codes must hold the lanes the copy's fetch returns: the binder names a form
// of the slot's class, so a float code form over an integer source (or the other way) is
// an invariant failure, not a value for `encode` to clamp or bitcast its way through.
let Some(sampled) = sampled_type(fb, ty)? else {
return Err(cx.fail(format!("snapshot slot {index} is copied from no image")));
};
if !holds(fb, form, sampled)? {
return Err(cx.fail(format!(
"the copy of snapshot slot {index} fetches lanes its form {form:?} does not hold"
)));
}
copies.push(SlotCopy {
image: t,
snapshot: s,
form,
});
}
let Some(coord) = fp.fetch_coord else {
return Err(cx.fail("a snapshot read without its FragCoord"));
};
let frag = stage_io::object_global(cx, coord)?;
// At entry no discard has run: a helper is the device's.
let helper = if fp.demotes() {
fb.is_helper_invocation()?
} else {
let Some(g) = cx.decl.families.fragment.helper else {
return Err(cx.fail("a snapshot read without the helper input"));
};
let p = fb.module().global_value(g)?;
fb.load(p, MemAccess::default())?
};
let p = fb.module().global_value(helper_copy)?;
fb.store(p, helper, MemAccess::default())?;
let phase = cx.push_field(fb, PushField::SnapshotPhase)?;
let zero = fb.u32_const(0)?;
let zero = fb.module().const_value(zero)?;
let taking = fb.binary(BinOp::INotEqual, phase, zero)?;
fb.begin_interlock()?;
let other = fb.unary(UnOp::LogicalNot, helper)?;
let copy = fb.binary(BinOp::LogicalAnd, taking, other)?;
let arm: ArmFn<'_, ()> = Box::new(move |fb, _| {
let pixel = pixel(fb, frag)?;
for &SlotCopy {
image,
snapshot,
form,
} in &copies
{
let bits = fetched_codes(fb, image, form, pixel)?;
store(fb, snapshot, pixel, bits)?;
}
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut (), copy, arm, None)?;
fb.end_interlock()?;
// The draw that takes the snapshot runs nothing else: its write masks are all 0, and the
// function writes no memory.
let done: ArmFn<'_, ()> = Box::new(|fb, _| {
fb.ret(None)?;
Ok(ArmEnd::Exits)
});
fb.if_(&mut (), taking, done, None)?;
Ok(())
}
/// `uvec2(uint(FragCoord.x), uint(FragCoord.y))` from `FragCoord` variable `frag`: a non-helper
/// fragment's coordinates lie in its pixel `[p, p + 1)`, at or above 0.
fn pixel(fb: &mut FunctionBuilder<'_>, frag: GlobalId) -> BResult<SValue> {
let frag = fb.module().global_value(frag)?;
let frag = fb.load(frag, MemAccess::default())?;
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let uvec2 = fb.module().ty(SType::Vector { elem: u32_, len: 2 })?;
let fx = fb.composite_extract(frag, &[0])?;
let fy = fb.composite_extract(frag, &[1])?;
let x = fb.convert(ConvOp::ConvertFToU, fx, u32_)?;
let y = fb.convert(ConvOp::ConvertFToU, fy, u32_)?;
fb.composite_construct(uvec2, &[x, y])
}
/// The `uvec4` of 32-bit lanes `texel`'s codes in `form` ([module docs](self)), for the
/// snapshot's write: each lane's bits for [`SnapshotForm::Bits`], else each lane's code, its low
/// 8 or 16 bits.
pub(crate) fn encode(
fb: &mut FunctionBuilder<'_>,
form: SnapshotForm,
texel: SValue,
) -> BResult<SValue> {
let u = lanes(Held::Int {
bits: 32,
container: 32,
});
let uvec4 = ty(fb, u)?;
let Some((width, signed)) = form.code() else {
return match fb.value_ty(texel)? == uvec4 {
true => Ok(texel),
false => fb.convert(ConvOp::Bitcast, texel, uvec4),
};
};
let codes = match form {
SnapshotForm::Unorm8
| SnapshotForm::Unorm16
| SnapshotForm::Snorm8
| SnapshotForm::Snorm16 => {
let f = lanes(Held::Float(FloatFmt::F32));
let low = match signed {
true => (-1.0f32).to_bits(),
false => 0,
};
let (low, high) = (
splat(fb, f, u64::from(low))?,
splat(fb, f, u64::from(1.0f32.to_bits()))?,
);
let clamped = fb.glsl(GlslOp::FClamp, &[texel, low, high])?;
let d = splat(fb, f, u64::from((scale(width, signed) as f32).to_bits()))?;
let scaled = fb.binary(BinOp::FMul, clamped, d)?;
let code = fb.glsl(GlslOp::RoundEven, &[scaled])?;
match signed {
true => {
let ivec4 = signed_lanes(fb)?;
let c = fb.convert(ConvOp::ConvertFToS, code, ivec4)?;
fb.convert(ConvOp::Bitcast, c, uvec4)?
}
false => fb.convert(ConvOp::ConvertFToU, code, uvec4)?,
}
}
SnapshotForm::Half => narrow::to_bits(fb, lanes(Held::Float(FloatFmt::Half)), texel)?,
_ => match fb.value_ty(texel)? == uvec4 {
true => texel,
false => fb.convert(ConvOp::Bitcast, texel, uvec4)?,
},
};
mask_codes(fb, form, codes)
}
/// The `uvec4` of codes `codes` (32-bit lanes) kept to `form`'s code width: the snapshot's image
/// holds that many bits a lane, so a lane of a wider value loses the rest.
fn mask_codes(fb: &mut FunctionBuilder<'_>, form: SnapshotForm, codes: SValue) -> BResult<SValue> {
let u = lanes(Held::Int {
bits: 32,
container: 32,
});
let uvec4 = ty(fb, u)?;
let codes = match fb.value_ty(codes)? == uvec4 {
true => codes,
false => fb.convert(ConvOp::Bitcast, codes, uvec4)?,
};
let Some((width, _)) = form.code() else {
return Ok(codes);
};
let mask = splat(fb, u, (1u64 << width) - 1)?;
fb.binary(BinOp::BitwiseAnd, codes, mask)
}
/// The value of type `texel` the codes `codes` (a `uvec4` read from the snapshot) of `form` stand
/// for ([module docs](self)): the inverse of [`encode`] on every value it encodes.
pub(crate) fn decode(
fb: &mut FunctionBuilder<'_>,
form: SnapshotForm,
codes: SValue,
texel: TypeId,
) -> BResult<SValue> {
let u = lanes(Held::Int {
bits: 32,
container: 32,
});
let Some((width, signed)) = form.code() else {
return match fb.value_ty(codes)? == texel {
true => Ok(codes),
false => fb.convert(ConvOp::Bitcast, codes, texel),
};
};
// A signed code's lanes, sign-extended from their low `width` bits.
let extended = |fb: &mut FunctionBuilder<'_>| -> BResult<SValue> {
let ivec4 = signed_lanes(fb)?;
let shift = splat(fb, u, u64::from(32 - width))?;
let up = fb.binary(BinOp::ShiftLeftLogical, codes, shift)?;
let up = fb.convert(ConvOp::Bitcast, up, ivec4)?;
fb.binary(BinOp::ShiftRightArithmetic, up, shift)
};
// A normalized code `c` times the `f32` nearest `1 / D`.
let f = lanes(Held::Float(FloatFmt::F32));
let reciprocal = |fb: &mut FunctionBuilder<'_>, signed: bool| -> BResult<SValue> {
let r = 1.0 / scale(width, signed) as f32;
splat(fb, f, u64::from(r.to_bits()))
};
let value = match form {
SnapshotForm::Unorm8 | SnapshotForm::Unorm16 => {
let vec4 = ty(fb, f)?;
let c = fb.convert(ConvOp::ConvertUToF, codes, vec4)?;
let r = reciprocal(fb, false)?;
fb.binary(BinOp::FMul, c, r)?
}
SnapshotForm::Snorm8 | SnapshotForm::Snorm16 => {
let n = extended(fb)?;
let vec4 = ty(fb, f)?;
let c = fb.convert(ConvOp::ConvertSToF, n, vec4)?;
let r = reciprocal(fb, true)?;
let v = fb.binary(BinOp::FMul, c, r)?;
// `-2^(b-1)` reads `-1`, as the code above it.
let low = splat(fb, f, u64::from((-1.0f32).to_bits()))?;
fb.glsl(GlslOp::FMax, &[v, low])?
}
SnapshotForm::Half => narrow::from_bits(fb, lanes(Held::Float(FloatFmt::Half)), codes)?,
_ => match signed {
true => extended(fb)?,
false => codes,
},
};
match fb.value_ty(value)? == texel {
true => Ok(value),
false => fb.convert(ConvOp::Bitcast, value, texel),
}
}
/// Whether `form` is a normalized form, whose read decodes its codes by the device's arithmetic.
fn normalized(form: SnapshotForm) -> bool {
matches!(
form,
SnapshotForm::Unorm8 | SnapshotForm::Unorm16 | SnapshotForm::Snorm8 | SnapshotForm::Snorm16
)
}
/// The scale `D` of a normalized code of `width` bits: `2^b - 1`, or `2^(b-1) - 1` where signed.
fn scale(width: u8, signed: bool) -> u32 {
match signed {
true => (1u32 << (width - 1)) - 1,
false => (1u32 << width) - 1,
}
}
/// The four-lane form of `held`.
fn lanes(held: Held) -> Form {
Form { held, lanes: 4 }
}
/// The type `ivec4`.
fn signed_lanes(fb: &mut FunctionBuilder<'_>) -> BResult<TypeId> {
let i32_ = fb.module().ty(SType::Int {
width: 32,
signed: true,
})?;
fb.module().ty(SType::Vector { elem: i32_, len: 4 })
}
/// What a read of a snapshot slot needs, made in the open block before the read: the snapshot's
/// image, whether the invocation is no helper, and the type the slot's fetch returns.
#[derive(Clone, Copy, Debug)]
pub(crate) struct SnapshotRead {
snapshot: SValue,
other: SValue,
texel: TypeId,
form: SnapshotForm,
}
/// The snapshot read standing for a fetch of texture slot `index` from image `img` (loaded from
/// the image the copy fetches from), or `None` where the function reads the slot
/// directly. The read must be the fetch of a single-sampled 2D level the copy makes: anything
/// else is an invariant failure, since the slot's interface fact admits no other.
pub(crate) fn prepare(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
index: u32,
img: SValue,
plain_fetch: bool,
) -> BResult<Option<SnapshotRead>> {
let Some(&form) = cx.plan.families.fragment.snapshot.get(&index) else {
return Ok(None);
};
if !plain_fetch {
return Err(cx.fail(format!(
"a read of snapshot slot {index} that is no plain fetch"
)));
}
let ty = fb.value_ty(img)?;
let image = match fb.module().types().get(ty)? {
SType::Image(i) => *i,
_ => return Err(cx.fail(format!("snapshot slot {index} read from no image"))),
};
if image.dim != Dim::D2 || image.arrayed || image.multisampled {
return Err(cx.fail(format!("snapshot slot {index} is no single 2D image")));
}
if !holds(fb, form, image.sampled_type)? {
return Err(cx.fail(format!(
"snapshot slot {index} returns lanes its form {form:?} does not hold"
)));
}
let texel = fb.module().ty(SType::Vector {
elem: image.sampled_type,
len: 4,
})?;
let decl = &cx.decl.families.fragment.snapshot;
let (Some(&s), Some(helper)) = (decl.images.get(&index), decl.helper) else {
return Err(cx.fail(format!("snapshot slot {index} is not declared")));
};
let ptr = fb.module().global_value(s)?;
let snapshot = fb.load(ptr, MemAccess::default())?;
let ptr = fb.module().global_value(helper)?;
let h = fb.load(ptr, MemAccess::default())?;
let other = fb.unary(UnOp::LogicalNot, h)?;
Ok(Some(SnapshotRead {
snapshot,
other,
texel,
form,
}))
}
/// The texel at `coord` a read of `r` returns: the snapshot's codes decoded as the slot's lanes
/// ([`decode`]), in a non-helper invocation, and 0 in a helper, which reads nothing.
pub(crate) fn read(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
r: SnapshotRead,
coord: SValue,
) -> BResult<SValue> {
let texel = r.texel;
let snapshot = r.snapshot;
let form = r.form;
let read: ArmFn<'_, ()> = Box::new(move |fb, _| {
let codes = fb.read(
snapshot,
coord,
&ImageOperands::default(),
TexelMemory::PRIVATE,
)?;
let value = decode(fb, form, codes, texel)?;
Ok(ArmEnd::FallThrough(vec![value]))
});
let nothing: ArmFn<'_, ()> = Box::new(move |fb, _| {
let zero = fb.module().constant(Constant::Null { ty: texel })?;
let zero = fb.module().const_value(zero)?;
Ok(ArmEnd::FallThrough(vec![zero]))
});
let merged = fb.if_(&mut (), r.other, read, Some(nothing))?;
match merged.0.as_slice() {
[v] => Ok(*v),
_ => Err(cx.fail("a snapshot read without its merged texel")),
}
}
@@ -1,557 +0,0 @@
//! A fragment function's `[[stencil]]` output without `VK_EXT_shader_stencil_export`: the
//! shader-side stencil.
//!
//! **Metal's semantics** (measured). The output's low 8 bits `r` are the stencil reference of both
//! faces. The stencil test `(r & readMask) cmp (s & readMask)` against the stored value `s` runs
//! before the depth test, and the face's operation writes `s' = (s & ~writeMask) | (op(s, r) &
//! writeMask)`, per sample in primitive order. A fragment that fails is dropped; a discarded one
//! changes nothing. `[[early_fragment_tests]]` does not compile beside the output, so the tests
//! always follow the function.
//!
//! **The form.** Vulkan's fixed-function stencil test takes one reference per draw, so no state
//! can give each fragment its own. Where the device has the ordered pixel interlock
//! ([`device_form`]), the function applies the test itself: its body runs inside the interlock
//! (`fragment::wrap_entry`), and at each return, unless a discard was recorded, it reads the
//! pixel's value from a coherent `R8Uint` shadow of the stencil (`SyntheticBinding::ShadowStencil`,
//! texel `(x, y)` for pixel `(x, y)`), takes the face's state from `PushField::ShadowStencilState`
//! by `FrontFacing`, applies Metal's comparison and the stencil-failure or pass operation under the
//! masks, writes the shadow, and records a failing fragment as discarded, which the entry kills
//! after the critical section. The ordered interlock makes the read, the operation, and the write
//! of each fragment of a pixel one step in primitive order, across the draws of a subpass; the
//! device-scope coherence of every access inside the critical section (`sync::memory_model`) makes
//! each step's write visible to the next. The fixed-function stencil test is off; the depth test
//! stays fixed-function after the function, so the module never declares early tests. The consumer
//! keeps the shadow (`GraphicsState::shadow_stencil`).
//!
//! **Multisampled** (compiled for a pipeline of more than one sample,
//! `LoweringInputs::multisampled`). Metal tests and writes each covered sample of the fragment
//! against the one reference. The shadow is then a multisampled storage image of the pipeline's
//! count (sample `s` of texel `(x, y)` is sample `s` of pixel `(x, y)`), and the step runs once per
//! sample of the invocation's `SampleMask` input: every covered sample of a pixel-rate invocation,
//! the one sample of an invocation under sample shading (a function that writes memory or reads
//! `[[sample_id]]`). The function writes the samples that pass to the `SampleMask` output, so a
//! failing sample gets no color or depth, and a fragment no sample of which passes is recorded as
//! discarded. The form reads only the invocation's own coverage, never Metal's `[[sample_mask]]`
//! (the pixel's), so the stage interface states the output and not the input.
//!
//! **Exact only where the stencil write cannot depend on the depth result**: the binder refuses a
//! state with a depth attachment, a depth comparison other than `Always`, and a face whose
//! depth-failure operation differs from its pass operation; link refuses alpha to coverage. A
//! returned sample mask and an imageblock beside the output are not implemented.
use crate::air::abi::OutputRole;
use crate::air::ir::TypeId as AirTypeId;
use crate::device::requirements::{FormatUsage, VkExtension, VkFeature};
use crate::device::DeviceProfile;
use crate::error::{Capability, Error, Feature, Unsupported};
use crate::lower::arith::Form;
use crate::lower::emit::EmitCx;
use crate::lower::select::SelectCx;
use crate::lower::stage_io::{self, Returned};
use crate::lower::sync::memory_model;
use crate::metal::format::{without_format_gaps, StorageUse};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, SyntheticBinding};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{GlobalId, Value as SValue};
use crate::spirv::ir::{
BinOp, Dim, GlslOp, ImageOperands, ImageType, ImageUsage, MemAccess, StorageClass,
Type as SType, UnOp,
};
use crate::vk;
/// The shadow's format: Metal's stencil values are 8-bit.
pub(crate) const SHADOW_FORMAT: vk::Format = vk::Format::R8_UINT;
/// Bit 31 of a face's word: the pass has a stencil attachment to test against.
pub(crate) const ATTACHED_BIT: u32 = 1 << 31;
/// The word of one face of `PushField::ShadowStencilState` (see its docs): Metal's compare
/// function `compare` and operations `stencil_failure` and `pass` by their raw values, the read
/// and write masks' low 8 bits, and [`ATTACHED_BIT`] when `attached`.
pub(crate) fn face_word(
compare: u32,
stencil_failure: u32,
pass: u32,
read_mask: u32,
write_mask: u32,
attached: bool,
) -> u32 {
(compare & 7)
| (stencil_failure & 7) << 3
| (pass & 7) << 6
| (read_mask & 0xFF) << 9
| (write_mask & 0xFF) << 17
| if attached { ATTACHED_BIT } else { 0 }
}
/// The shader-side stencil's plan: the output's field of the returned value and its form, and
/// how the module declares the shadow.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShadowStencil {
/// The returned value's field that holds the output (0 for a returned value itself).
pub field: u32,
pub form: Form,
/// The declared SPIR-V image format: `R8ui`, or `Unknown` for a formatless declaration.
pub declared: crate::spv::ImageFormat,
/// The stage interface's `FrontFacing` object, which selects the face's state.
pub front_facing: usize,
/// The multisampled form's coverage objects (see the module docs); `None` for one sample.
pub samples: Option<SampleMasks>,
}
/// The stage interface's objects of the multisampled form: the `SampleMask` input it tests and
/// the `SampleMask` output it writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SampleMasks {
pub covered: usize,
pub kept: usize,
}
/// The declaration of the shadow on `p`, or what the device lacks for the form (see the module
/// docs): the ordered pixel interlock, fragment stores, the shadow's format as a storage image,
/// declared `R8ui` where the device has the extended storage formats, else without a format
/// where it grants that access, and, `multisampled`, multisampled storage images. The refusal names
/// both ways to translate the output: the extension, or what the form lacks (the extended storage
/// formats for the declaration, as the interlocked framebuffer fetch names them for a typed
/// format).
pub(crate) fn device_form(
p: &DeviceProfile,
multisampled: bool,
) -> Result<crate::spv::ImageFormat, Unsupported> {
let f = p.fields();
let mut missing = Vec::new();
if !super::fetch::interlock_forms(p) {
missing.push(Capability::Feature(VkFeature::FragmentShaderPixelInterlock));
}
if !f.leaf.fragment_stores_and_atomics {
missing.push(Capability::Feature(VkFeature::FragmentStoresAndAtomics));
}
if multisampled && !f.images.storage_multisample {
missing.push(Capability::Feature(
VkFeature::ShaderStorageImageMultisample,
));
}
if !p.supports_format(SHADOW_FORMAT, FormatUsage::StorageImage) {
missing.push(Capability::Format {
format: SHADOW_FORMAT,
usage: FormatUsage::StorageImage,
});
}
let use_ = StorageUse::texture(true, true);
let declared = if f.images.storage_extended_formats {
Some(crate::spv::ImageFormat::R8ui)
} else if without_format_gaps(SHADOW_FORMAT, use_, p).is_empty() {
Some(crate::spv::ImageFormat::Unknown)
} else {
// `R8ui` is an extended format: the typed declaration needs only the feature.
missing.push(Capability::Feature(
VkFeature::ShaderStorageImageExtendedFormats,
));
None
};
match declared {
Some(d) if missing.is_empty() => Ok(d),
_ => Err(Unsupported::needs_any_of(
Feature::StencilExport,
vec![
vec![Capability::Extension(VkExtension::ExtShaderStencilExport)],
missing,
],
)),
}
}
fn not_implemented() -> Error {
Unsupported::not_implemented(Feature::StencilExport).into()
}
/// Plan the `[[stencil]]` output of AIR type `ty`, held in field `field` of the returned value,
/// as the shader-side stencil (`stage_io` plans the entry's other outputs; the caller checked the
/// device has no stencil export).
pub fn select_output(cx: &mut SelectCx<'_>, field: u32, ty: AirTypeId) -> Result<(), Error> {
let multisampled = cx.inputs.multisampled;
let declared = device_form(cx.profile, multisampled)?;
let form = stage_io::int_scalar_output(cx, ty)?;
// A returned sample mask would drop samples after the function's write.
let sample_mask = cx
.entry
.ep
.outputs
.iter()
.any(|o| matches!(o.role, OutputRole::SampleMask));
if sample_mask {
return Err(not_implemented());
}
if cx.families.fragment.stencil.is_some() {
return Err(cx.invariant("a second stencil output"));
}
let coord = stage_io::frag_coord(cx);
let front_facing = stage_io::front_facing(cx);
let samples = multisampled.then(|| {
let (covered, kept) = stage_io::sample_masks(cx);
SampleMasks { covered, kept }
});
let fp = &mut cx.families.fragment;
fp.fetch_coord = Some(coord);
fp.stencil = Some(ShadowStencil {
field,
form,
declared,
front_facing,
samples,
});
cx.facts.insert(RuntimeFact::ShadowStencil {
formatless: declared == crate::spv::ImageFormat::Unknown,
multisampled,
});
cx.push.insert(PushField::ShadowStencilState);
cx.descriptors.storage_images = cx.descriptors.storage_images.saturating_add(1);
Ok(())
}
/// Check the plan once every output and parameter is planned: an imageblock beside the output
/// is not implemented (what Metal's stencil test does to its writes is not read).
pub(super) fn finish(cx: &SelectCx<'_>) -> Result<(), Error> {
let fp = &cx.families.fragment;
if fp.stencil.is_some() && fp.imageblock.is_some() {
return Err(not_implemented());
}
Ok(())
}
/// Declare the shadow: a 2D `uint` storage image of the planned declaration, multisampled for the
/// multisampled form.
pub(super) fn declare(
mb: &mut ModuleBuilder,
plan: Option<&ShadowStencil>,
) -> BResult<Option<GlobalId>> {
let Some(plan) = plan else {
return Ok(None);
};
let sampled_type = mb.ty(SType::Int {
width: 32,
signed: false,
})?;
let ty = mb.ty(SType::Image(ImageType {
sampled_type,
dim: Dim::D2,
depth: false,
arrayed: false,
multisampled: plan.samples.is_some(),
usage: ImageUsage::Storage,
format: plan.declared,
}))?;
let slot = ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::Synthetic(SyntheticBinding::ShadowStencil),
index: 0,
};
mb.resource(slot, StorageClass::UniformConstant, ty)
.map(Some)
}
/// A `u32` constant.
fn u32_value(fb: &mut FunctionBuilder<'_>, v: u32) -> BResult<SValue> {
let c = fb.u32_const(v)?;
fb.module().const_value(c)
}
/// The bits `[offset, offset + width)` of `word`.
pub(super) fn field_of(
fb: &mut FunctionBuilder<'_>,
word: SValue,
offset: u32,
width: u32,
) -> BResult<SValue> {
let o = u32_value(fb, offset)?;
let w = u32_value(fb, width)?;
fb.bit_field_extract(false, word, o, w)
}
/// `choices[code]` for a `code` in `0..8`, as a chain of selections.
fn select_by(fb: &mut FunctionBuilder<'_>, code: SValue, choices: [SValue; 8]) -> BResult<SValue> {
let mut out = choices[7];
for (i, &choice) in choices.iter().enumerate().take(7).rev() {
let k = u32_value(fb, i as u32)?;
let is = fb.binary(BinOp::IEqual, code, k)?;
out = fb.select(is, choice, out)?;
}
Ok(out)
}
/// Whether `a cmp b` under Metal's compare function `code` (`MTLCompareFunction`: never, less,
/// equal, less-equal, greater, not-equal, greater-equal, always), with `a` the masked reference
/// and `b` the masked stored value.
pub(super) fn compare(
fb: &mut FunctionBuilder<'_>,
code: SValue,
a: SValue,
b: SValue,
) -> BResult<SValue> {
let never = super::bool_const(fb, false)?;
let always = super::bool_const(fb, true)?;
let less = fb.binary(BinOp::ULessThan, a, b)?;
let equal = fb.binary(BinOp::IEqual, a, b)?;
let less_equal = fb.binary(BinOp::ULessThanEqual, a, b)?;
let greater = fb.binary(BinOp::UGreaterThan, a, b)?;
let not_equal = fb.binary(BinOp::INotEqual, a, b)?;
let greater_equal = fb.binary(BinOp::UGreaterThanEqual, a, b)?;
select_by(
fb,
code,
[
never,
less,
equal,
less_equal,
greater,
not_equal,
greater_equal,
always,
],
)
}
/// The 8-bit value Metal's stencil operation `code` (`MTLStencilOperation`: keep, zero, replace,
/// increment-clamp, decrement-clamp, invert, increment-wrap, decrement-wrap) makes of stored
/// value `s` with reference `r`.
pub(super) fn operation(
fb: &mut FunctionBuilder<'_>,
code: SValue,
s: SValue,
r: SValue,
) -> BResult<SValue> {
let zero = u32_value(fb, 0)?;
let one = u32_value(fb, 1)?;
let max = u32_value(fb, 0xFF)?;
let up = fb.binary(BinOp::IAdd, s, one)?;
let down = fb.binary(BinOp::ISub, s, one)?;
let at_max = fb.binary(BinOp::IEqual, s, max)?;
let at_zero = fb.binary(BinOp::IEqual, s, zero)?;
let increment_clamp = fb.select(at_max, max, up)?;
let decrement_clamp = fb.select(at_zero, zero, down)?;
let invert = fb.binary(BinOp::BitwiseXor, s, max)?;
let increment_wrap = fb.binary(BinOp::BitwiseAnd, up, max)?;
let decrement_wrap = fb.binary(BinOp::BitwiseAnd, down, max)?;
select_by(
fb,
code,
[
s,
zero,
r,
increment_clamp,
decrement_clamp,
invert,
increment_wrap,
decrement_wrap,
],
)
}
/// The values one step of the test reads: the face's word, the reference, the pixel, the
/// shadow, and the shadow's texel coherence.
#[derive(Clone, Copy)]
struct Step {
word: SValue,
reference: SValue,
pixel: SValue,
image: SValue,
mem: crate::spirv::ir::TexelMemory,
}
/// Apply Metal's stencil test and the face's operation to the shadow's texel at `step.pixel`
/// (its sample `sample` in the multisampled form): read it, compare under the read mask, write the
/// stencil-failure or pass operation's value under the write mask. Whether the test passed.
fn apply(fb: &mut FunctionBuilder<'_>, step: Step, sample: Option<SValue>) -> BResult<SValue> {
let Step {
word,
reference,
pixel,
image,
mem,
} = step;
let operands = ImageOperands {
sample,
..ImageOperands::default()
};
let texel = fb.read(image, pixel, &operands, mem)?;
let stored = fb.composite_extract(texel, &[0])?;
let compare_code = field_of(fb, word, 0, 3)?;
let fail_code = field_of(fb, word, 3, 3)?;
let pass_code = field_of(fb, word, 6, 3)?;
let read_mask = field_of(fb, word, 9, 8)?;
let write_mask = field_of(fb, word, 17, 8)?;
let a = fb.binary(BinOp::BitwiseAnd, reference, read_mask)?;
let b = fb.binary(BinOp::BitwiseAnd, stored, read_mask)?;
let passed = compare(fb, compare_code, a, b)?;
let code = fb.select(passed, pass_code, fail_code)?;
let written = operation(fb, code, stored, reference)?;
let max = u32_value(fb, 0xFF)?;
let keep_mask = fb.binary(BinOp::BitwiseXor, write_mask, max)?;
let kept_bits = fb.binary(BinOp::BitwiseAnd, stored, keep_mask)?;
let new_bits = fb.binary(BinOp::BitwiseAnd, written, write_mask)?;
let value = fb.binary(BinOp::BitwiseOr, kept_bits, new_bits)?;
let u32_ = u32_type(fb)?;
let uvec4 = fb.module().ty(SType::Vector { elem: u32_, len: 4 })?;
let zero = u32_value(fb, 0)?;
let texel = fb.composite_construct(uvec4, &[value, zero, zero, zero])?;
fb.write(image, pixel, texel, &operands, mem)?;
Ok(passed)
}
/// The `u32` type.
fn u32_type(fb: &mut FunctionBuilder<'_>) -> BResult<crate::spirv::ids::TypeId> {
fb.module().ty(SType::Int {
width: 32,
signed: false,
})
}
/// A pointer to element 0 of the stage interface's array object `i` (a `SampleMask`).
fn element0(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, i: usize) -> BResult<SValue> {
let g = stage_io::object_global(cx, i)?;
let base = fb.module().global_value(g)?;
let zero = u32_value(fb, 0)?;
fb.access_chain(base, &[zero])
}
/// The multisampled form's step over the samples of `covered` (see the module docs): the mask
/// of those that pass.
fn apply_per_sample(fb: &mut FunctionBuilder<'_>, step: Step, covered: SValue) -> BResult<SValue> {
let u32_ = u32_type(fb)?;
let zero_c = fb.u32_const(0)?;
let left_var = fb.local_var(u32_, Some(zero_c))?;
let left = fb.var_ptr(left_var)?;
let kept_var = fb.local_var(u32_, Some(zero_c))?;
let kept = fb.var_ptr(kept_var)?;
fb.store(left, covered, MemAccess::default())?;
let body: LoopFn<'_, ()> = Box::new(move |fb, ctx, lc| {
let rest = fb.load(left, MemAccess::default())?;
let zero = u32_value(fb, 0)?;
let done = fb.binary(BinOp::IEqual, rest, zero)?;
let exit: ArmFn<'_, ()> = Box::new(move |fb, _| {
lc.break_(fb)?;
Ok(ArmEnd::Exits)
});
fb.if_(ctx, done, exit, None)?;
// The lowest sample left, then the others.
let sample = fb.glsl(GlslOp::FindILsb, &[rest])?;
let one = u32_value(fb, 1)?;
let below = fb.binary(BinOp::ISub, rest, one)?;
let others = fb.binary(BinOp::BitwiseAnd, rest, below)?;
fb.store(left, others, MemAccess::default())?;
let passed = apply(fb, step, Some(sample))?;
let bit = fb.binary(BinOp::ShiftLeftLogical, one, sample)?;
let bit = fb.select(passed, bit, zero)?;
let so_far = fb.load(kept, MemAccess::default())?;
let so_far = fb.binary(BinOp::BitwiseOr, so_far, bit)?;
fb.store(kept, so_far, MemAccess::default())?;
Ok(())
});
fb.loop_(&mut (), LoopSpec::default(), body)?;
fb.load(kept, MemAccess::default())
}
/// At a return of returned value `v`: unless a discard was recorded, apply Metal's stencil test
/// and operation of the fragment's face to the shadow at its pixel (at each sample of the
/// invocation in the multisampled form) with the output as the reference, and record a failing
/// fragment as discarded (see the module docs). The multisampled form first keeps every covered
/// sample in the `SampleMask` output, then the samples that pass. Called before the other writes
/// at the return, which a recorded discard skips.
pub(super) fn emit_return(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
v: Option<crate::air::ir::ValueId>,
) -> BResult<()> {
let Some(plan) = cx.plan.families.fragment.stencil else {
return Ok(());
};
let Some(v) = v else {
return Err(cx.fail("a stencil output without a returned value"));
};
let Some(shadow) = cx.decl.families.fragment.shadow_stencil else {
return Err(cx.fail("the shadow stencil is not declared"));
};
let Some(discarded) = cx.decl.families.fragment.discarded else {
return Err(cx.fail("a shader-side stencil without its discard predicate"));
};
let x = cx.operand(fb, v)?;
let output = match cx.plan.families.stage_io.returned {
Returned::Struct => fb.composite_extract(x, &[plan.field])?,
Returned::Value => x,
Returned::Void => return Err(cx.fail("a stencil output of a void entry")),
};
let max = u32_value(fb, 0xFF)?;
let reference = fb.binary(BinOp::BitwiseAnd, output, max)?;
let state = cx.push_field(fb, PushField::ShadowStencilState)?;
let facing = stage_io::object_global(cx, plan.front_facing)?;
let pixel = super::fetch::pixel(cx, fb)?;
let mem = memory_model::coherence(cx.plan).texel(fb)?;
let masks = match plan.samples {
// The coverage word, from the entry's copy inside an interlocked body.
Some(m) => Some((
stage_io::coverage_in(cx, fb, m.covered)?,
element0(cx, fb, m.kept)?,
)),
None => None,
};
let facing = fb.module().global_value(facing)?;
let front = fb.load(facing, MemAccess::default())?;
let front_word = fb.composite_extract(state, &[0])?;
let back_word = fb.composite_extract(state, &[1])?;
let word = fb.select(front, front_word, back_word)?;
let attached_bit = u32_value(fb, ATTACHED_BIT)?;
let attached = fb.binary(BinOp::BitwiseAnd, word, attached_bit)?;
let zero = u32_value(fb, 0)?;
let attached = fb.binary(BinOp::INotEqual, attached, zero)?;
let p = fb.module().global_value(discarded)?;
let was = fb.load(p, MemAccess::default())?;
let kept = fb.unary(UnOp::LogicalNot, was)?;
let test = fb.binary(BinOp::LogicalAnd, kept, attached)?;
// Every covered sample stays unless the test drops it.
let covered = match masks {
Some((c, kept)) => {
fb.store(kept, c, MemAccess::default())?;
Some((c, kept))
}
None => None,
};
let arm: ArmFn<'_, ()> = Box::new(move |fb, _| {
let image = fb.module().global_value(shadow)?;
let image = fb.load(image, MemAccess::default())?;
let step = Step {
word,
reference,
pixel,
image,
mem,
};
// A failing fragment is dropped: the entry kills it after the critical section, and
// the return's other writes skip it. In the multisampled form, a fragment of which
// some samples pass keeps those.
let failed = match covered {
None => {
let passed = apply(fb, step, None)?;
fb.unary(UnOp::LogicalNot, passed)?
}
Some((covered, kept)) => {
let passed = apply_per_sample(fb, step, covered)?;
fb.store(kept, passed, MemAccess::default())?;
let zero = u32_value(fb, 0)?;
fb.binary(BinOp::IEqual, passed, zero)?
}
};
let p = fb.module().global_value(discarded)?;
fb.store(p, failed, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut (), test, arm, None)?;
Ok(())
}
#[cfg(test)]
mod tests;
@@ -1,121 +0,0 @@
//! The shader-side stencil's device form: where it is declared, and what the refusal names where it
//! is not; and the push word's layout.
use super::*;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::error::Needs;
/// Committed profile `stem` with `features` removed from its description.
fn profile(stem: &str, features: &[VkFeature]) -> DeviceProfile {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles")
.join(format!("{stem}.json"));
let text = std::fs::read_to_string(path).expect("profile");
let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
for f in features {
desc.features.remove(f);
}
Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES)
.expect("device")
.profile()
.clone()
}
fn alternatives(u: Unsupported) -> Vec<Vec<Capability>> {
assert_eq!(u.feature, Feature::StencilExport);
match u.needs {
Needs::AnyOf(a) => a,
other => panic!("{other:?}"),
}
}
/// Every NVIDIA profile (no stencil export, with the ordered interlock) declares the shadow as
/// `R8ui`. A device that also lacks the extended storage formats, and `R8_UINT` storage without a
/// format, names them; the extension is always the first alternative.
#[test]
fn nvidia_declares_the_shadow_and_a_device_without_the_interlock_names_both_ways() {
for stem in [
"nvidia-rtx50-linux",
"nvidia-pascal-linux",
"nvidia-rtx5080-laptop",
] {
let p = profile(stem, &[]);
assert!(!p.fields().fragment.stencil_export, "{stem}");
assert_eq!(
device_form(&p, false),
Ok(crate::spv::ImageFormat::R8ui),
"{stem}"
);
assert_eq!(
device_form(&p, true),
Ok(crate::spv::ImageFormat::R8ui),
"{stem}"
);
}
let ext = vec![Capability::Extension(VkExtension::ExtShaderStencilExport)];
let p = profile(
"nvidia-rtx50-linux",
&[
VkFeature::FragmentShaderPixelInterlock,
VkFeature::FragmentStoresAndAtomics,
],
);
let a = alternatives(device_form(&p, false).expect_err("no interlock"));
assert_eq!(a[0], ext);
assert_eq!(
a[1],
[
Capability::Feature(VkFeature::FragmentShaderPixelInterlock),
Capability::Feature(VkFeature::FragmentStoresAndAtomics),
]
);
let stem = "runtime-floor";
let a = alternatives(device_form(&profile(stem, &[]), false).expect_err(stem));
assert_eq!(a.len(), 2, "{stem}");
assert_eq!(a[0], ext, "{stem}");
assert!(
a[1].contains(&Capability::Feature(
VkFeature::FragmentShaderPixelInterlock
)),
"{stem}: {a:?}"
);
}
/// The word's fields sit where `PushField::ShadowStencilState` states, each masked to its width.
/// The multisampled form also needs multisampled storage images: a device without them names
/// `shaderStorageImageMultisample` beside the extension, and the single-sample form does not.
#[test]
fn the_multisampled_form_names_multisampled_storage_images() {
let p = profile(
"nvidia-rtx50-linux",
&[VkFeature::ShaderStorageImageMultisample],
);
assert_eq!(device_form(&p, false), Ok(crate::spv::ImageFormat::R8ui));
let a = alternatives(device_form(&p, true).expect_err("no multisampled storage"));
assert_eq!(
a,
[
vec![Capability::Extension(VkExtension::ExtShaderStencilExport)],
vec![Capability::Feature(
VkFeature::ShaderStorageImageMultisample
)],
]
);
}
#[test]
fn a_face_word_packs_the_state_in_its_documented_bits() {
let w = face_word(5, 2, 7, 0x0F, 0xF0, true);
assert_eq!(w & 7, 5);
assert_eq!((w >> 3) & 7, 2);
assert_eq!((w >> 6) & 7, 7);
assert_eq!((w >> 9) & 0xFF, 0x0F);
assert_eq!((w >> 17) & 0xFF, 0xF0);
assert_eq!(w & ATTACHED_BIT, ATTACHED_BIT);
// Wider masks keep their low 8 bits, as Metal's 8-bit stencil does.
let w = face_word(7, 0, 0, u32::MAX, 0x1FF, false);
assert_eq!((w >> 9) & 0xFF, 0xFF);
assert_eq!((w >> 17) & 0xFF, 0xFF);
assert_eq!(w & ATTACHED_BIT, 0);
assert_eq!(w & 0x7E00_0000, 0, "bits 25 to 30 stay clear");
}
@@ -3,8 +3,7 @@
//!
//! An attachment the device renders through a view of its word (`metal::format::WordAttachment`)
//! has one component, which the device writes whole, so the device's write mask cannot keep a
//! field of it. On a device that orders fetch through the pixel interlock the storage form merges
//! the word (`fetch`); on one that orders it through input attachments with rasterization-order
//! field of it. On a device that orders fetch through input attachments with rasterization-order
//! access (lavapipe) the function reads the texel's word through the attachment's input attachment
//! at its first output's write (at the invocation's sample in a multisampled pipeline) and stores
//! Metal's word of the output (`stage_io::word_color::encode`) with the fields of the channels the
-6
View File
@@ -167,8 +167,6 @@ pub const fn shape(f: PushField) -> FieldShape {
PushField::DispatchRegion | PushField::StageInRegion => FieldShape::UVec4Array(2),
// A draw's depth clamp range, two `f32`s' bits.
PushField::DepthClampRange => FieldShape::UVec2,
// Which of a snapshot variant's draws runs.
PushField::SnapshotPhase => FieldShape::U32,
// The alpha test reference's code.
PushField::AlphaTestReference => FieldShape::U32,
// The blend color and one minus it, four `f32`s' bits each.
@@ -179,12 +177,8 @@ pub const fn shape(f: PushField) -> FieldShape {
PushField::BaseVertexInstance => FieldShape::UVec2,
// The draw's vertices per primitive.
PushField::VerticesPerPrimitive => FieldShape::U32,
// The front face's word, then the back face's.
PushField::ShadowStencilState => FieldShape::UVec2,
// A zero word, the index count, the first instance, and the base vertex.
PushField::CaptureLayout => FieldShape::UVec4Array(1),
// Four bits of kept channels per color attachment.
PushField::StorageKeptChannels => FieldShape::U32,
// A constexpr sampler's index in its use's sampler array, and the sampled-texture array's
// element a fetched color attachment is read through.
PushField::ConstexprSampler(_) | PushField::FetchedColor { .. } => FieldShape::U32,
+2 -2
View File
@@ -1275,8 +1275,8 @@ fn select_entry(
.collect();
}
tessellation::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?;
// The framebuffer-fetch forms first: an output to a storage-form attachment is no interface
// variable.
// The framebuffer-fetch forms first: a write the function computes over its input attachment
// decides its output's interface variable.
fragment::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?;
stage_io::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?;
mesh::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?;
@@ -31,11 +31,7 @@
//! (`stage_io::returns_no_nan`) stores none, and records no note for one.
//!
//! An attachment no lane of which rounds is not listed as rounded: it keeps its Vulkan blend of
//! one and zero, through which the facts were measured too. A write in the storage form records
//! the device's conversion: the facts are of the device's conversion of an output variable. A
//! storage write the shader blends into a 16-bit float attachment stores the NaN of the device's
//! arithmetic, which the storage image's store converts, noted `PrecisionNote::DeviceNanEncoding`
//! (Metal stores every NaN of the blend as `0x7e00`). An attachment a lane of
//! one and zero, through which the facts were measured too. An attachment a lane of
//! which rounds is listed as rounded (`rounded_colors`), and takes no Vulkan blend of one and zero.
use crate::lower::arith::color_write;
@@ -51,8 +47,7 @@ use crate::spirv::error::BResult;
use crate::spirv::ids::Value;
/// Plan the write of a fragment function's output of form `f` to color attachment `color`
/// (dual-source index 0), through an output variable or in the storage form (see the module
/// docs). `nan_free`: every value the function returns there is a constant none of whose lanes is
/// (dual-source index 0), through an output variable (see the module docs). `nan_free`: every value the function returns there is a constant none of whose lanes is
/// a NaN, which stores no NaN.
pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form, nan_free: bool) {
if cx.stage != Stage::Fragment {
@@ -66,27 +61,13 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form, nan_free: bool) {
.interface
.color_writes
.insert(color, rules);
// A storage write the shader blends into a 16-bit float attachment stores the blend's result:
// a `half` output's `half` in every channel, which the device converts exactly, and a `float`
// output's `float`, which the storage image's store rounds to `half` as the device rounds it
// (`PrecisionNote::DeviceColorConversion`). No
// conversion of an output variable's bears on it, and its NaN is the device's arithmetic's,
// which the storage image's store converts (`PrecisionNote::DeviceNanEncoding`).
// One the shader blends into an 8-bit unorm attachment stores the blend's result, which the
// storage image's store converts (`fetch::unorm8_blended`, which notes it).
let shader_blended = crate::lower::fragment::blends_in_storage(cx, color);
let sixteen_blended = crate::lower::fragment::blends_sixteen_in_storage(cx, color);
let mut lanes = [None; 4];
let mut device = false;
let mut blended = false;
let mut nans = false;
for (slot, rule) in lanes.iter_mut().zip(rules).take(usize::from(f.lanes)) {
let Some(rule) = rule else { continue };
nans |= !shader_blended && !nan_free && color_writes::half_float(rule) && !nan_kept(f);
if sixteen_blended && f.float_fmt() == Some(FloatFmt::F32) {
device = true;
continue;
}
nans |= !nan_free && color_writes::half_float(rule) && !nan_kept(f);
match (rule, f.float_fmt()) {
(_, None | Some(FloatFmt::F64 | FloatFmt::BFloat)) => {}
// A `half` is a half already, whichever way the channel rounds.
@@ -103,8 +84,8 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form, nan_free: bool) {
) => {}
// The pipeline's rounding mode, which the function applies.
(rule @ ChannelWrite::FloatNearestEven { .. }, Some(_)) => *slot = Some(rule),
(ChannelWrite::BlendedNearestEven { .. }, _) => blended |= !shader_blended,
(_, Some(_)) => device |= !shader_blended,
(ChannelWrite::BlendedNearestEven { .. }, _) => blended = true,
(_, Some(_)) => device = true,
}
}
if device {
@@ -113,7 +94,6 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form, nan_free: bool) {
if blended {
cx.precision.insert(PrecisionNote::BlendedWriteRounding);
}
nans |= sixteen_blended;
if nans {
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
}
@@ -26,10 +26,10 @@
//! writes there (`InvalidDescriptor(ColorAttachment)`: Metal's pipeline validation asserts that
//! the format is not blendable). A `bfloat` output is refused before, as Metal's compiler rejects
//! it. The blend of another form, a padded one's included, is the function's own, over an ordered
//! read of the attachment (below, and `lower::fragment::fetch`'s storage form), and a dual-source
//! second output to such an attachment is that blend's second source: on a device that orders fetch
//! in neither form the blend is refused naming what it needs (`fetch::unordered_extended_fetch`:
//! `fragmentShaderPixelInterlock` or `rasterizationOrderColorAttachmentAccess`). A blend into one
//! read of the attachment (below), and a dual-source second output to such an attachment is that
//! blend's second source: on a device that does not order fetch the blend is refused naming what
//! it needs (`fetch::unordered_extended_fetch`: `rasterizationOrderColorAttachmentAccess`). A blend
//! into one
//! of Apple's extended-range forms (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their `_sRGB`
//! twins) is not implemented on any device (`Feature::Format`, `fetch::codes_round_the_tile`):
//! only a padded form's blend is built.
@@ -93,9 +93,9 @@ pub(super) fn plan(
return Err(Unsupported::not_implemented(Feature::Format).into());
}
let blended = e.blended && !cx.families.fragment.input_blends.contains_key(&color);
// A blend the function computes over an ordered read of the attachment (the storage form, or
// over the input attachment, `lower::fragment`), on a device that orders fetch in neither
// form: refused naming the two orderings.
// A blend the function computes over an ordered read of the attachment (over the input
// attachment, `lower::fragment`), on a device that does not order fetch: refused naming the
// ordering.
if blended && crate::lower::fragment::fetch::fetch_unordered(cx.profile) {
return Err(crate::lower::fragment::fetch::unordered_extended_fetch().into());
}
@@ -151,8 +151,7 @@ pub(super) fn raw_components(
/// attachment `e` (the module docs): the lanes completed to four as [`held`] completes them, a
/// `float` output rounded to `half` toward zero (saturating at 65504) or, where
/// `e.nearest_even`, to nearest even, then each lane's bfloat code nearest, ties to even, a NaN
/// `0x7fc0` (`arith::extended_range::bfloat_stored`). Integer operations on the bits alone. The
/// storage form's unblended write stores it too (`lower::fragment::fetch`).
/// `0x7fc0` (`arith::extended_range::bfloat_stored`). Integer operations on the bits alone.
pub(crate) fn bfloat_output(
fb: &mut FunctionBuilder<'_>,
e: ExtendedRangeColor,
@@ -181,8 +180,7 @@ const FOUR: Form = Form {
/// held in `form`, unblended, as a `uvec4` (`arith::extended_range::encode`): the lanes completed
/// to four (a color lane the output lacks 0, a missing alpha 1; an output with fewer lanes than
/// the format's channels is refused before), a `float` output rounded to `half` to nearest even,
/// then the kernel write's encode. The storage form's unblended write stores it too
/// (`lower::fragment::fetch`).
/// then the kernel write's encode.
pub(crate) fn texel(
fb: &mut FunctionBuilder<'_>,
form: ExtendedRange,
@@ -195,8 +193,8 @@ pub(crate) fn texel(
/// The value [`texel`] encodes for output `x` (form `f`) to an attachment held in `form`, a
/// `vec4` of `half` values: the lanes completed to four, a `float` output rounded to `half`.
/// Metal's tile holds it until the store, which the storage form's shadow of the attachment keeps
/// (`lower::fragment::fetch`). Not a bfloat form's, whose rounding is the pipeline's and whose
/// Metal's tile holds it until the store. Not a bfloat form's, whose rounding is the pipeline's and
/// whose
/// store rounds to the nearest code ([`bfloat_output`]).
pub(crate) fn held(
fb: &mut FunctionBuilder<'_>,
+5 -52
View File
@@ -406,7 +406,7 @@ pub struct StageIoPlan {
/// Whether a kernel reads the stage-in region (`RuntimeFact::StageInRegion`).
pub region: bool,
/// The lanes of each color attachment's output a fragment function rounds itself
/// (`color_write`), through an output variable or in the storage form: each by its rule, a
/// (`color_write`), through an output variable: each by its rule, a
/// half-float channel's under `TextureWriteRoundingMode::NearestEven`.
pub rounded: BTreeMap<u32, [Option<crate::pipeline::lower_inputs::ChannelWrite>; 4]>,
/// The extended-range color attachments whose `float` or `half` output each return stores
@@ -618,12 +618,7 @@ pub fn select_return(cx: &mut SelectCx<'_>, _at: InstId, v: Option<Value>) -> Re
None if void => Ok(()),
None => Err(cx.invariant("an entry with outputs returns no value")),
Some(_) if void => Err(cx.invariant("an entry without outputs returns a value")),
Some(_)
if cx.families.stage_io.outputs.is_empty()
&& !crate::lower::fragment::writes_outside_interface(cx) =>
{
Ok(())
}
Some(_) if cx.families.stage_io.outputs.is_empty() => Ok(()),
Some(v) => {
let ty = cx
.value_ty(v)
@@ -871,47 +866,6 @@ pub fn sample_id(cx: &mut SelectCx<'_>) -> usize {
)
}
/// Plan the fragment's `FrontFacing` input for a family that reads the fragment's face (the
/// shader-side stencil): the index of its object, shared with a `[[front_facing]]` input.
pub fn front_facing(cx: &mut SelectCx<'_>) -> usize {
plan::builtin(
&mut cx.families.stage_io,
crate::spv::BuiltIn::FrontFacing,
IoDir::Input,
Shape::Bool,
crate::pipeline::stage_io::StageBuiltin::FrontFacing,
)
}
/// Plan the fragment's `SampleMask` input and output for the shader-side stencil's multisampled
/// form: the indexes of their objects, the input shared with a `[[sample_mask]]` input. The form
/// reads the invocation's own coverage, which is not Metal's `[[sample_mask]]` (the pixel's
/// coverage), so the stage interface states only the output, which the module writes.
pub fn sample_masks(cx: &mut SelectCx<'_>) -> (usize, usize) {
let sp = &mut cx.families.stage_io;
let covered = plan::builtin_object(
sp,
crate::spv::BuiltIn::SampleMask,
IoDir::Input,
Shape::U32Array(1),
);
let kept = plan::builtin(
sp,
crate::spv::BuiltIn::SampleMask,
IoDir::Output,
Shape::U32Array(1),
crate::pipeline::stage_io::StageBuiltin::SampleMaskOut,
);
(covered, kept)
}
/// The form of an output of AIR type `ty` that must be a 32-bit integer scalar, as a stencil or
/// sample-mask output must, for a family that writes it outside the stage interface (the
/// shader-side stencil).
pub fn int_scalar_output(cx: &SelectCx<'_>, ty: crate::air::ir::TypeId) -> Result<Form, Error> {
plan::int_scalar_form(cx, ty)
}
/// The global [`declare`] declared for planned object `i`.
pub fn object_global(cx: &mut EmitCx<'_>, i: usize) -> BResult<GlobalId> {
global(cx, i)
@@ -2319,10 +2273,9 @@ fn rotated_second(
enum NanDrop {
/// Kill the invocation there (`FragmentPlan::return_kill`).
Kill(KillForm),
/// Inside an interlocked body, record it in the `discarded` predicate: the storage form's
/// color stores and the other writes at the return skip it, and the entry kills it after the
/// critical section, so a color stored in the shader is dropped as Vulkan's tests would drop an
/// output.
/// Inside an interlocked body, record it in the `discarded` predicate: the writes at the
/// return skip it, and the entry kills it after the critical section, as Vulkan's tests would
/// drop an output.
Record(GlobalId),
}
+12 -47
View File
@@ -273,13 +273,6 @@ fn int_scalar(f: Form) -> Result<(), Error> {
}
}
/// The [`io_form`] of AIR type `ty`, which must be [`int_scalar`].
pub(super) fn int_scalar_form(cx: &SelectCx<'_>, ty: AirTypeId) -> Result<Form, Error> {
let f = io_form(cx, ty)?;
int_scalar(f)?;
Ok(f)
}
/// A `float`-lane builtin read into or written from a float of `lanes` lanes.
fn float_lanes(f: Form, lanes: u8) -> Result<(), Error> {
match f.held {
@@ -2123,23 +2116,20 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
float_lanes(io_form(cx, ty)?, 1)?;
continue;
}
// An imageblock output is written to the pass's imageblock storage, not an interface
// variable.
if let OutputRole::ImageblockData(ib) = &o.role {
if cx.stage != Stage::Fragment {
return Err(cx.invariant("an imageblock output outside a fragment function"));
}
crate::lower::fragment::select_imageblock_output(cx, o.field, ib, o.ty.align, ty)?;
continue;
// An imageblock output is not implemented.
if let OutputRole::ImageblockData(_) = &o.role {
return Err(Unsupported::not_implemented(Feature::Imageblocks).into());
}
// A stencil output on a device without stencil export is the shader-side stencil,
// written to the stencil's shadow, not an interface variable.
// A stencil output needs stencil export.
if matches!(o.role, OutputRole::Stencil)
&& cx.stage == Stage::Fragment
&& !cx.profile.fields().fragment.stencil_export
{
crate::lower::fragment::select_stencil_output(cx, o.field, ty)?;
continue;
return Err(Unsupported::needs(
Feature::StencilExport,
Capability::Extension(VkExtension::ExtShaderStencilExport),
)
.into());
}
// An output to a color the pass lacks is stored nowhere, as plain Metal drops it: no
// output variable, so the pipeline writes no location without an attachment. So is one to a
@@ -2164,22 +2154,6 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
}
}
}
// An output to an attachment the function reads in the interlocked storage form is
// written to its storage image, not an interface variable.
if let OutputRole::RenderTarget {
attachment: AbiInt::Const(color),
index: 0,
..
} = o.role
{
if cx.stage == Stage::Fragment
&& crate::lower::fragment::writes_through_storage(cx, color)
{
crate::lower::fragment::select_storage_output(cx, o.field, color, ty)
.map_err(|e| e.at_attachment(Attachment::Color(color)))?;
continue;
}
}
// A second output of the function's own to an attachment whose blend reads the one the
// rotation needs (`LoweringInputs::rotated_factors`) is stored nowhere: Metal's blend
// there reads no second output.
@@ -2192,15 +2166,6 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
if cx.stage == Stage::Fragment && cx.inputs.rotated_factors.contains_key(&color) {
continue;
}
// The second source of an extended-range or generic blend the shader computes in the
// storage form, which the blend reads from the returned value.
if cx.stage == Stage::Fragment
&& crate::lower::fragment::blends_second_through_storage(cx, color)
{
crate::lower::fragment::select_storage_second_output(cx, o.field, color, ty)
.map_err(|e| e.at_attachment(Attachment::Color(color)))?;
continue;
}
// The second source of an extended-range blend the function computes over the
// attachment's input attachment, which the blend reads from the returned value.
if cx.stage == Stage::Fragment
@@ -2210,8 +2175,8 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
.map_err(|e| e.at_attachment(Attachment::Color(color)))?;
continue;
}
// Every other write of an extended-range attachment (the storage form's of none of its
// channels or unblended, or the raw texel's through the interface) reads no second
// Every other write of an extended-range attachment (the raw texel's through the
// interface, or over the input attachment unblended) reads no second
// output, as Metal's write there reads none: it is stored nowhere, where the
// interface's raw texel refused it `Format`.
if cx.stage == Stage::Fragment && cx.inputs.extended_range_colors.contains_key(&color) {
@@ -2902,7 +2867,7 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result<Lin
cx.families.fragment.depth_output = true;
link
}
// A device without stencil export runs the shader-side stencil (`entry`).
// A device without stencil export refuses the output (`entry`).
OutputRole::Stencil if !vertex && frag.stencil_export => {
let f = io_form(cx, ty)?;
int_scalar(f)?;
@@ -20,10 +20,6 @@
//!
//! An integer output to such an attachment is Metal's pipeline error: it is not encoded, and link
//! refuses it (`ColorAttachment`).
//!
//! The interlocked storage form writes such an attachment through the same encode where it blends
//! or keeps some channels (`lower::fragment::fetch`), and a blend there reads the word read first
//! as Metal's blend reads it ([`decode`]).
use crate::air::intrinsics::PackFormat;
use crate::error::{Error, Feature, Unsupported};
@@ -185,57 +181,3 @@ pub(crate) fn encode(
}
Ok(out)
}
/// The four channels Metal's blend reads from word `x` (a `u32`) of packed 16-bit word attachment
/// `word` (`WordAttachment::Packed16`), as a
/// `vec4` of `f32`, red first: each channel's code over its maximum code rounded to `half`, nearest
/// even, a channel the format lacks 0, alpha 1 (measured: the packed 16-bit blend sweep,
/// `extended_range::Blend::packed16`). The code times the `f32` nearest the maximum's reciprocal
/// lies within two `f32` steps of the quotient, whose `half` it rounds to: the quotient of a code
/// by `2^k - 1` repeats `k` bits without end (or is 0 or 1), which keeps it far from a `half`
/// midpoint, more than `2^-(k+1)` of a `half` step for `k` up to 6.
pub(crate) fn decode(
fb: &mut FunctionBuilder<'_>,
word: WordAttachment,
x: Value,
) -> BResult<Value> {
let s = Form {
held: Held::Float(FloatFmt::F32),
lanes: 1,
};
let u = Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes: 1,
};
let st = ty(fb, s)?;
let mut lanes = Vec::with_capacity(4);
for (lane, field) in word.fields().iter().enumerate() {
let Some(field) = field else {
lanes.push(fsplat(fb, s, if lane == 3 { 1.0 } else { 0.0 })?);
continue;
};
let max = (1u32 << field.bits) - 1;
let code = match field.shift {
0 => x,
shift => {
let shift = splat(fb, u, u64::from(shift))?;
fb.binary(BinOp::ShiftRightLogical, x, shift)?
}
};
let mask = splat(fb, u, u64::from(max))?;
let code = fb.binary(BinOp::BitwiseAnd, code, mask)?;
let c = fb.convert(ConvOp::ConvertUToF, code, st)?;
let r = fsplat(fb, s, f64::from(1.0f32 / max as f32))?;
let v = fb.binary_no_contraction(BinOp::FMul, c, r)?;
lanes.push(half_rounded(fb, s, v)?);
}
let v4 = Form {
held: Held::Float(FloatFmt::F32),
lanes: 4,
};
let t = ty(fb, v4)?;
fb.composite_construct(t, &lanes)
}
+1 -24
View File
@@ -2518,23 +2518,6 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR
} else {
texel_memory(cx, fb, &r.image)?
};
// A slot the draw reads through a snapshot (`LoweringInputs::snapshot_textures`): its
// interface fact admits only the plain fetch of a level the snapshot's copy makes, through the
// slot's image, which the copy fetches from.
let snapshot = match r.image {
ImageRef::Slot(index) => {
let plain = sampled
&& !decl.rows
&& decl.parts.is_none()
&& spec.is_none()
&& sample.is_none()
&& r.through.is_none()
&& !r.level_views
&& within.is_none();
crate::lower::fragment::snapshot_prepare(cx, fb, index, img, plain)?
}
ImageRef::Heap { .. } => None,
};
let access = move |fb: &mut FunctionBuilder<'_>, sparse: bool| -> BResult<SValue> {
match (sampled, sparse) {
(true, false) => fb.fetch(img, coord, &ops),
@@ -2592,13 +2575,7 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR
inb = Some(and(fb, inb, kept)?);
(texel, Some(word))
}
None => match snapshot {
Some(s) => (
crate::lower::fragment::snapshot_read(cx, fb, s, coord)?,
None,
),
None => (access(fb, false)?, None),
},
None => (access(fb, false)?, None),
};
// A heap member of a form a heap reads: its raw texel's value, Metal's out-of-bounds texel
// selected against its own image, which the float array's test below then leaves, and a read
+2 -1
View File
@@ -509,7 +509,8 @@ pub fn declare_threadgroup(
/// Declare a fragment function's threadgroup arena, its tile's memory (the module docs): the
/// pass's tile memory buffer, a storage view of the fragment stage, each region at its
/// `SpecKey::TgOffset`, and the size `SpecKey::TileThreadgroupLength`. A fragment has no
/// imageblock region (its imageblock is the pass's storage, `lower::fragment::imageblock`).
/// imageblock region: the product refuses a fragment function's imageblock
/// (`Feature::Imageblocks`).
fn declare_fragment(mb: &mut ModuleBuilder, shape: &TgShape, coord: usize) -> BResult<TgDecl> {
let u32_ = u32_ty(mb)?;
let slot = ResourceSlot {
+6 -69
View File
@@ -1031,10 +1031,12 @@ fn copies_only_repr(pf: PixelFormat) -> Repr {
/// Whether a render pipeline on `profile` blends into a color attachment of `pf`, one of Apple's
/// extended-range formats ([`ExtendedRange::of`]). No device blends such an attachment's raw
/// texels: the fragment function computes Metal's blend in the shader, inside the pixel
/// interlock, from the texel it reads. `Ok` where the device orders fetch through the pixel
/// interlock alone and that form is exact for an attachment of `pf` written whole under a blend
/// Metal's model holds (a padded 10-bit form's); else what blocks it. `BGR10_XR`, `BGRA10_XR`,
/// texels: the fragment function computes Metal's blend in the shader from the texel it reads
/// through the attachment's input attachment. `Ok` where the device orders fetch through
/// rasterization-order input attachments and that blend holds for an attachment of `pf` written
/// whole under a blend Metal's model holds (a padded 10-bit form's); else what blocks it (on a
/// device without rasterization-order color attachment access, `Feature::FramebufferFetch` naming
/// that feature). `BGR10_XR`, `BGRA10_XR`,
/// `RGB10A8_2P_XR10` and their `_sRGB` twins answer `NotImplemented(Format)` on every device: Metal's
/// tile holds such an attachment as `half` through the render pass, which the codes the attachment
/// holds do not keep, so its blend over an earlier draw's write is not built. A pipeline's own
@@ -2851,71 +2853,6 @@ pub(crate) fn red_blue_exchanged(pf: PixelFormat) -> bool {
)
}
/// The RGBA-order twin of a BGRA-order direct format, whose fields are the format's with red and
/// blue exchanged: `R8G8B8A8_UNORM` for `B8G8R8A8_UNORM` and `A2B10G10R10_UNORM_PACK32` for
/// `A2R10G10B10_UNORM_PACK32`, each of the format's texel size and compatibility class (the
/// kernels' `SwizzleBgra` alias views, [`storage_choice`]). SPIR-V names no image format for
/// either BGRA-order format. `None` for every other format.
pub(crate) fn rgba_twin(format: vk::Format) -> Option<vk::Format> {
match format {
vk::Format::B8G8R8A8_UNORM => Some(vk::Format::R8G8B8A8_UNORM),
vk::Format::A2R10G10B10_UNORM_PACK32 => Some(vk::Format::A2B10G10R10_UNORM_PACK32),
_ => None,
}
}
/// What a storage view in `twin`, an RGBA-order twin ([`rgba_twin`]), lacks on `profile` for a
/// function that reads and writes it: the format's storage usage, and a declaration, without a
/// format where the device grants the format that access without one, else by its SPIR-V image
/// format (`shaderStorageImageExtendedFormats` for an extended one). Empty where it lacks
/// nothing.
pub(crate) fn rgba_twin_gaps(twin: vk::Format, profile: &DeviceProfile) -> Vec<Capability> {
let use_ = StorageUse::READ_WRITE_TEXTURE;
let mut gaps = Vec::new();
if !profile.supports_format(twin, FormatUsage::StorageImage) {
gaps.push(Capability::Format {
format: twin,
usage: FormatUsage::StorageImage,
});
}
if !accessed_without_format(twin, use_, profile) {
match spirv_image_format(twin) {
Some(declared)
if crate::spirv::requirements::extended_format(declared)
&& !profile.fields().images.storage_extended_formats =>
{
gaps.push(Capability::Feature(
VkFeature::ShaderStorageImageExtendedFormats,
));
}
Some(_) => {}
None => gaps.extend(without_format_gaps(twin, use_, profile)),
}
}
gaps
}
/// The format other than `format` a fetching draw's storage view of a color attachment of
/// `format` takes in the storage form of framebuffer fetch on `profile`
/// (`StorageAttachmentUse::view_alias_of`, its public door): an 8-bit sRGB format's
/// unsigned-integer format of its texel size on every device, and a BGRA-order format's
/// RGBA-order twin ([`rgba_twin`]) where the device neither reads nor writes the format without a
/// format ([`accessed_without_format`]; SPIR-V names no image format for it, so no declaration
/// reaches it otherwise) and the twin lacks nothing ([`rgba_twin_gaps`]). `None` elsewhere: the
/// view is in `format`, and a device that accesses a BGRA-order format without one keeps that.
pub(crate) fn fetch_view_alias(format: vk::Format, profile: &DeviceProfile) -> Option<vk::Format> {
use vk::Format as F;
match format {
F::B8G8R8A8_SRGB | F::R8G8B8A8_SRGB => Some(F::R32_UINT),
F::R8G8_SRGB => Some(F::R16_UINT),
F::R8_SRGB => Some(F::R8_UINT),
_ => rgba_twin(format).filter(|&twin| {
!accessed_without_format(format, StorageUse::READ_WRITE_TEXTURE, profile)
&& rgba_twin_gaps(twin, profile).is_empty()
}),
}
}
/// The SPIR-V `Image Format` a storage image of Vulkan format `format` is declared with (Vulkan
/// spec "Compatibility Between SPIR-V Image Formats and Vulkan Formats"); `None` for formats only
/// a formatless (`Unknown`) declaration can access. Crate-private: only the lowering and the
+12 -23
View File
@@ -25,10 +25,10 @@
//! by Metal's twelve-bit table, as `pack_float_to_srgb_unorm4x8` encodes a color channel. The
//! fragment function encodes the channel by the MSL transfer through the device's `Pow`, as its
//! `pack_float_to_srgb_unorm4x8` does (`lower::arith::pack`, `PrecisionNote::DevicePackConversion`). A write
//! of some of its channels merges the word into the texel's: in the pixel interlock
//! (`color_writes::stored_word`), or over the attachment's input attachment on a device that orders
//! fetch through rasterization-order input attachments (`color_writes::merged_word`). A blend of
//! such an attachment, other than one and zero, is not built.
//! of some of its channels merges the word into the texel's over the attachment's input attachment
//! on a device that orders fetch through rasterization-order input attachments
//! (`color_writes::merged_word`), and is refused as the device lacking the format elsewhere. A
//! blend of such an attachment, other than one and zero, is not built.
//!
//! Metal's store of a `float` output into `RGB9E5Float` (measured on the M3 Max: 65,536 draws and
//! clears, and the format scout's draws): each of red, green and blue clamped to `[0, 65408]` (a
@@ -38,25 +38,14 @@
//! folds the conversion into the store): that store is not built.
//!
//! A blend of factors one and zero, added, stores the same (Metal's draws through it matched too).
//! A write mask of some of the format's channels keeps the other fields: where the device orders
//! fetch through the pixel interlock, the fragment function stores the word in the interlocked
//! storage form, merging the kept fields of the word it reads first (`lower::fragment::fetch`),
//! which hold their codes as Metal's tile holds them. The device blends no such view otherwise,
//! resolves none, and reads none as the format's input attachment: a pipeline that blends a word
//! attachment, covers by its alpha, or writes some of its channels on a device without that
//! interlock is refused as the device lacking the format's attachment, as without the view.
//!
//! A fragment function's color input of a packed 16-bit word attachment reads the word and
//! decodes it, in the interlocked storage form (`lower::fragment::fetch`): each channel's code
//! over its maximum code rounded to `half`, nearest even, which is the value Metal's programmable
//! blending hands the function (measured on an Apple M3 Max under macOS 27.0.1: a `float4` and a
//! `half4` color input of `BGRA4Unorm`, `ABGR4Unorm` and `B5G6R5Unorm`, every code of each 4-bit
//! channel and a sweep of the 5- and 6-bit ones, stored raw into an `RGBA32Float` attachment; an
//! `RGBA8Unorm` control reads the `f32` quotient through a `float4` input, so the two rules are
//! told apart). Metal's tile holds a pass's clear and an earlier draw's write finer than the
//! codes, as it holds them for a blend (`PrecisionNote::DeviceColorConversion`), so a read after
//! one in the same pass reads the code the attachment holds. A color input of an 8-bit sRGB word
//! and of an `RGB9E5Float` one is `NotImplemented(Format)`.
//! A write mask of some of the format's channels keeps the other fields: on a device that orders
//! fetch through rasterization-order input attachments, the fragment function merges an 8-bit
//! sRGB word into the word its input attachment holds (`lower::fragment`'s `word_input`). The
//! device blends no such view, resolves none, and reads none as the format's input attachment: a
//! pipeline that blends a word attachment, covers by its alpha, or writes some of a packed 16-bit
//! or `RGB9E5Float` word's channels is refused as the device lacking the format's attachment, as
//! without the view. A fragment function's color input of a word attachment is
//! `NotImplemented(Format)`.
//!
//! A multisampled texture of such a format is held in the word's format where the device renders
//! that at the texture's count (the runtime's image plan), so every sample holds Metal's word.
@@ -45,8 +45,6 @@ fn stage_module_bytes_are_little_endian_words() {
constant_blob: None,
rounded_colors: Vec::new(),
own_pixel_textures: Vec::new(),
snapshot_textures: Vec::new(),
snapshot_refusals: Vec::new(),
level_reads: Vec::new(),
private_bytes: 0,
specialized_notes: Vec::new(),
@@ -97,8 +95,6 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() {
constant_blob: None,
rounded_colors: Vec::new(),
own_pixel_textures: Vec::new(),
snapshot_textures: Vec::new(),
snapshot_refusals: Vec::new(),
level_reads: Vec::new(),
private_bytes: 0,
specialized_notes: vec![
@@ -247,8 +243,6 @@ mod serde_round_trips {
line_band: Some(crate::pipeline::BandPrimitive::Triangles),
swizzled_storage: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 6)]),
addressed_function_tables: true,
interlocked_colors: BTreeSet::from([1]),
read_only_tests: true,
address_maps: BTreeMap::from([(
slot(Stage::Kernel, SlotClass::Texture, 7),
metal::sampler::AddressModeMap::IDENTITY.with(
@@ -260,10 +254,6 @@ mod serde_round_trips {
primitive_id_indices: Some(metal::IndexType::UInt16),
quad_primitive_ids: true,
private_list: true,
snapshot_textures: BTreeMap::from([(
slot(Stage::Fragment, SlotClass::Texture, 2),
crate::pipeline::SnapshotForm::Unorm8,
)]),
cross_class: BTreeMap::from([(
slot(Stage::Kernel, SlotClass::Texture, 8),
SampledType::Uint,
@@ -346,15 +336,8 @@ mod serde_round_trips {
),
(2, None),
]),
depth_or_stencil: true,
alpha_to_coverage: false,
amplified: true,
}),
srgb_textures: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 7)]),
snapshot_textures: BTreeMap::from([(
slot(Stage::Fragment, SlotClass::Texture, 3),
crate::pipeline::SnapshotForm::Half,
)]),
ycbcr_in_place: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 9)]),
ycbcr_planes_sampled: BTreeMap::from([(
slot(Stage::Fragment, SlotClass::Texture, 9),
@@ -442,7 +425,6 @@ mod serde_round_trips {
alpha_test: Some(metal::CompareFunction::GreaterEqual),
logic_operation: Some(crate::vk::LogicOp::XOR),
depth_compare_clamp_mask: 0x8000_0005,
read_only_tests: true,
rotated_colors: BTreeSet::from([4]),
alpha_in_red_colors: BTreeSet::from([4]),
rotated_factors: BTreeMap::from([(
@@ -591,29 +573,8 @@ mod serde_round_trips {
push_offset: 20,
control_point_index_type: metal::TessellationControlPointIndexType::UInt16,
}),
fragment_imageblock: Some(FragmentImageblock {
mechanism: ImageblockMechanism::StorageImageInterlock,
words: 3,
master: [9; 32],
data_size: 12,
alignment: 4,
}),
vertex_writes_memory: true,
writes_viewport_index: true,
storage_attachments: vec![StorageAttachmentUse {
color_index: 1,
format: vk::Format::R16G16B16A16_SFLOAT,
writes: true,
formatless: false,
view: StorageAttachmentView::SamplePlanes { layers: 4 },
view_alias: Some(vk::Format::R32_UINT),
kept: vk::ColorComponentFlags::G | vk::ColorComponentFlags::A,
}],
shadow_stencil: Some(ShadowStencilUse {
format: vk::Format::R8_UINT,
formatless: true,
samples: 4,
}),
writes_point_size: true,
writes_depth: true,
reads_barycentric_coord: true,
@@ -621,7 +582,6 @@ mod serde_round_trips {
fragment_writes_memory: true,
color_outputs: 0b101,
sample_mask: Some(0b1001),
snapshot_reads: true,
logic_op: Some(vk::LogicOp::EQUIVALENT),
line_band: Some(crate::pipeline::LineBandState {
push_offset: 112,
@@ -970,9 +930,6 @@ mod bind_serde_round_trips {
[8.0, -8.0, 1.75, -1.0],
)),
resident_ranges: vec![crate::bind::ResidentRange::new(0x9_0000, 0x3_0000, 100)],
interlocked_colors: BTreeSet::from([0, 3]),
fragment_tests: crate::bind::FragmentTests::Depth { writes: true },
snapshot_textures: BTreeSet::from([2]),
blend_color: [0.25, -0.5, 1.5, 0.75],
alpha_test_reference: Some(0.375),
primitive_type: Some(metal::PrimitiveType::TriangleStrip),
@@ -1034,9 +991,6 @@ mod bind_serde_round_trips {
depth_clamp_range: true,
rotated_weights: true,
line_band: Some(crate::pipeline::BandPrimitive::Lines),
interlocked_colors: BTreeSet::from([0, 3]),
fragment_tests: crate::bind::FragmentTests::Pass,
snapshot_textures: BTreeSet::from([2]),
primitive_id_indices: Some(metal::IndexType::UInt32),
quad_primitive_ids: true,
private_list: true,
@@ -1204,7 +1158,6 @@ mod bind_serde_round_trips {
control_point_index: None,
});
round_trip(&WriteSource::TessellationFactors);
round_trip(&WriteSource::ShadowStencil);
round_trip(&UseTarget::TessellationFactors);
round_trip(&WriteSource::PatchIndices { min_bytes: 16 });
round_trip(&WriteSource::TileMemory { bytes: 480 });
+20 -83
View File
@@ -11,7 +11,7 @@ use crate::cache::{Hash256, PipelineKey, SpecializationKey};
use crate::device::requirements::Requirements;
use crate::pipeline::facts::{Mechanism, RuntimeFact};
use crate::pipeline::graphics::GraphicsState;
use crate::pipeline::interface::{LevelReads, PipelineInterface, SampledLevels, SnapshotRefusal};
use crate::pipeline::interface::{LevelReads, PipelineInterface, SampledLevels};
use crate::pipeline::layout::PipelineLayout;
use crate::pipeline::sym::SpecKey;
use crate::pipeline::vertex::VertexInputState;
@@ -95,12 +95,7 @@ fn stage_footprint(stage: &StageModule) -> u64 {
+ vector_bytes::<PrecisionNote>(stage.precision_notes.capacity())
+ vector_bytes::<SpecializedNote>(stage.specialized_notes.capacity())
+ clauses
+ vector_bytes::<u32>(
stage.rounded_colors.capacity()
+ stage.own_pixel_textures.capacity()
+ stage.snapshot_textures.capacity(),
)
+ vector_bytes::<(u32, SnapshotRefusal)>(stage.snapshot_refusals.capacity())
+ vector_bytes::<u32>(stage.rounded_colors.capacity() + stage.own_pixel_textures.capacity())
+ vector_bytes::<LevelReads>(stage.level_reads.capacity())
+ (stage.level_reads.iter())
.map(|reads| vector_bytes::<SampledLevels>(reads.sampled.capacity()))
@@ -189,14 +184,6 @@ pub struct StageModule {
/// rectangle bounding its scissors, a pixel wider each way for its helper invocations, on a
/// framebuffer below `2^24` pixels a side. Empty for every other stage.
pub own_pixel_textures: Vec<u32>,
/// The texture slots of `own_pixel_textures` a draw can read through a snapshot an earlier
/// draw of the same primitives took (`StageInterface::snapshot_textures`), sorted. Empty for
/// every other stage.
pub snapshot_textures: Vec<u32>,
/// Why each slot of `own_pixel_textures` that `snapshot_textures` leaves out is left out
/// (`StageInterface::snapshot_refusals`): every [`SnapshotRefusal`] that holds for it, sorted
/// by slot and then by refusal. Empty for every other stage.
pub snapshot_refusals: Vec<(u32, SnapshotRefusal)>,
/// The levels of its bound view each texture slot's reads reach, one entry a slot, sorted by
/// slot (`StageInterface::level_reads`). Empty for a kernel and a stage the link makes.
pub level_reads: Vec<LevelReads>,
@@ -807,10 +794,7 @@ pub enum PrecisionNote {
/// (`pipeline::link::vertex`): Metal widens its NaN to `0x7fc00000`, and the device's
/// widening need not. A pulled attribute's decode records it in the module (a vertex
/// function's, a kernel's `[[stage_in]]` attribute's, a post-tessellation function's). Also
/// recorded by a
/// 16-bit float attachment's blend the function computes in the storage form: a NaN of the
/// blend is the device's arithmetic's, which the storage image's store converts, where Metal
/// stores every NaN of the blend as `0x7e00`. Also recorded by a `float` read of a heap's texture buffer on a device without
/// recorded by a `float` read of a heap's texture buffer on a device without
/// Metal's sampler: Metal hands back a half-float texel's NaN as `0x7fc00000`, and the handle
/// carries no class to convert it by. The runtime announces it too for a GPU blit through an
/// `RG11B10Float` texture Metal keeps losslessly compressed: Metal's compression makes a NaN
@@ -1021,9 +1005,7 @@ pub enum PrecisionNote {
/// Metal's integer store rounds such a channel to nearest even, the device's store as it rounds
/// a `float` write (toward zero on every measured driver: within one unit in the last place of
/// the channel's value, a finite value past 65504 stored as 65504 where Metal's `half` is the
/// infinity). So does a fragment function's `float` output blended in the shader into a 16-bit
/// float attachment it renders through a storage image (the pixel interlock's fetch), whose
/// `half` the store rounds.
/// infinity).
///
/// Also: a blend into a packed 16-bit unorm attachment (`B5G6R5Unorm`, `A1BGR5Unorm`,
/// `ABGR4Unorm`, `BGR5A1Unorm`) reads what the device's attachment holds, its channels' codes,
@@ -1038,10 +1020,10 @@ pub enum PrecisionNote {
/// than Metal (3,527 of 94,732,288 channels measured a code apart, none further). `RGBA8Unorm`
/// and `RGB10A2Unorm` hold their codes there, as the device does.
///
/// Also: a blend the function computes in the storage form into an 8-bit unorm attachment
/// (`R8Unorm`, `RG8Unorm`, `RGBA8Unorm`, `BGRA8Unorm`), whose result the storage image's store
/// converts to its code, where Metal rounds the exact product with 255 (a NaN 0); the store may
/// take the other code near a tie.
/// Also: a blend the function computes over the input attachment of an attachment held with
/// its channels rotated (`ARGB8Unorm`), whose result the device's color write converts to its
/// code, where Metal rounds the exact product with 255 (a NaN 0); the write may take the other
/// code near a tie.
///
/// Also: a render pipeline's private logic operation the fragment function computes on a
/// device without Vulkan's `logicOp` (`LoweringInputs::logic_operation`), into an 8- or 16-bit
@@ -1135,8 +1117,8 @@ pub enum PrecisionNote {
/// even, and the device's blend converts it by its own rounding (MoltenVK's toward zero), so
/// a blended value off the half grid may store the neighbouring half; under a constant factor
/// Metal's result is neither rule's on 2,376 of 580,508 `RGBA16Float` channels near the half
/// denormals. The exact path, the blend in the function under the pixel
/// interlock, is not built.
/// denormals. The exact path, the blend in the function over an ordered input attachment, is
/// not built.
///
/// Validation derives no tolerance and no explanation from it: a difference stays a
/// mismatch for review, deferred in C3 until an exact path exists.
@@ -1219,8 +1201,8 @@ pub enum PrecisionNote {
/// of a module without fast math keeps a zero factor's product, the destination's by zero
/// there: a NaN of an infinite or NaN texel, and `+0` of a `-0` output over a texel of `+0` or
/// above (plain Metal on the M3 Max under macOS 27.0.1, `half4` and `float4`
/// outputs). Where the function does not compute that blend in the storage form, the pipeline
/// blends the output by the device's blend, whose answer for those texels is the device's own,
/// outputs). The pipeline blends the output by the device's blend, whose answer for those
/// texels is the device's own,
/// where a `float` output would otherwise store as written.
///
/// Validation derives no tolerance and no explanation from it: a difference stays a
@@ -1358,9 +1340,8 @@ pub enum PrecisionNote {
/// A fragment function of a module compiled with fast math (`air.compile.fast_math_enable`)
/// returns a `half` color output to an attachment the pipeline has that stores some channel
/// (its write mask names one of its format's channels; `StageIo::half_fast_colors`, which the
/// pipeline's stage reads, or the interlocked storage form's write), where
/// [`PrecisionNote::HalfOutputPrecision`]'s conditions hold; or computes the blend of a 16-bit
/// float attachment it fetches where Metal's compiler may regroup it (below). Metal's compiler
/// pipeline's stage reads), where [`PrecisionNote::HalfOutputPrecision`]'s conditions hold.
/// Metal's compiler
/// folds the attachment's blend and conversion into the function and, under fast math, fuses
/// and regroups them per pipeline: it reads the output's `float` or its `half`, rounds each
/// factor and product to `half` or keeps it, and takes a lerp or a common factor, by the
@@ -1382,22 +1363,6 @@ pub enum PrecisionNote {
/// the sweep; the device's `float` blend modelled on the same draws, three units). A consumer
/// may relay it as a known difference. The output reaches every device widened to `float`.
///
/// A fragment function that fetches a blended `R16Float`, `RG16Float` or `RGBA16Float`
/// attachment in the interlocked storage form computes the blend itself, no Vulkan blend
/// applying to a storage write (`lower::fragment::fetch`): in the arithmetic of its `half` or
/// `float` output of one to four lanes, as Metal's compiler appends it (plain Metal on the M3
/// Max under macOS 27.0.1: every channel of 677 and 1,350 blend states into each format, half
/// and float outputs, safe and fast math). Under fast math it records this note where the blend
/// is not Metal's exactly: where Metal's compiler may fold the output's own arithmetic into the
/// blend (a lane computed by a fast-math operation, a constant, or the fetched color: a
/// returned product fused into the blend's one minus the source alpha), or the blend's fast
/// form is a sum, a lerp, a common factor or a product rounded beside a fused one (but a blend
/// constant's difference), which the sweeps fit in most states but not all. It then stores
/// within 2 units in the last place of a `half` of Metal's at the operands' magnitude, 16 at
/// the stored value's under cancellation (below one at the function's own largest term). Where
/// every lane of the output is opaque to the blend and its form fits every state, the blend is
/// Metal's and the function records nothing.
///
/// The pipeline's stage also records it for an attachment of `StageIo::half_fast_colors` that
/// stores some channel **without** blending (`color_writes::stores_output`, which is the test
/// it makes), and that is deliberate rather than the blend's name read loosely: under fast math
@@ -1405,8 +1370,8 @@ pub enum PrecisionNote {
/// conversion round once, where this rounds the output to `half` first, so a channel whose format
/// converts the `float` and its `half` to different codes may store a value apart from Metal's.
/// It is the cause [`PrecisionNote::HalfOutputPrecision`] records for a module naming no math
/// mode, under a name that reads as a blend's alone. Measured in the interlocked storage form,
/// whose write stores the output's `half`: into `BGRA8Unorm`, one code apart from Metal's in
/// mode, under a name that reads as a blend's alone. Measured through a write that stores the
/// output's `half`: into `BGRA8Unorm`, one code apart from Metal's in
/// 2.2 to 2.5% of pixels for an output computed through one division or one `fwidth`, and in
/// 2.1 to 4.5% for a coverage computed through both, where the same arithmetic with a `float`
/// output stores Metal's codes (MoltenVK 1.4.2 on an Apple M3 Max, macOS 27.0.1). The 12
@@ -1768,9 +1733,8 @@ pub enum PrecisionNote {
/// the device's. The same conversions serve, noted alike: an implicit imageblock access of a
/// normalized attachment (a `half` one's load rounding the unpacked `float` once more, where
/// Metal rounds `c / D` once), a fragment function's read and write of an 8-bit sRGB attachment
/// in the interlocked storage form or through its word view, and a snapshot read's decode of a
/// normalized code (`c` times the `f32` nearest `1 / D`, where Metal reads `c / D` correctly
/// rounded). So does every conversion of an extended-range, padded 10-bit or bfloat texel
/// through its word view. So does every conversion of an extended-range, padded 10-bit or
/// bfloat texel
/// (`lower::arith::extended_range`; `ArithPlan::converts` records it), on every device, no
/// Vulkan format holding them: a read `float(c - 384)` (a padded code's `float(c)`) times the
/// `f32` nearest `1 / 510` (`1 / 1023`), a write `RoundEven` of the clamped value's `f32`
@@ -1870,33 +1834,6 @@ pub enum PrecisionNote {
/// Validation derives no tolerance and no explanation from it: a difference stays a
/// mismatch for review.
DeviceAlphaCoverage,
/// A fragment function reads a color attachment the pipeline blends, in the interlocked
/// storage form (`lower::fragment::fetch`, on a device that orders framebuffer fetch only
/// through the pixel interlock), of a format whose blend arithmetic of Metal's the translation
/// does not build: a format held directly whose channels read as floats, but a 16-bit float
/// one, an sRGB one and an extended-range one (a 32-bit float, 16-bit normalized, 8-bit signed
/// normalized, 10-bit, packed float or `A8Unorm` format, among others), an 8-bit unorm one
/// written by an output of fewer than four lanes, and a 16-bit float or 8-bit unorm one under a
/// blend of the second source or beside a second (index 1) output. No Vulkan blend applies to
/// a storage write, so the shader computes the pipeline's blend itself: in `float`, each
/// factor, product and sum
/// rounded to nearest even, a factor of zero keeping its product, the source and the blend
/// color clamped first to a normalized format's range (`[0, 1]`, `[-1, 1]`; a NaN to its low
/// end) as Vulkan's blend clamps them, an output's missing lane zero, the result stored through
/// the device's conversion. Metal's blend arithmetic for these formats is not measured, so the
/// recorded bound is not known; a blend in `float` of a 32-bit float format agrees with one
/// that fuses a product within that product's rounding, and one of a format of fewer bits than
/// a `float` within the format's own rounding of the result where Metal's arithmetic is at
/// least as fine. A factor of the second source reads the function's second output, clamped as
/// the source. An 8-bit sRGB attachment (`R8Unorm_sRGB`, `RG8Unorm_sRGB`, `RGBA8Unorm_sRGB`,
/// `BGRA8Unorm_sRGB`) under a blend of the second source, a one- or two-channel one under a
/// lerp, each in a module compiled with fast math, and one written by an output of fewer than
/// four lanes, record it too: there the shader computes Metal's 8-bit unorm blend's rounded
/// forms over the decoded texel, in the output's type (a missing lane zero), and stores the
/// result by Metal's sRGB encode (`extended_range::Blend::srgb8`), which is Metal's without
/// fast math at four lanes; under fast math Metal regroups the blend, unmeasured.
/// Validation derives no tolerance from it.
UnmeasuredFetchBlend,
/// A fragment function reads an `interpolant` through `interpolate_at_offset(offset)`, which
/// Metal evaluates at the offset as given from the pixel's upper-left corner, at any distance
/// and on no grid (the Apple M3 Max, macOS 27.0.1: an offset of 0.999 read at 0.999, one of
@@ -1931,8 +1868,8 @@ pub enum PrecisionNote {
/// Validation derives no tolerance and no explanation from it: a difference stays a
/// mismatch for review.
ExtrapolatedInterpolation,
/// A fragment function reads a color attachment (framebuffer fetch) on a device with neither
/// rasterization-order color attachment access nor `fragmentShaderPixelInterlock`. It reads
/// A fragment function reads a color attachment (framebuffer fetch) on a device without
/// rasterization-order color attachment access. It reads
/// the attachment as an input attachment, and the consumer records a barrier of the subpass's
/// dependency on itself, by region, from the color writes of the draws before to the input
/// attachment reads of a draw that fetches (and from those reads to the color writes of the
@@ -55,7 +55,6 @@ use crate::metal::format::{color_output_components, write_conversion, WriteConve
use crate::metal::TextureWriteRoundingMode;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::descriptor::ColorAttachmentDescriptor;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::graphics::ColorAttachmentState;
use crate::pipeline::lower_inputs::{ChannelWrite, ExtendedRangeColor, FactorLane};
use crate::pipeline::rotated_blend::{inexact, rotated_blend, RotatedBlend};
@@ -330,12 +329,10 @@ pub(crate) fn extended_range_colors(
/// one raw component (`BGR10_XR`, the two-plane forms' color word, and their `_sRGB` twins), is
/// written unblended under a mask of some of those codes ([`merges_extended`]): no mask of the
/// raw components keeps one code of a word and writes another, so the fragment function merges its
/// codes into the word it reads first: in the interlocked storage form (`lower::fragment::fetch`)
/// where the device orders fetch through the pixel interlock alone, over the attachment's input
/// attachment (`lower::fragment`'s `input_blend`, `RuntimeFact::WordInputMerge`) where it orders
/// it through rasterization-order input attachments. On a device that orders fetch in neither
/// form, link names the orderings the merge needs
/// (`lower::fragment::fetch::unordered_extended_fetch`).
/// codes into the word it reads first, over the attachment's input attachment
/// (`lower::fragment`'s `input_blend`, `RuntimeFact::WordInputMerge`) where the device orders
/// fetch through rasterization-order input attachments. On a device that does not order fetch so,
/// link names the ordering the merge needs (`lower::fragment::fetch::unordered_extended_fetch`).
pub(crate) fn merged_extended(c: &ColorAttachmentDescriptor) -> bool {
merges_extended(c.pixel_format, c.write_mask, c.blending_enabled)
}
@@ -361,9 +358,8 @@ pub(crate) fn merges_extended(
/// Metal stores alike), under a write mask of all of the format's channels or none, or of some of
/// them where the function merges the word into the texel over its input attachment
/// ([`merged_word`]), and it is not attachment 0 under alpha-to-coverage (whose coverage reads the
/// output's alpha as computed). `None` for every other attachment: one the function stores in the
/// interlocked storage form ([`stored_word`]), or one that takes its format's own attachment, as
/// the device has it or not.
/// output's alpha as computed). `None` for every other attachment: one that takes its format's own
/// attachment, as the device has it or not.
pub(crate) fn word_color(
index: u32,
c: &ColorAttachmentDescriptor,
@@ -422,54 +418,6 @@ pub(crate) fn merged_word(
merges_over_input(c, word, p).then(|| word_channels(word).difference(c.write_mask))
}
/// The word view of color attachment `c` of a render pipeline on profile `p` whose writes the
/// fragment function stores in the interlocked storage form (`lower::fragment::fetch`), reading
/// the word first inside the interlock: a packed 16-bit word attachment
/// (`metal::format::WordAttachment::of`) written under a blend other than one and zero, added,
/// whose factors read no second source (Metal's packed 16-bit blend, which the function computes
/// over the word, `extended_range::Blend::packed16`), or a word attachment other than
/// `RGB9E5Float`'s written unblended under a write mask of some of the format's channels (the
/// function merges the fields of the channels the mask keeps), on a device that orders fetch
/// through the pixel interlock alone.
/// `None` for every other attachment, and for a write mask of none of the format's channels.
pub(crate) fn stored_word(
c: &ColorAttachmentDescriptor,
p: &DeviceProfile,
) -> Option<metal::format::WordAttachment> {
use metal::{BlendFactor as F, ColorWriteMask as M};
let word = metal::format::WordAttachment::of(c.pixel_format, p)?;
let channels = [M::RED, M::GREEN, M::BLUE, M::ALPHA]
.into_iter()
.zip(word.fields())
.filter(|(_, f)| f.is_some())
.fold(M::NONE, |m, (bit, _)| m | bit);
let kept = c.write_mask & channels;
let partial = !kept.is_empty() && kept != channels;
let unblended = !c.blending_enabled || replaces(c);
let second = [
c.source_rgb_blend_factor,
c.destination_rgb_blend_factor,
c.source_alpha_blend_factor,
c.destination_alpha_blend_factor,
]
.iter()
.any(|f| {
matches!(
f,
F::Source1Color | F::OneMinusSource1Color | F::Source1Alpha | F::OneMinusSource1Alpha
)
});
// Metal's blend of a packed 16-bit word is built; an 8-bit sRGB word's is not, nor is an
// `RGB9E5Float` word's blend or partial mask (its mantissas share the exponent).
let packed = matches!(word, metal::format::WordAttachment::Packed16 { .. });
let fielded = word != metal::format::WordAttachment::Rgb9e5;
let stored = match unblended {
true => partial && fielded,
false => packed && !kept.is_empty() && !second,
};
(stored && crate::lower::fragment::interlock_orders(p)).then_some(word)
}
/// The word attachments of a render pipeline whose color attachments are `colors` (covering by
/// alpha where `alpha_to_coverage`) on `p`, by color index ([`word_color`]).
pub(crate) fn word_colors(
@@ -576,9 +524,8 @@ pub(crate) fn alpha_in_red_colors(
/// The attachments holding Metal's alpha in red that the fragment stage `fragment` writes or reads
/// in a render pipeline whose color attachments are `colors` on `p`: [`alpha_in_red_colors`]'s,
/// for the attachments it writes through output variables of either dual-source index, reads
/// through an input attachment, or reads in the interlocked storage form
/// (`RuntimeFact::InterlockedFramebufferFetch`), the set it must have compiled under
/// for the attachments it writes through output variables of either dual-source index or reads
/// through an input attachment, the set it must have compiled under
/// (`StageIo::alpha_in_red_colors`).
pub(crate) fn wanted_alpha_in_red(
fragment: &FunctionArtifact,
@@ -602,11 +549,7 @@ pub(crate) fn wanted_alpha_in_red(
crate::pipeline::sym::ResourceKind::InputAttachment(color) => Some(color),
_ => None,
});
let interlocked = fragment.facts.iter().filter_map(|f| match *f {
RuntimeFact::InterlockedFramebufferFetch { color, .. } => Some(color),
_ => None,
});
let used: BTreeSet<u32> = written.chain(inputs).chain(interlocked).collect();
let used: BTreeSet<u32> = written.chain(inputs).collect();
let mut out = alpha_in_red_colors(colors, p);
out.retain(|a| used.contains(a));
out
@@ -621,11 +564,10 @@ pub(crate) fn wanted_alpha_in_red(
/// device that orders framebuffer fetch (`lower::fragment::fetch`). Metal blends the format as
/// `RGBA8Unorm` with its channels rotated, so the function computes Metal's 8-bit unorm blend
/// (`extended_range::Blend::unorm8`, which takes every factor and operation but the second
/// source's) over the texel rotated into Metal's order: in the interlocked storage form where the
/// device orders fetch through the pixel interlock (`lower::fragment::fetch`), over the
/// attachment's input attachment where it orders it through rasterization-order input attachments
/// (`lower::fragment`'s `input_blend`). A device that orders fetch in neither form refuses the
/// pipeline (`fetch::unordered_extended_fetch`, at link).
/// source's) over the texel rotated into Metal's order, over the attachment's input attachment
/// where the device orders fetch through rasterization-order input attachments
/// (`lower::fragment`'s `input_blend`). A device that does not order fetch so refuses the pipeline
/// (`fetch::unordered_extended_fetch`, at link).
pub(crate) fn shader_rotated_blend(c: &ColorAttachmentDescriptor, p: &DeviceProfile) -> bool {
rotated_blend_in_shader(c, p) && !crate::lower::fragment::fetch::fetch_unordered(p)
}
@@ -794,7 +736,7 @@ pub(crate) fn wanted_extended_range(
/// The color writes the fragment stage `fragment` compiles under in a render pipeline whose
/// color attachments are `colors` (alpha-to-coverage on where `alpha_to_coverage`, rounding by
/// `rounding`) on `p`: the pipeline's, for the attachments it writes through output variables of
/// dual-source index 0 or in the storage form ([`written`]).
/// dual-source index 0 ([`written`]).
pub(crate) fn wanted(
fragment: &FunctionArtifact,
colors: &[Option<ColorAttachmentDescriptor>],
@@ -805,7 +747,7 @@ pub(crate) fn wanted(
}
/// The color attachments the fragment stage `fragment` writes through output variables of
/// dual-source index 0 or in the storage form.
/// dual-source index 0.
fn written(fragment: &FunctionArtifact) -> impl Iterator<Item = u32> + '_ {
let outputs = fragment
.interface
@@ -819,15 +761,7 @@ fn written(fragment: &FunctionArtifact) -> impl Iterator<Item = u32> + '_ {
} => Some(attachment),
_ => None,
});
let storage = fragment.facts.iter().filter_map(|f| match *f {
RuntimeFact::InterlockedFramebufferFetch {
color,
writes: true,
..
} => Some(color),
_ => None,
});
outputs.chain(storage)
outputs
}
/// Whether the color writes the fragment stage `fragment` compiled under
@@ -913,8 +847,7 @@ pub(crate) fn stores_output(c: &ColorAttachmentState) -> bool {
/// fast math (`StageIo::half_blend_colors`, `StageIo::float_blend_colors`), whose blend there
/// Metal computes keeping the destination's product by zero (a NaN of an infinite or NaN texel,
/// `+0` of a `-0` output over a texel of `+0` or above), which no write of the
/// output alone stores. The pipeline blends it and announces `PrecisionNote::HalfOutputPrecision`;
/// the storage form computes Metal's (`lower::fragment::fetch`).
/// output alone stores. The pipeline blends it and announces `PrecisionNote::HalfOutputPrecision`.
pub(crate) fn keeps_zero(
io: &crate::pipeline::stage_io::StageIo,
color: u32,
+34 -122
View File
@@ -103,9 +103,10 @@ pub enum InputsFrom<'a> {
/// inputs, the attachments among the pipeline's color attachments that the specialized entry
/// writes and whose pixel format is a signed integer
/// (`LoweringInputs::signed_color_attachments`), whether the pipeline rasterizes more than one
/// sample (`LoweringInputs::multisampled`), on a device that orders framebuffer fetch only
/// through the pixel interlock the state of the attachments the entry reads
/// (`LoweringInputs::framebuffer_fetch`), and, for each index the pipeline's vertex function
/// sample (`LoweringInputs::multisampled`), on a device that orders framebuffer fetch through
/// rasterization-order input attachments the state of the attachments whose writes the entry
/// computes over them (`LoweringInputs::framebuffer_fetch`), and, for each index the pipeline's
/// vertex function
/// writes (the [`RawIndices`]), whether the entry reads it
/// (`LoweringInputs::viewport_index_varying`;
/// `LoweringInputs::render_target_array_index_varying`). The pipeline's
@@ -134,17 +135,14 @@ pub enum InputsFrom<'a> {
pub(crate) static NO_PRIMITIVE_VARYINGS: BTreeSet<VaryingKey> = BTreeSet::new();
/// The pipeline state a fragment stage compiles under ([`InputsFrom::Fragment`]): its render
/// pipeline's, or its mesh render pipeline's, which has no vertex amplification and no call stack
/// depth of its own (Metal's default, 1).
/// pipeline's, or its mesh render pipeline's, which has no call stack depth of its own (Metal's
/// default, 1).
#[derive(Clone, Copy, Debug)]
pub struct FragmentPass<'a> {
pub(crate) color_attachments: &'a [Option<ColorAttachmentDescriptor>; 8],
/// The pipeline has a depth or a stencil attachment.
pub(crate) depth_or_stencil: bool,
pub(crate) raster_sample_count: u32,
pub(crate) rasterization_enabled: bool,
pub(crate) alpha_to_coverage: bool,
pub(crate) max_vertex_amplification_count: u32,
pub(crate) max_call_stack_depth: u32,
/// The pipeline's `textureWriteRoundingMode`.
pub(crate) texture_write_rounding_mode: crate::metal::TextureWriteRoundingMode,
@@ -171,11 +169,9 @@ impl<'a> From<&'a RenderPipelineDescriptor> for FragmentPass<'a> {
fn from(d: &'a RenderPipelineDescriptor) -> FragmentPass<'a> {
FragmentPass {
color_attachments: &d.color_attachments,
depth_or_stencil: d.depth_format.is_some() || d.stencil_format.is_some(),
raster_sample_count: d.raster_sample_count,
rasterization_enabled: d.rasterization_enabled,
alpha_to_coverage: d.alpha_to_coverage,
max_vertex_amplification_count: d.max_vertex_amplification_count,
max_call_stack_depth: d.max_fragment_call_stack_depth,
texture_write_rounding_mode: d.texture_write_rounding_mode,
sample_mask: None,
@@ -194,11 +190,9 @@ impl<'a> From<&'a MeshPipelineDescriptor> for FragmentPass<'a> {
fn from(d: &'a MeshPipelineDescriptor) -> FragmentPass<'a> {
FragmentPass {
color_attachments: &d.color_attachments,
depth_or_stencil: d.depth_format.is_some() || d.stencil_format.is_some(),
raster_sample_count: d.raster_sample_count,
rasterization_enabled: d.rasterization_enabled,
alpha_to_coverage: d.alpha_to_coverage,
max_vertex_amplification_count: 1,
max_call_stack_depth: 1,
texture_write_rounding_mode: d.texture_write_rounding_mode,
sample_mask: None,
@@ -2497,34 +2491,26 @@ pub(crate) fn unattached_colors_written(
}
/// The framebuffer-fetch state of pass `d` for the specialized fragment entry `spec` on `p`
/// (`LoweringInputs::framebuffer_fetch`): on a device that orders fetch only through the pixel
/// interlock, the state of every attachment the entry reads through a `[[color(n)]]` input of a
/// constant index (one an instruction of its specialized body uses: an input the function's
/// constants leave unread reads nothing), of every extended-range attachment it writes that the
/// pass blends (whose blend the function computes from the texel it reads) or writes unblended
/// under a mask of some of the codes one word holds (`color_writes::merged_extended`), of every
/// attachment held with its channels rotated whose blend the function computes
/// (`color_writes::shader_rotated_blend`, in either form below), and of every attachment variant
/// `v`'s instance keeps out of its subpass that the entry writes through its first output
/// (`VariantKey::interlocked_colors`); `None` on another device or for an entry that declares none
/// of them. On a device that orders fetch through rasterization-order input attachments, the state
/// of every extended-range attachment the entry writes that the pass blends (whose blend the
/// function computes over its input attachment, `lower::fragment`'s `input_blend`), of every
/// word attachment it writes under a mask of some of the word's channels (whose word the function
/// merges into its input attachment's, `color_writes::merged_word`), and of every extended-range
/// attachment it writes unblended under a mask of some of the codes one word holds (merged so,
/// `color_writes::merged_extended`). On either device, under a private logic operation the function computes
/// (`FragmentPass::logic_operation`), the state of every attachment whose format the operation
/// serves that the entry writes through its first output (`lower::fragment`'s `logic`).
/// (`LoweringInputs::framebuffer_fetch`): on a device that orders fetch through
/// rasterization-order input attachments, the state of every extended-range attachment the entry
/// writes that the pass blends (whose blend the function computes over its input attachment,
/// `lower::fragment`'s `input_blend`), of every attachment held with its channels rotated whose
/// blend the function computes (`color_writes::shader_rotated_blend`), of every word attachment
/// it writes under a mask of some of the word's channels (whose word the function merges into its
/// input attachment's, `color_writes::merged_word`), of every extended-range attachment it writes
/// unblended under a mask of some of the codes one word holds (merged so,
/// `color_writes::merged_extended`), and, under a private logic operation the function computes
/// (`FragmentPass::logic_operation`), of every attachment whose format the operation serves that
/// the entry writes through its first output (`lower::fragment`'s `logic`); `None` on another
/// device or for an entry that writes none of them.
pub(crate) fn fetch_inputs(
spec: &air::Entry,
d: FragmentPass<'_>,
v: &VariantKey,
p: &DeviceProfile,
) -> Option<crate::pipeline::lower_inputs::FramebufferFetchInputs> {
let interlock = crate::lower::fragment::interlock_orders(p);
let inputs = crate::lower::fragment::inputs_order(p);
if !matches!(spec.ep.stage, AbiStage::Fragment { .. }) || !(interlock || inputs) {
if !matches!(spec.ep.stage, AbiStage::Fragment { .. })
|| !crate::lower::fragment::inputs_order(p)
{
return None;
}
let blended = |color: u32| {
@@ -2546,15 +2532,6 @@ pub(crate) fn fetch_inputs(
.flatten()
.is_some_and(|c| crate::pipeline::color_writes::merged_extended(&c))
};
// A word attachment whose writes the function blends over, or merges into, the word it reads.
let stored_word = |color: u32| {
d.color_attachments
.get(color as usize)
.copied()
.flatten()
.and_then(|c| crate::pipeline::color_writes::stored_word(&c, p))
.is_some()
};
// A word attachment whose writes the function merges into the word its input attachment
// holds.
let merged_word = |color: u32| {
@@ -2586,23 +2563,11 @@ pub(crate) fn fetch_inputs(
.flatten()
.is_some_and(|c| crate::lower::fragment::logic_channels(c.pixel_format).is_some())
};
// A color input counts only where the specialized body reads it, as the lowering plans only
// a used parameter: a read the function's constants make dead reads nothing, so it takes
// neither the storage form nor its blend in the shader.
let used = params_used(spec);
let read: BTreeSet<u32> = spec
.ep
.params
.outputs
.iter()
.filter(|b| used.contains(&b.param))
.filter_map(|b| match b.role {
ParamRole::ColorInput {
index: AbiInt::Const(color),
..
} if interlock => Some(color),
_ => None,
})
.chain(spec.ep.outputs.iter().filter_map(|o| match o.role {
.filter_map(|o| match o.role {
OutputRole::RenderTarget {
attachment: AbiInt::Const(color),
index: 0,
@@ -2610,42 +2575,23 @@ pub(crate) fn fetch_inputs(
} if blended(color)
|| rotated_blend(color)
|| logic(color)
|| (interlock && (stored_word(color) || merged_extended(color)))
|| (inputs && (merged_word(color) || merged_extended(color))) =>
|| merged_word(color)
|| merged_extended(color) =>
{
Some(color)
}
// A color the draw's instance keeps out of its subpass, written through the storage
// form as a fetched one is.
OutputRole::RenderTarget {
attachment: AbiInt::Const(color),
index: 0,
..
} if interlock && v.interlocked_colors.contains(&color) => Some(color),
_ => None,
}))
})
.collect();
if read.is_empty() {
return None;
}
// The blend over an input attachment depends on the attachments' state alone: its write is
// the fixed function's, which the tests, coverage and views take as any other's.
Some(match interlock {
true => crate::pipeline::lower_inputs::FramebufferFetchInputs::of(
read,
d.color_attachments,
d.depth_or_stencil,
d.alpha_to_coverage,
d.max_vertex_amplification_count,
),
false => crate::pipeline::lower_inputs::FramebufferFetchInputs::of(
read,
d.color_attachments,
false,
false,
1,
),
})
Some(crate::pipeline::lower_inputs::FramebufferFetchInputs::of(
read,
d.color_attachments,
))
}
/// A fragment stage's lowering inputs under variant `v` on `p` that need no decoded entry: the
@@ -2826,7 +2772,7 @@ fn lower_inputs(
));
out.unattached_colors =
unattached_colors_written(spec, d.color_attachments, d.alpha_to_coverage);
out.framebuffer_fetch = fetch_inputs(spec, d, variant, p);
out.framebuffer_fetch = fetch_inputs(spec, d, p);
let read = raw_indices_read(spec);
out.viewport_index_varying = written.viewport && read.viewport;
out.render_target_array_index_varying = written.layer && read.layer;
@@ -3239,37 +3185,9 @@ fn lower_bounded<K>(
// count's) are the product's.
let writes_memory = crate::spirv::requirements::writes_memory(&module)?;
// A fragment function's texture slots read only at the fragment's own pixel.
let mut own_pixel_textures = crate::spirv::requirements::own_pixel_textures(&module, m)?;
let own_pixel_textures = crate::spirv::requirements::own_pixel_textures(&module, m)?;
// The levels of its bound view each texture slot's reads reach.
let level_reads = crate::spirv::requirements::level_reads(&module, m)?;
// Those a draw can read through a snapshot an earlier draw of the same primitives took, of a
// function that writes no memory, and why each other one is left out. A variant compiled to
// read them so states its own, and judges none: its only texel access of each is the entry's
// copy, at the fragment's own pixel.
let snapshots: Vec<u32> = plan.families.fragment.snapshot.keys().copied().collect();
let snapshot_textures = match snapshots.is_empty() {
false => {
if !crate::spirv::requirements::snapshot_copies_alone(&module, &snapshots, m)? {
return Err(Error::Internal(InternalError::new(
InternalKind::Invariant,
"a snapshot variant that reads its texture outside the copy",
)));
}
own_pixel_textures.extend(&snapshots);
own_pixel_textures.sort_unstable();
own_pixel_textures.dedup();
crate::spirv::requirements::Judged {
slots: snapshots,
refusals: Vec::new(),
}
}
true => crate::spirv::requirements::snapshot_textures(
&module,
&own_pixel_textures,
writes_memory,
m,
)?,
};
// A `half` rounded through `OpQuantizeToF16` (`QuantizeForm::Device`): the module records the
// native note on every profile, a result below the smallest normal half the device's.
let mut precision = plan.precision.clone();
@@ -3365,7 +3283,7 @@ fn lower_bounded<K>(
&function_tables,
(reaches_command_buffers, command_writes),
(writes_textures, numbered_samplers),
(own_pixel_textures, snapshot_textures, level_reads),
(own_pixel_textures, level_reads),
unbound,
);
let mut requirements = module.requirements.clone();
@@ -3533,11 +3451,7 @@ fn stage_interface(
function_tables: &std::collections::BTreeSet<u32>,
(reaches_command_buffers, command_writes): (bool, crate::pipeline::interface::CommandWrites),
(writes_textures, numbered_samplers): (bool, Vec<crate::pipeline::interface::NumberedSampler>),
(own_pixel_textures, snapshots, level_reads): (
Vec<u32>,
crate::spirv::requirements::Judged,
Vec<crate::pipeline::interface::LevelReads>,
),
(own_pixel_textures, level_reads): (Vec<u32>, Vec<crate::pipeline::interface::LevelReads>),
unbound: unbound::Unbound,
) -> StageInterface {
use crate::pipeline::interface::{BufferKind, BufferSlot};
@@ -3603,8 +3517,6 @@ fn stage_interface(
unbound_storage_textures: unbound.storage_textures,
numbered_samplers,
own_pixel_textures,
snapshot_textures: snapshots.slots,
snapshot_refusals: snapshots.refusals,
level_reads,
private_bytes: plan.private_bytes,
sampler_arrays: crate::lower::sampler::sampler_arrays(plan),
@@ -24,7 +24,7 @@
use crate::budget::{Budget, Meter};
use crate::cache::VariantKey;
use crate::device::requirements::{Requirements, VkExtension, VkFeature, VkLimit, VkProperty};
use crate::device::requirements::{Requirements, VkExtension, VkFeature, VkLimit};
use crate::device::{mechanism, Device, DeviceProfile};
use crate::error::{
ComputePipelineProblem, DescriptorError, Error, Feature, InternalError, InternalKind,
@@ -51,7 +51,7 @@ use crate::pipeline::descriptor::{
RenderPipelineDescriptor, StageSource, TileRenderPipelineDescriptor,
};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::graphics::{GraphicsState, StorageAttachmentView};
use crate::pipeline::graphics::GraphicsState;
use crate::pipeline::link::tessellation::{note_evaluation_stage, synthesized_stages};
use crate::pipeline::link::{link, LinkInputs, Linked, RenderLinkInputs};
use crate::pipeline::lower_inputs::LoweringInputs;
@@ -101,8 +101,9 @@ pub struct RenderPipelineKeys {
pub vertex_inputs: Option<LoweringInputs>,
/// The inputs a `Function` fragment stage compiles under (`VariantKey::lowering_inputs` of
/// the fragment stage, the signed-integer color attachments it writes, whether the pipeline is
/// multisampled, and the state of the attachments it reads where the device orders framebuffer
/// fetch only through the pixel interlock). `None` for a `Compiled` fragment stage or none.
/// multisampled, and the state of the attachments whose writes it computes over their input
/// attachments where the device orders framebuffer fetch through rasterization-order input
/// attachments). `None` for a `Compiled` fragment stage or none.
pub fragment_inputs: Option<LoweringInputs>,
}
@@ -447,8 +448,7 @@ impl Device {
// Every fragment function is decoded, to learn which colors it writes that the
// pipeline has no attachment for, as `compile_render_pipeline` and a mesh
// pipeline's fragment learn them; and so which signed-integer attachments it
// writes, which attachments it reads on a device that orders framebuffer fetch only
// through the pixel interlock, and whether it reads the `[[viewport_array_index]]`
// writes, and whether it reads the `[[viewport_array_index]]`
// or `[[render_target_array_index]]` its vertex function writes.
Some(source @ StageSource::Function(f)) => {
// Whether the function applies the private masks itself shows only in its
@@ -575,15 +575,9 @@ impl Device {
v: &VariantKey,
m: &mut Meter,
) -> Result<RenderPipeline, Error> {
// A mesh draw's plan zeroes and drops no color, nor writes one through the interlock it
// does not fetch, nor shadows one.
if !v.zeroed_colors.is_empty()
|| !v.dropped_colors.is_empty()
|| !v.interlocked_colors.is_empty()
{
return Err(invariant(
"a mesh variant zeroing, dropping, interlocking or shadowing colors",
));
// A mesh draw's plan zeroes and drops no color.
if !v.zeroed_colors.is_empty() || !v.dropped_colors.is_empty() {
return Err(invariant("a mesh variant zeroing or dropping colors"));
}
check_mesh_fields(d)?;
let p = self.profile();
@@ -969,7 +963,6 @@ impl Device {
graphics.sample_mask = crate::pipeline::private_state::sample_mask(
d,
fragment.as_ref().map(|f| f.artifact()),
&graphics,
)?;
crate::pipeline::private_state::alpha_tested(d, fragment.as_ref().map(|f| f.artifact()))?;
crate::pipeline::private_state::depth_compares_clamped(
@@ -979,7 +972,6 @@ impl Device {
crate::pipeline::private_state::logic_operated(
logic,
fragment.as_ref().map(|f| f.artifact()),
&graphics,
)?;
let logic_op = crate::pipeline::private_state::LogicDraw::vulkan(logic);
graphics.logic_op = logic_op;
@@ -1093,13 +1085,6 @@ fn graphics_requirements(
requirements
.features
.extend(graphics.dynamic_state_features()?);
// A pipeline that reads through snapshots samples a color attachment of its subpass in the
// feedback loop layout, created with its flag (`GraphicsState::snapshot_reads`).
if graphics.snapshot_reads {
requirements
.features
.insert(VkFeature::AttachmentFeedbackLoopLayout);
}
// Its color blend state: attachments that blend differently, dual-source blending.
requirements
.features
@@ -1146,46 +1131,6 @@ fn graphics_requirements(
.features
.insert(VkFeature::RasterizationOrderColorAttachmentAccess);
}
// The interlocked form's storage views of the attachments; the module's own requirements name
// the interlock and the fragment stores.
for a in &graphics.storage_attachments {
requirements.formats.extend(a.format_usages());
}
// The shader-side stencil's shadow; the module's own requirements name the interlock, the
// fragment stores, and multisampled storage images. A multisampled shadow is copied by image
// copies (`maintenance8`), and it, or the neutral that stands in for it without a stencil
// attachment, is a storage image of the pipeline's samples.
if let Some(s) = &graphics.shadow_stencil {
requirements.formats.extend(s.format_usages());
if s.samples > 1 {
requirements.features.insert(VkFeature::Maintenance8);
}
}
let multisampled_shadow = artifacts.iter().any(|a| {
a.facts.iter().any(|f| {
matches!(
f,
RuntimeFact::ShadowStencil {
multisampled: true,
..
}
)
})
});
// A per-sample framebuffer fetch's multisampled storage images have the pipeline's
// samples; planes are single-sample.
let multisampled_storage = graphics
.storage_attachments
.iter()
.any(|a| a.view == StorageAttachmentView::Attachment)
&& graphics.rasterization_samples.as_raw() > 1;
if multisampled_shadow || multisampled_storage {
requirements
.properties
.insert(VkProperty::StorageImageSampleCount(
graphics.rasterization_samples.as_raw(),
));
}
// A multiview pipeline needs `multiview` and its view count whether or not a stage reads the
// view index; the binder draws more amplifications than the device has views one at a time, so
// the views it needs are at most those.
@@ -1691,8 +1636,6 @@ fn stage_module(c: &CompiledFunction, linked: &Linked, i: usize) -> Result<Stage
rounded_colors,
specialized_notes: a.specialized.clone(),
own_pixel_textures: a.interface.own_pixel_textures.clone(),
snapshot_textures: a.interface.snapshot_textures.clone(),
snapshot_refusals: a.interface.snapshot_refusals.clone(),
level_reads: a.interface.level_reads.clone(),
private_bytes: a.interface.private_bytes,
// Link resolves the module's symbols and adds no instruction, so the function's own
@@ -240,11 +240,6 @@ pub fn function_key(
.bytes(format!("{:?}", inputs.srgb_textures).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
if !inputs.snapshot_textures.is_empty() {
h.bytes(b"snapshot-textures")
.bytes(format!("{:?}", inputs.snapshot_textures).as_bytes());
}
// Appended only when set, as `storage_view_slots`.
if !inputs.ycbcr_in_place.is_empty() {
h.bytes(b"ycbcr-in-place")
.bytes(format!("{:?}", inputs.ycbcr_in_place).as_bytes());
@@ -440,10 +435,6 @@ pub fn function_key(
.bytes(&inputs.depth_compare_clamp_mask.to_le_bytes());
}
// Appended only when set.
if inputs.read_only_tests {
h.bytes(b"read-only-tests");
}
// Appended only when set.
if inputs.threadgroup_size_matches_tile_size {
h.bytes(b"threadgroup-size-matches-tile-size");
}
+59 -534
View File
@@ -524,19 +524,13 @@ fn function_keys_cover_their_inputs() {
let cl = a.function_compile_key(&fd, &cl);
assert_ne!(with_true, cl);
assert_ne!(replay, cl);
// So is the interlocked framebuffer fetch's pipeline state, by its attachments' state.
// So is the framebuffer-fetch pipeline state, by its attachments' state.
let fetch = |format| {
let mut i = LoweringInputs::new();
let colors = [Some(
crate::pipeline::descriptor::ColorAttachmentDescriptor::new(format),
)];
i.framebuffer_fetch = Some(crate::pipeline::FramebufferFetchInputs::of(
[0],
&colors,
false,
false,
1,
));
i.framebuffer_fetch = Some(crate::pipeline::FramebufferFetchInputs::of([0], &colors));
a.function_compile_key(&fd, &i)
};
let r32 = fetch(metal::PixelFormat::R32Float);
@@ -670,7 +664,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
.replace(", merged_draws: false", "")
.replace(", framebuffer_fetch: None", "")
.replace(", srgb_textures: {}", "")
.replace(", snapshot_textures: {}", "")
.replace(", ycbcr_in_place: {}", "")
.replace(", ycbcr_planes_sampled: {}", "")
.replace(", texel_rows: {}", "")
@@ -1790,20 +1783,15 @@ fn a_vertex_pipeline_makes_its_input_assembly_dynamic_exactly_with_both_extended
/// A render pipeline whose fragment function reads its color attachment orders the read exactly
/// where the device can. With rasterization-order attachment access it states that access and
/// requires `rasterizationOrderColorAttachmentAccess` (enabled with its extension). With only the
/// ordered pixel interlock it reads and writes the attachment as a storage image inside the
/// interlock: no input attachment, no color attachment state for it, the interlock, the
/// fragment-stage store, and the format's storage access required; a blending attachment's blend
/// the shader computes (`R32Float`'s the generic one, noted). Where the pipeline's state blocks
/// that form (alpha to coverage), the pipeline is refused with the blocker. With neither form it
/// reads the input attachment without rasterization-order access, which the consumer's barriers
/// order between draws alone, and its fragment stage records
/// `PrecisionNote::UnorderedFetchWithinDraw`, which neither ordered form records. A raster order
/// group on the color input (`fetch_ordered`) takes the interlock where the device has it, and
/// with neither form orders that read alone: no interlock, noted.
/// requires `rasterizationOrderColorAttachmentAccess` (enabled with its extension). Without it,
/// with the ordered pixel interlock or not, it reads the input attachment without
/// rasterization-order access, which the consumer's barriers order between draws alone, a blend
/// the device's, and its fragment stage records `PrecisionNote::UnorderedFetchWithinDraw`, which
/// the ordered form does not record. A raster order group on the color input (`fetch_ordered`)
/// orders that read alone there: no interlock, noted.
#[test]
fn a_framebuffer_fetch_pipeline_is_ordered_exactly_where_the_device_orders_it() {
use crate::device::requirements::{FormatUsage, VkExtension, VkFeature};
use crate::device::requirements::{VkExtension, VkFeature};
use crate::pipeline::{PrecisionNote, RenderPipeline};
const ORDERED: VkFeature = VkFeature::RasterizationOrderColorAttachmentAccess;
const INTERLOCK: VkFeature = VkFeature::FragmentShaderPixelInterlock;
@@ -1822,13 +1810,19 @@ fn a_framebuffer_fetch_pipeline_is_ordered_exactly_where_the_device_orders_it()
RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(vertex)));
d.fragment = Some(StageSource::Function(FunctionDescriptor::new(fragment)));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(metal::PixelFormat::R32Float));
// Blended, adding the destination (a blend of one and zero, added, stores the source as no
// blending does).
// Blended, adding the destination.
let mut blended = d.clone();
if let Some(c) = blended.color_attachments[0].as_mut() {
c.blending_enabled = true;
c.destination_rgb_blend_factor = metal::BlendFactor::One;
}
let mut grouped = d.clone();
grouped.fragment = Some(StageSource::Function(FunctionDescriptor::new(
Library::from_air(&fetch)
.expect("library")
.function("fetch_ordered")
.expect("fragment"),
)));
let compile = |desc: &DeviceDescription, policy: DevicePolicy, d: &RenderPipelineDescriptor| {
let dev = Device::from_queries(desc.clone(), policy).expect("device");
let pipe = dev.compile_render_pipeline(d, &Budget::standard())?;
@@ -1854,7 +1848,6 @@ fn a_framebuffer_fetch_pipeline_is_ordered_exactly_where_the_device_orders_it()
let pipe = compile(&lavapipe, DevicePolicy::RESIDENT_TABLES, &d).expect("lavapipe");
assert!(!unordered(&pipe));
assert_eq!(pipe.graphics.input_attachments.len(), 1);
assert!(pipe.graphics.storage_attachments.is_empty());
assert!(pipe.graphics.rasterization_order_attachment_access);
assert!(pipe.requirements.features.contains(&ORDERED));
let enables = lavapipe
@@ -1869,90 +1862,18 @@ fn a_framebuffer_fetch_pipeline_is_ordered_exactly_where_the_device_orders_it()
let mut interlocked = lavapipe.clone();
interlocked.features.remove(&ORDERED);
assert!(interlocked.has(INTERLOCK));
{
let pipe = compile(&interlocked, DevicePolicy::RESIDENT_TABLES, &d).expect("interlocked");
assert!(!unordered(&pipe));
assert!(pipe.graphics.input_attachments.is_empty());
assert!(pipe.graphics.color_attachments.iter().all(Option::is_none));
let [s] = pipe.graphics.storage_attachments.as_slice() else {
panic!("{:?}", pipe.graphics.storage_attachments);
};
// Declared without a format where the device grants that: lavapipe does.
assert_eq!(
(s.color_index, s.format, s.writes, s.formatless),
(0, vk::Format::R32_SFLOAT, true, true)
);
// The capability, which the device resolves (`DeviceProfile::check`), not its feature.
assert!(pipe.requirements.spirv_capabilities.contains(
&crate::device::requirements::SpirvCapability::of(
crate::spv::Capability::StorageImageReadWithoutFormat
)
));
assert!(!pipe
.requirements
.features
.contains(&VkFeature::ShaderStorageImageReadWithoutFormat));
assert!(!pipe.graphics.rasterization_order_attachment_access);
for f in [INTERLOCK, VkFeature::FragmentStoresAndAtomics] {
assert!(pipe.requirements.features.contains(&f), "{f:?}");
}
assert!(!pipe.requirements.features.contains(&ORDERED));
assert!(pipe
.requirements
.formats
.contains(&(vk::Format::R32_SFLOAT, FormatUsage::StorageImage)));
}
// The blend, which the shader computes: the generic one of `R32Float`, noted.
{
let pipe = compile(&interlocked, DevicePolicy::RESIDENT_TABLES, &blended).expect("blended");
let [s] = pipe.graphics.storage_attachments.as_slice() else {
panic!("{:?}", pipe.graphics.storage_attachments);
};
assert_eq!((s.color_index, s.writes), (0, true));
let fragment = (pipe.stages.iter())
.find(|s| s.stage == vk::ShaderStage::FRAGMENT)
.expect("a fragment stage");
assert!(fragment
.precision_notes
.contains(&PrecisionNote::UnmeasuredFetchBlend));
}
// Alpha to coverage, which can drop the fragment's samples, blocks the form.
let mut covered = d.clone();
covered.alpha_to_coverage = true;
match compile(&interlocked, DevicePolicy::RESIDENT_TABLES, &covered) {
Err(Error::Unsupported(u)) => assert_eq!(
(u.feature, u.needs),
(Feature::FramebufferFetch, Needs::NotImplemented)
),
other => panic!("{:?}", other.map(|_| ())),
}
let mut without = interlocked.clone();
without.features.remove(&INTERLOCK);
let pipe = compile(&without, DevicePolicy::RESIDENT_TABLES, &d).expect("neither");
assert!(unordered(&pipe));
assert_eq!(pipe.graphics.input_attachments.len(), 1);
assert!(pipe.graphics.storage_attachments.is_empty());
assert!(!pipe.graphics.rasterization_order_attachment_access);
for f in [ORDERED, INTERLOCK] {
assert!(!pipe.requirements.features.contains(&f), "{f:?}");
}
let mut grouped = d.clone();
grouped.fragment = Some(StageSource::Function(FunctionDescriptor::new(
Library::from_air(&fetch)
.expect("library")
.function("fetch_ordered")
.expect("fragment"),
)));
let pipe = compile(&interlocked, DevicePolicy::RESIDENT_TABLES, &grouped).expect("grouped");
assert!(!unordered(&pipe));
assert!(pipe.requirements.features.contains(&INTERLOCK));
let pipe =
compile(&without, DevicePolicy::RESIDENT_TABLES, &grouped).expect("grouped, neither");
assert!(unordered(&pipe));
assert_eq!(pipe.graphics.input_attachments.len(), 1);
for f in [ORDERED, INTERLOCK] {
assert!(!pipe.requirements.features.contains(&f), "{f:?}");
for desc in [&interlocked, &without] {
for pd in [&d, &blended, &grouped] {
let pipe = compile(desc, DevicePolicy::RESIDENT_TABLES, pd).expect("unordered");
assert!(unordered(&pipe));
assert_eq!(pipe.graphics.input_attachments.len(), 1);
assert!(!pipe.graphics.rasterization_order_attachment_access);
for f in [ORDERED, INTERLOCK] {
assert!(!pipe.requirements.features.contains(&f), "{f:?}");
}
}
}
}
@@ -2041,10 +1962,6 @@ fn an_identity_fetch_reads_its_attachments_pushed_texture_in_the_attachments_cla
pipe.graphics.input_attachments.is_empty(),
"{fragment} {format:?}"
);
assert!(
pipe.graphics.storage_attachments.is_empty(),
"{fragment} {format:?}"
);
assert!(!pipe.graphics.rasterization_order_attachment_access);
assert!(
(pipe.layout.sets.iter())
@@ -2102,80 +2019,20 @@ fn images_and_sample_id(words: &[u32]) -> (Vec<(u32, u32, u32)>, bool) {
(images, sample_id)
}
/// The guard of the one storage write in `words` where a returned sample mask's bit gates it:
/// `Some(shift)` where the write's block is the true arm of a branch on
/// `((mask >> shift) & 1) != 0`, `shift` the shift's constant (`Some(0)` where no shift is left),
/// or `None` where the shift is not a constant (the invocation's `SampleId`); `None` where no
/// such branch guards the write.
fn mask_gate(words: &[u32]) -> Option<Option<u32>> {
const IMAGE_WRITE: u32 = 99;
const CONSTANT: u32 = 43;
const I_NOT_EQUAL: u32 = 171;
const SHIFT_RIGHT_LOGICAL: u32 = 194;
const BITWISE_AND: u32 = 199;
const LABEL: u32 = 248;
const BRANCH_CONDITIONAL: u32 = 250;
let mut defs = std::collections::HashMap::new();
let (mut branches, mut writes, mut label) = (Vec::new(), Vec::new(), 0);
let mut at = 5;
while at < words.len() {
let (count, op) = ((words[at] >> 16) as usize, words[at] & 0xFFFF);
let inst = &words[at..at + count.max(1)];
match op {
CONSTANT | I_NOT_EQUAL | SHIFT_RIGHT_LOGICAL | BITWISE_AND => {
defs.insert(inst[2], (op, &inst[3..]));
}
LABEL => label = inst[1],
BRANCH_CONDITIONAL => branches.push((inst[1], inst[2])),
IMAGE_WRITE => writes.push(label),
_ => {}
}
at += count.max(1);
}
let def = |id: &u32, want: u32| match defs.get(id) {
Some(&(op, operands)) if op == want => Some(operands),
_ => None,
};
let constant = |id: &u32| def(id, CONSTANT).and_then(|v| v.first().copied());
let [write] = writes.as_slice() else {
return None;
};
let (condition, _) = branches.iter().find(|(_, arm)| arm == write)?;
let [bit, zero] = def(condition, I_NOT_EQUAL)? else {
return None;
};
let [shifted, one] = def(bit, BITWISE_AND)? else {
return None;
};
if (constant(zero), constant(one)) != (Some(0), Some(1)) {
return None;
}
Some(match def(shifted, SHIFT_RIGHT_LOGICAL) {
Some([_, shift]) => constant(shift),
_ => Some(0),
})
}
/// Metal runs a function that reads a color attachment of a multisampled pass once per covered
/// sample, reading its own sample. Compiled for a pipeline of 4 samples, the fragment reads each
/// color at its `SampleId` (which runs it once per covered sample under sample shading): on
/// lavapipe through a multisampled `SubpassData` image under rasterization-order access, on a
/// device that orders fetch only through the pixel interlock through a multisampled storage image
/// of the pipeline's samples (`shaderStorageImageMultisample`, `storageImageSampleCounts`), and,
/// where that device has no multisampled storage image (ANV, MoltenVK), through planes: a
/// single-sample 2D-array storage image of one layer per sample, which needs neither. Where the
/// device lacks what the form needs, the refusal names it; a returned sample mask is exact per
/// sample (the storage write is gated on the sample's bit) and at one sample (gated on bit 0, as
/// Metal stores); `[[sample_mask]]` in is the pixel's coverage, which no device gives a per-sample
/// invocation. One sample compiles as before: no `SampleId`, a single-sample image.
/// color at its `SampleId` (which runs it once per covered sample under sample shading) through a
/// multisampled `SubpassData` image: on lavapipe under rasterization-order access, and on a device
/// without it unordered within a draw (noted). Where the device lacks sample-rate shading, the
/// refusal names it; `[[sample_mask]]` in is the pixel's coverage, which no device gives a
/// per-sample invocation. One sample compiles as before: no `SampleId`, a single-sample image.
#[test]
fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() {
use crate::device::requirements::{VkFeature, VkProperty};
use crate::error::{Capability, Unsupported};
use crate::pipeline::{RenderPipeline, StorageAttachmentView};
use crate::device::requirements::VkFeature;
use crate::error::Capability;
use crate::pipeline::{PrecisionNote, RenderPipeline};
const ORDERED: VkFeature = VkFeature::RasterizationOrderColorAttachmentAccess;
const SUBPASS_DATA: u32 = 6;
const D2: u32 = 1;
let (Some(io), Some(blend), Some(ms)) = (
fixture("stage_io"),
fixture("exf_fetch_blend"),
@@ -2218,161 +2075,44 @@ fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() {
Err(Error::Unsupported(u)) => (u.feature, u.needs),
other => panic!("{:?}", other.map(|_| ())),
};
let unordered = |pipe: &RenderPipeline| {
pipe.stages[1]
.precision_notes
.contains(&PrecisionNote::UnorderedFetchWithinDraw)
};
// Raster order: the input attachment's own sample.
// The input attachment's own sample, ordered where the device orders it.
let lavapipe = description("lavapipe");
let pipe = compile(&lavapipe, &descriptor(&blend, "exf_fetch_blend", 4)).expect("lavapipe");
assert_eq!(pipe.graphics.input_attachments.len(), 1);
assert!(pipe.graphics.storage_attachments.is_empty());
assert!(pipe.graphics.rasterization_order_attachment_access);
assert_eq!(
pipe.graphics.rasterization_samples,
vk::SampleCountFlags::COUNT_4
);
for f in [ORDERED, VkFeature::SampleRateShading] {
assert!(pipe.requirements.features.contains(&f), "{f:?}");
}
assert_eq!(
images_and_sample_id(&fragment_words(&pipe)),
(vec![(SUBPASS_DATA, 0, 1)], true)
);
let one = compile(&lavapipe, &descriptor(&blend, "exf_fetch_blend", 1)).expect("one");
assert_eq!(
images_and_sample_id(&fragment_words(&one)),
(vec![(SUBPASS_DATA, 0, 0)], false)
);
// The returned mask and alpha to coverage stay the fixed function's.
compile(&lavapipe, &descriptor(&ms, "msf_fetch_mask_out", 4)).expect("mask out");
// The pixel interlock: a multisampled storage image of the pipeline's samples.
let mut interlocked = lavapipe.clone();
interlocked.features.remove(&ORDERED);
let pipe = compile(&interlocked, &descriptor(&blend, "exf_fetch_blend", 4)).expect("storage");
assert!(pipe.graphics.input_attachments.is_empty());
let [s] = pipe.graphics.storage_attachments.as_slice() else {
panic!("{:?}", pipe.graphics.storage_attachments);
};
assert_eq!(
(s.color_index, s.format, s.writes, s.view),
(
0,
vk::Format::R32G32B32A32_SFLOAT,
true,
StorageAttachmentView::Attachment
)
);
for f in [
VkFeature::FragmentShaderPixelInterlock,
VkFeature::ShaderStorageImageMultisample,
VkFeature::SampleRateShading,
] {
assert!(pipe.requirements.features.contains(&f), "{f:?}");
}
assert!(pipe
.requirements
.properties
.contains(&VkProperty::StorageImageSampleCount(4)));
assert_eq!(
images_and_sample_id(&fragment_words(&pipe)),
(vec![(D2, 0, 1)], true)
);
let one = compile(&interlocked, &descriptor(&blend, "exf_fetch_blend", 1)).expect("one");
assert_eq!(
images_and_sample_id(&fragment_words(&one)),
(vec![(D2, 0, 0)], false)
);
assert!(!one
.requirements
.properties
.contains(&VkProperty::StorageImageSampleCount(1)));
// A returned mask (`msf_fetch_mask_out` returns 0x5) gates the write on the invocation's own
// sample's bit; at one sample, where no `SampleId` is read, on bit 0, as Metal stores no color
// without it (before, refused `NotImplemented(FramebufferFetch)`).
let four = compile(&interlocked, &descriptor(&ms, "msf_fetch_mask_out", 4)).expect("mask out");
assert_eq!(
images_and_sample_id(&fragment_words(&four)),
(vec![(D2, 0, 1)], true)
);
assert_eq!(mask_gate(&fragment_words(&four)), Some(None));
let one = compile(&interlocked, &descriptor(&ms, "msf_fetch_mask_out", 1)).expect("one mask");
let [s] = one.graphics.storage_attachments.as_slice() else {
panic!("{:?}", one.graphics.storage_attachments);
};
assert_eq!(
(s.color_index, s.writes, s.view),
(0, true, StorageAttachmentView::Attachment)
);
assert_eq!(
images_and_sample_id(&fragment_words(&one)),
(vec![(D2, 0, 0)], false)
);
assert_eq!(mask_gate(&fragment_words(&one)), Some(Some(0)));
// Without multisampled storage images: planes, one single-sample layer per sample, which
// need neither the feature nor a sample count of storage images. ANV and MoltenVK.
let mut no_storage_ms = interlocked.clone();
no_storage_ms
.features
.remove(&VkFeature::ShaderStorageImageMultisample);
no_storage_ms.limits.storage_image_sample_counts = vk::SampleCountFlags::COUNT_1;
for desc in [
&no_storage_ms,
&description("moltenvk-m3"),
&description("intel-arl-anv"),
] {
let pipe = compile(desc, &descriptor(&blend, "exf_fetch_blend", 4)).expect("planes");
let [s] = pipe.graphics.storage_attachments.as_slice() else {
panic!("{:?}", pipe.graphics.storage_attachments);
};
let mut unordered_device = lavapipe.clone();
unordered_device.features.remove(&ORDERED);
for (desc, ordered) in [(&lavapipe, true), (&unordered_device, false)] {
let pipe = compile(desc, &descriptor(&blend, "exf_fetch_blend", 4)).expect("four");
assert_eq!(pipe.graphics.input_attachments.len(), 1);
assert_eq!(pipe.graphics.rasterization_order_attachment_access, ordered);
assert_eq!(unordered(&pipe), !ordered);
assert_eq!(
(s.color_index, s.format, s.writes, s.view),
(
0,
vk::Format::R32G32B32A32_SFLOAT,
true,
StorageAttachmentView::SamplePlanes { layers: 4 }
)
pipe.graphics.rasterization_samples,
vk::SampleCountFlags::COUNT_4
);
for f in [
VkFeature::FragmentShaderPixelInterlock,
VkFeature::SampleRateShading,
] {
assert!(pipe.requirements.features.contains(&f), "{f:?}");
}
assert!(!pipe
assert!(pipe
.requirements
.features
.contains(&VkFeature::ShaderStorageImageMultisample));
assert!(!pipe
.requirements
.properties
.iter()
.any(|p| matches!(p, VkProperty::StorageImageSampleCount(_))));
.contains(&VkFeature::SampleRateShading));
assert_eq!(pipe.requirements.features.contains(&ORDERED), ordered);
assert_eq!(
images_and_sample_id(&fragment_words(&pipe)),
(vec![(D2, 1, 0)], true)
(vec![(SUBPASS_DATA, 0, 1)], true)
);
compile(desc, &descriptor(&ms, "msf_fetch_mask_out", 4)).expect("mask out");
let one = compile(desc, &descriptor(&blend, "exf_fetch_blend", 1)).expect("one");
assert_eq!(
one.graphics.storage_attachments[0].view,
StorageAttachmentView::Attachment
);
assert_eq!(
images_and_sample_id(&fragment_words(&one)),
(vec![(D2, 0, 0)], false)
(vec![(SUBPASS_DATA, 0, 0)], false)
);
// The returned mask and alpha to coverage stay the fixed function's.
compile(desc, &descriptor(&ms, "msf_fetch_mask_out", 4)).expect("mask out");
}
let mut no_count = interlocked.clone();
no_count.limits.storage_image_sample_counts = vk::SampleCountFlags::COUNT_1;
assert_eq!(
compile(&no_count, &descriptor(&blend, "exf_fetch_blend", 4)).map(|_| ()),
Err(Error::Unsupported(Unsupported::needs(
Feature::FramebufferFetch,
Capability::Property(VkProperty::StorageImageSampleCount(4))
)))
);
// Without sample-rate shading no form reads a sample.
for desc in [&lavapipe, &interlocked, &no_storage_ms] {
for desc in [&lavapipe, &unordered_device] {
let mut no_rate = desc.clone();
no_rate.features.remove(&VkFeature::SampleRateShading);
let (feature, needs) =
@@ -2387,7 +2127,7 @@ fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() {
.any(|c| *c == Capability::Feature(VkFeature::SampleRateShading)));
}
// `[[sample_mask]]` in beside a fetch reads the pixel's coverage (measured): no device.
for desc in [&lavapipe, &interlocked, &no_storage_ms] {
for desc in [&lavapipe, &unordered_device] {
assert_eq!(
refusal(compile(desc, &descriptor(&ms, "msf_fetch_mask_in", 4))),
(Feature::PixelCoverageAtSampleRate, Needs::NotRepresentable)
@@ -3019,221 +2759,6 @@ fn the_interface_states_the_textures_read_at_the_fragments_own_pixel() {
assert_eq!(checks.len(), 2, "both read checks");
}
/// The interface states why it leaves an own-pixel slot out of those a draw can read through a
/// snapshot (`StageInterface::snapshot_refusals`, `spirv::requirements::snapshot`): owned fixture
/// `snapshot_discard`'s `sd_read_discarding`, which discards by the texel it read, states none on
/// the Radeon 780M's profile, where the discard demotes the invocation and the slot qualifies, and
/// its branch alone where the profile withholds `shaderDemoteToHelperInvocation` and the discard
/// ends the invocation; `tob_renders`'s `tob_read` states none on either. The stage module of a
/// render pipeline of it states the same.
#[test]
fn the_interface_states_why_a_slot_takes_no_snapshot() {
use crate::device::requirements::VkFeature;
use crate::pipeline::interface::SnapshotRefusal;
let (Some(discarding), Some(reading)) = (fixture("snapshot_discard"), fixture("tob_renders"))
else {
return;
};
let demotes = device("amd-780m-radv");
let mut d = description("amd-780m-radv");
assert!(
(d.features).remove(&VkFeature::ShaderDemoteToHelperInvocation),
"the 780M's profile demotes"
);
let ends = Device::from_queries(d, DevicePolicy::RESIDENT_TABLES).expect("device");
for (name, dev, refusals) in [
("demote", &demotes, Vec::new()),
("no demote", &ends, vec![(0, SnapshotRefusal::Branch)]),
] {
let p = dev.profile();
let a = crate::pipeline::testing::compile(&discarding, "sd_read_discarding", p)
.unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!(a.interface.own_pixel_textures, [0u32], "{name}");
let slots: &[u32] = if refusals.is_empty() { &[0] } else { &[] };
assert_eq!(a.interface.snapshot_textures, slots, "{name}");
assert_eq!(a.interface.snapshot_refusals, refusals, "{name}");
let read = crate::pipeline::testing::compile(&reading, "tob_read", p)
.unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!(read.interface.snapshot_textures, [0u32], "{name}: tob_read");
assert!(
read.interface.snapshot_refusals.is_empty(),
"{name}: tob_read"
);
let rect = Library::from_air(&reading).expect("library");
let rect = rect.function("tob_rect").expect("vertex");
let discard = Library::from_air(&discarding).expect("library");
let discard = discard.function("sd_read_discarding").expect("fragment");
let mut d =
RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(rect)));
d.fragment = Some(StageSource::Function(FunctionDescriptor::new(discard)));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(
metal::PixelFormat::RGBA8Unorm,
));
let pipe = (dev.compile_render_pipeline(&d, &Budget::standard()))
.unwrap_or_else(|e| panic!("{name}: {e}"));
let fragment = (pipe.stages.iter())
.find(|s| s.stage == vk::ShaderStage::FRAGMENT)
.expect("a fragment stage");
assert_eq!(fragment.snapshot_textures, slots, "{name}: the stage");
assert_eq!(fragment.snapshot_refusals, refusals, "{name}: the stage");
}
}
/// A selection on the texel a fragment read at its own pixel keeps the slot where a helper
/// invocation may take either arm (`spirv::requirements::snapshot`'s `arms`): owned fixture
/// `snapshot_select`'s `ss_read_selecting`, whose arm halves the red, states none on the Radeon
/// 780M's profile and on lavapipe's; `ss_read_selecting_dfdx`, whose arm also takes a derivative,
/// and `wlk_readers`'s `wlk_read_branch`, whose texel decides a loop's trip count, state their
/// branch.
#[test]
fn a_selection_on_the_texel_keeps_the_slot_where_a_helper_may_take_either_arm() {
use crate::pipeline::interface::SnapshotRefusal;
let (Some(selecting), Some(looping)) = (fixture("snapshot_select"), fixture("wlk_readers"))
else {
return;
};
for stem in ["amd-780m-radv", "lavapipe"] {
let p = crate::pipeline::testing::profile(stem, DevicePolicy::RESIDENT_TABLES)
.expect("profile");
for (bc, entry, refusals) in [
(&selecting, "ss_read_selecting", Vec::new()),
(
&selecting,
"ss_read_selecting_dfdx",
vec![(0, SnapshotRefusal::Branch)],
),
(
&looping,
"wlk_read_branch",
vec![(0, SnapshotRefusal::Branch)],
),
] {
let a = crate::pipeline::testing::compile(bc, entry, &p)
.unwrap_or_else(|e| panic!("{stem} {entry}: {e}"));
assert_eq!(a.interface.own_pixel_textures, [0u32], "{stem} {entry}");
let slots: &[u32] = if refusals.is_empty() { &[0] } else { &[] };
assert_eq!(a.interface.snapshot_textures, slots, "{stem} {entry}");
assert_eq!(a.interface.snapshot_refusals, refusals, "{stem} {entry}");
}
}
}
/// The interface states the own-pixel slots a draw can read through a snapshot
/// (`spirv::requirements::snapshot`): `tob_read`'s, whose texel reaches only its output. Its
/// snapshot variant (`LoweringInputs::snapshot_textures`) links and validates on every profile with
/// the pixel interlock, which it requires; binds the slot's snapshot; places the phase in the
/// fragment window; still states the slot, as read at the own pixel and through a snapshot; and
/// writes no memory of the function's. A profile without the interlock refuses it, naming the
/// feature. A variant asked for `tob_sample`'s slot, which the fact does not list, would sample the
/// texture beside the copy: refused, never compiled so.
#[test]
fn a_snapshot_variant_reads_its_texture_in_the_copy_alone() {
use crate::device::requirements::VkFeature;
use crate::error::Capability;
use crate::pipeline::interface::PushLoc;
use crate::pipeline::sym::{PushField, ResourceKind, SlotClass, SlotRef, SnapshotForm, Stage};
let Some(bc) = fixture("tob_renders") else {
return;
};
let inputs = |form: SnapshotForm| {
let mut inputs = LoweringInputs::new();
let slot = SlotRef {
stage: Stage::Fragment,
class: SlotClass::Texture,
index: 0,
};
inputs.snapshot_textures.insert(slot, form);
inputs
};
let mut interlocked = 0;
for stem in [
"intel-irisxe-anv",
"nvidia-rtx5080-laptop",
"amd-780m-radv",
"lavapipe",
"moltenvk-m3",
"runtime-floor",
] {
let p = crate::pipeline::testing::profile(stem, DevicePolicy::RESIDENT_TABLES)
.expect("profile");
let base = crate::pipeline::testing::compile(&bc, "tob_read", &p)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_eq!(base.interface.snapshot_textures, [0u32], "{stem}");
let sampled = crate::pipeline::testing::compile(&bc, "tob_sample", &p)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert!(sampled.interface.snapshot_textures.is_empty(), "{stem}");
let variant = crate::pipeline::testing::compile_with(
&bc,
"tob_read",
&p,
&inputs(SnapshotForm::Bits),
);
if !p.fields().fragment.pixel_interlock {
assert_eq!(
variant.map(|_| ()),
Err(Error::Unsupported(crate::error::Unsupported::needs(
Feature::RasterOrderGroups,
Capability::Feature(VkFeature::FragmentShaderPixelInterlock),
))),
"{stem}"
);
continue;
}
interlocked += 1;
// Each form of a float slot's codes compiles, its copy alone reading the texture.
for form in [
SnapshotForm::Unorm8,
SnapshotForm::Snorm8,
SnapshotForm::Unorm16,
SnapshotForm::Snorm16,
SnapshotForm::Half,
] {
let narrow = crate::pipeline::testing::compile_with(&bc, "tob_read", &p, &inputs(form))
.unwrap_or_else(|e| panic!("{stem} {form:?}: {e}"));
assert_eq!(
narrow.interface.snapshot_textures,
[0u32],
"{stem} {form:?}"
);
}
let a = variant.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_eq!(a.interface.snapshot_textures, [0u32], "{stem}");
assert_eq!(a.interface.own_pixel_textures, [0u32], "{stem}");
assert!(!a.interface.writes_memory, "{stem}");
assert!(
a.interface
.descriptors
.iter()
.any(|d| d.slot.kind == ResourceKind::SnapshotTexels(0)),
"{stem}"
);
assert!(
a.interface.push.fields.iter().any(|f| {
f.field == PushField::SnapshotPhase && matches!(f.loc, PushLoc::Push { .. })
}),
"{stem}"
);
assert!(
a.requirements
.features
.contains(&VkFeature::FragmentShaderPixelInterlock),
"{stem}"
);
crate::pipeline::testing::link_and_validate(&a, &p)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
match crate::pipeline::testing::compile_with(
&bc,
"tob_sample",
&p,
&inputs(SnapshotForm::Bits),
) {
Err(Error::Internal(e)) if e.kind == InternalKind::Invariant => {}
other => panic!("{stem} tob_sample: {other:?}"),
}
}
assert!(interlocked >= 4, "the interlocked profiles");
}
/// The interface states whether the function writes memory another invocation or a later command
/// can read: a buffer store, an image write (through an argument buffer's handle too), in a
/// fragment function or a kernel alike; a function that only reads does not, nor does one that only
+3 -118
View File
@@ -4,8 +4,6 @@
//! their values, and `device::mechanism(fact, profile)` is a total function with one [`Mechanism`]
//! per (fact, profile).
use crate::air::container::Hash256;
use crate::pipeline::sym::{ImageHandleClass, SlotRef, Stage};
/// Translation-relevant state that Metal binds at pipeline or encode time.
@@ -124,24 +122,6 @@ pub enum RuntimeFact {
/// buffer slot the pipeline writes may be bound overlapping its window: instantiation checks
/// the Metal addresses (`BindError::UniformViewAliased`).
UniformViewAliasing { slot: SlotRef },
/// The fragment function reads or writes the render pass's imageblock, whose cells take
/// `words` 32-bit words per pixel (`air.imageblock_data_size` rounded up to a word): the
/// consumer binds the pass's imageblock storage (`SyntheticBinding::Imageblock`), which
/// `GraphicsState::fragment_imageblock` describes. `writes`: the function writes the
/// imageblock, so the storage holds its write before the pipeline's coverage (alpha to
/// coverage) could drop the fragment (the depth and stencil tests run before its write: its
/// module declares early tests, or it states [`TestedStorageWrites`](Self::TestedStorageWrites));
/// `master`: the fingerprint of the master
/// layout its views view (`FragmentImageblock::master`); `data_size`: the cell's bytes
/// (`air.imageblock_data_size`); `alignment`: the alignment Metal states for its views
/// (`air.arg_type_align_size`, `FragmentImageblock::alignment`).
FragmentImageblock {
words: u32,
writes: bool,
master: Hash256,
data_size: u32,
alignment: u32,
},
/// The kernel is a tile function (`Device::compile_tile_pipeline`): a dispatch covers the
/// render pass's render area (`BindState::render_area`, `SpecKey::RenderAreaWidth` and
/// `SpecKey::RenderAreaHeight`) in tiles of the imageblock size (`BindState::imageblock_size`),
@@ -228,52 +208,6 @@ pub enum RuntimeFact {
/// one). A slot read only this way needs no acceleration-structure descriptor, so no ray
/// tracing feature.
AccelerationStructureInstanceCount { slot: SlotRef },
/// The function reads color attachment `color`, and writes it when `writes`, as a storage
/// image inside the ordered pixel interlock: framebuffer fetch on a device that orders it
/// only that way (no `rasterizationOrderColorAttachmentAccess`, with
/// `fragmentShaderPixelInterlock`), where its render pipeline's state
/// (`LoweringInputs::framebuffer_fetch`) lets the form be exact
/// (`GraphicsState::storage_attachments`). `format` is the attachment's Vulkan format, which
/// the module's storage image declaration serves. `early_tests`: the module declares early
/// fragment tests: Metal's function declares them, or its pipeline state has a depth or
/// stencil attachment and they keep its writes Metal's (it runs no discard, exports no depth,
/// stencil, or coverage, and writes no other memory), or its draws' tests write nothing
/// (`TestedStorageWrites`). Link checks the form against the pipeline it links into: one whose
/// state would not choose it, would view another format, or needs early tests the module does
/// not declare (a depth or stencil attachment where it was compiled without one, but for
/// `TestedStorageWrites`) is `NeedsInput(FramebufferFetch)`. `kept`: the format's channels each
/// write keeps from the texel it overwrites, those outside the descriptor's write mask, which
/// the write takes from the texel it reads first (all four where the mask covers none of the
/// format's channels, so it stores nothing; empty where it covers every one, or the function
/// does not write the attachment); a pipeline of another mask is `NeedsInput(FramebufferFetch)`
/// too. `blend`: the blend the function computes in the shader, from the texel it reads first,
/// for an extended-range attachment it writes under blending, which the function then need not
/// read, or a 16-bit float one (Metal's blend in the output's arithmetic); a pipeline of another
/// blend there is `NeedsInput(FramebufferFetch)` too. `rounded`: that blend is computed
/// without fast math, each product rounded before the sum
/// (`lower::arith::extended_range::blend::BlendMath::Rounded`), whose model holds blends the
/// fast one refuses; link checks the blend under that math.
InterlockedFramebufferFetch {
color: u32,
format: crate::vk::Format,
writes: bool,
early_tests: bool,
kept: crate::vk::ColorComponentFlags,
blend: Option<crate::pipeline::lower_inputs::BlendEquation>,
rounded: bool,
},
/// The function's `[[stencil]]` output is a shader-side stencil: on a device without
/// `VK_EXT_shader_stencil_export`, with the ordered pixel interlock, the function applies
/// Metal's stencil test and operations to a shadow of the stencil attachment inside the
/// interlock (`SyntheticBinding::ShadowStencil`, `PushField::ShadowStencilState`) and kills a
/// fragment that fails (`GraphicsState::shadow_stencil`). `formatless`: the module declares
/// the shadow without a format (`Unknown`), else as `R8ui`. `multisampled`: compiled for a
/// pipeline of more than one sample (`LoweringInputs::multisampled`), the shadow is a
/// multisampled image and the function tests each sample of its coverage.
ShadowStencil {
formatless: bool,
multisampled: bool,
},
/// The kernel's predicated walk votes in a workgroup word of its own
/// (`lower::simd::divergent::VOTE_BYTES`, 4 bytes beside its threadgroup arena): it runs a
/// workgroup barrier that part of the workgroup skips in the source in every invocation, and
@@ -406,10 +340,9 @@ pub enum RuntimeFact {
/// The tile function declares an explicit imageblock that stands alone (no implicit one
/// beside it, and not aliased onto one), of `data_size` bytes (`air.imageblock_data_size`)
/// whose layout aligns to `alignment` (`air.arg_type_align_size`). Its cells are the render
/// pass's imageblock storage (`SyntheticBinding::Imageblock`), which the pass's fragment
/// functions' imageblocks are in and the consumer keeps for the pass: a dispatch whose plan
/// writes `WriteSource::Imageblock` binds it, and the pass's draws and dispatches share it
/// by its bytes. With the color attachments it gives the tile pipeline state's
/// pass's imageblock storage (`SyntheticBinding::Imageblock`), which the consumer keeps for
/// the pass: a dispatch whose plan writes `WriteSource::Imageblock` binds it, and the pass's
/// dispatches share it by its bytes. With the color attachments it gives the tile pipeline state's
/// `imageblockSampleLength` as a fragment function's explicit imageblock does (measured on an
/// M4).
TileImageblock { data_size: u32, alignment: u32 },
@@ -479,49 +412,6 @@ pub enum RuntimeFact {
/// through its device address (`VariantKey::addressed_function_tables`). `addressed` states
/// that this compile is that variant.
FunctionTableRange { addressed: bool },
/// The fragment function stores some channels of a color attachment through the interlocked
/// storage form (`InterlockedFramebufferFetch`) in a pipeline with a depth or stencil
/// attachment, and discards, but declares no `[[early_fragment_tests]]`, exports no depth,
/// stencil, or coverage, and writes no other memory: Metal tests its fragments after it runs,
/// so whether its write stores is the draw's depth and stencil tests' to decide. Without
/// `early_tests` its module stores before Vulkan's tests, Metal's store wherever the draw's
/// tests drop no fragment; with it (`LoweringInputs::read_only_tests`) the module declares
/// early fragment tests, Metal's store wherever they write neither attachment and count no
/// visibility result. The plan of a draw whose tests drop fragments asks for the variant with
/// `early_tests` where they write and count nothing (`VariantKey::read_only_tests`), and
/// refuses any other (`BindShape::fragment_tests`).
///
/// `early_variant`: whether that variant serves a draw whose tests drop fragments but write and
/// count nothing, which it does for a function that only its discard keeps from early tests. A
/// function that writes other memory, or returns depth, stencil, or a sample mask, beside a
/// depth or stencil attachment states the fact without it: Metal runs its memory writes for the
/// fragments its tests then drop, and tests what it returns, which early tests would not. Its
/// stores before the tests are Metal's only where the draw's tests drop no fragment, and the
/// plan refuses every other draw.
TestedStorageWrites {
early_tests: bool,
early_variant: bool,
},
/// On a device that orders framebuffer fetch only through the ordered pixel interlock, the
/// fragment function writes
/// a color through its first output and does not declare early fragment tests, and it
/// discards, writes other memory, or returns depth, stencil, or a sample mask. A draw may move
/// such a color into the interlocked storage form (`BindShape::interlocked_colors`), whose
/// variant then stores before the
/// depth and stencil tests and states [`TestedStorageWrites`](Self::TestedStorageWrites) with
/// this `early_variant`, where the write stores something. So the plan of a pipeline that
/// writes no color so selects the tests of such a draw from this as from that fact, and the
/// variant it names plans itself.
///
/// The plan reads it only for a draw that moves a color the function writes as an ordinary
/// output under a write mask that names some of the attachment's components (and only where
/// the pipeline has a depth or stencil attachment, whose tests the variant then depends on). A
/// write whose mask names none of them stores nothing: no test bears on it, its variant states
/// no store before the tests, and the plan selects none for it, as for a draw that moves
/// nothing. A draw whose tests neither the early-tests variant nor the function's own tests
/// serve (tests the draw does not state) is refused, as any draw whose variant is refused: the
/// runtime keeps the color out of the storage form there (the pass splits, or the shadow ends).
MovableStorageWrites { early_variant: bool },
/// The tile function reads a builtin whose answer depends on its pipeline's
/// `threadgroupSizeMatchesTileSize` (its threads per threadgroup, simdgroups or quadgroups
/// per threadgroup or their `dispatch_` forms, its position in the grid, the threads per
@@ -864,7 +754,6 @@ impl RuntimeFact {
RuntimeFact::StageInStride { .. } => "StageInStride",
RuntimeFact::UniformViewRange { .. } => "UniformViewRange",
RuntimeFact::UniformViewAliasing { .. } => "UniformViewAliasing",
RuntimeFact::FragmentImageblock { .. } => "FragmentImageblock",
RuntimeFact::TileFunction => "TileFunction",
RuntimeFact::TileAttachmentFormat { .. } => "TileAttachmentFormat",
RuntimeFact::StorageTextureNumericType { .. } => "StorageTextureNumericType",
@@ -876,8 +765,6 @@ impl RuntimeFact {
RuntimeFact::AccelerationStructureInstanceCount { .. } => {
"AccelerationStructureInstanceCount"
}
RuntimeFact::InterlockedFramebufferFetch { .. } => "InterlockedFramebufferFetch",
RuntimeFact::ShadowStencil { .. } => "ShadowStencil",
RuntimeFact::PredicationVote => "PredicationVote",
RuntimeFact::SrgbTexture { .. } => "SrgbTexture",
RuntimeFact::UlongAtomicView { .. } => "UlongAtomicView",
@@ -905,8 +792,6 @@ impl RuntimeFact {
RuntimeFact::RotatedWeights => "RotatedWeights",
RuntimeFact::ConstantLanes { .. } => "ConstantLanes",
RuntimeFact::FunctionTableRange { .. } => "FunctionTableRange",
RuntimeFact::TestedStorageWrites { .. } => "TestedStorageWrites",
RuntimeFact::MovableStorageWrites { .. } => "MovableStorageWrites",
RuntimeFact::TileThreadgroup { .. } => "TileThreadgroup",
RuntimeFact::ConstexprSampled { .. } => "ConstexprSampled",
RuntimeFact::CubicSampler { .. } => "CubicSampler",
+3 -363
View File
@@ -7,9 +7,7 @@
use std::collections::BTreeSet;
use crate::air::container::Hash256;
use crate::device::requirements::{VkFeature, VkProperty};
use crate::device::DeviceProfile;
use crate::error::{
Attachment, Capability, Error, Feature, InternalError, InternalKind, Unsupported,
};
@@ -62,9 +60,8 @@ pub struct GraphicsState {
/// `VK_SUBPASS_DESCRIPTION_RASTERIZATION_ORDER_ATTACHMENT_COLOR_ACCESS_BIT_EXT` and the
/// pipeline's color blend state with
/// `VK_PIPELINE_COLOR_BLEND_STATE_CREATE_RASTERIZATION_ORDER_ATTACHMENT_ACCESS_BIT_EXT`, and
/// the pipeline's requirements name the feature. A device without the feature but with
/// `fragmentShaderPixelInterlock` takes no input attachment: a fetch there is the interlocked
/// storage form or refused. A device with neither reads them without this flag: the consumer
/// the pipeline's requirements name the feature. A device without it reads them without this
/// flag: the consumer
/// then orders each draw that reads them after the color writes of the earlier draws of its
/// subpass, and each draw that writes a color after the input attachment reads of the earlier
/// ones, by a barrier of the subpass's dependency on itself (by region) between the two, which
@@ -87,10 +84,6 @@ pub struct GraphicsState {
/// its stages are the synthesized vertex and tessellation control stages, then the function's
/// evaluation stage, then the fragment stage.
pub tessellation: Option<TessellationState>,
/// The render pass's fragment imageblock, when the fragment function reads or writes it: the
/// consumer binds the pass's imageblock storage to every draw of the pass
/// (`WriteSource::Imageblock`).
pub fragment_imageblock: Option<FragmentImageblock>,
/// The vertex function (a post-tessellation vertex function included) writes memory
/// (`StageInterface::writes_memory`): each run of the pipeline's vertex stage repeats its
/// side effects. A rate-mapped pass drawn region by region records each draw once per region,
@@ -108,26 +101,6 @@ pub struct GraphicsState {
/// one, and the runtime refuses it.
#[cfg_attr(feature = "serde", serde(default))]
pub writes_viewport_index: bool,
/// The color attachments the fragment function reads, and may write, as storage images
/// inside the ordered pixel interlock (framebuffer fetch on a device without
/// `rasterizationOrderColorAttachmentAccess`): each such attachment's entry of
/// `color_attachments` is `None`, its subpass color reference is `VK_ATTACHMENT_UNUSED`, and
/// the consumer binds a 2D view of the attachment's image as a storage image
/// (`WriteSource::TileAttachment`) in `GENERAL` layout, over the pixels of the render pass; in
/// a pipeline of more than one sample the image has `rasterization_samples` samples, or, where
/// the attachment's `view` is [`StorageAttachmentView::SamplePlanes`], the consumer binds a
/// 2D-array view of a single-sample image of one layer per sample in its place. See
/// [`StorageAttachmentUse`] for the consumer contract.
#[cfg_attr(feature = "serde", serde(default))]
pub storage_attachments: Vec<StorageAttachmentUse>,
/// The fragment function's `[[stencil]]` output is a shader-side stencil over a shadow of
/// the pass's stencil attachment: on a device without `VK_EXT_shader_stencil_export`, the
/// function applies Metal's stencil test and operations itself, inside the ordered pixel
/// interlock. `None` for every other pipeline, and for one whose pass has no stencil
/// attachment (the function then tests nothing, as Metal's output reaches no attachment).
/// See [`ShadowStencilUse`] for the consumer contract.
#[cfg_attr(feature = "serde", serde(default))]
pub shadow_stencil: Option<ShadowStencilUse>,
/// A render pipeline variant that draws its lines as bands of triangles
/// (`VariantKey::line_band`, `pipeline::link::band`): its `topology` is `PATCH_LIST` (never
/// dynamic), its stages the vertex stage, the band's synthesized tessellation control and
@@ -176,9 +149,7 @@ pub struct GraphicsState {
pub fragment_writes_memory: bool,
/// The color attachments the fragment function may write, as a mask: bit `n` for color
/// attachment `n`. Each attachment that a first (`[[color(n)]]`, index 0) output of the
/// function names is set, whether the function writes it through an output variable or, for
/// an attachment it reads in the interlocked storage form, through its storage image. It is
/// decided from the stage's outputs, which come from the AIR's output metadata of the entry its
/// function names is set. It is decided from the stage's outputs, which come from the AIR's output metadata of the entry its
/// function constants specialized, never from names.
///
/// An attachment not set is one the function never writes:
@@ -211,15 +182,6 @@ pub struct GraphicsState {
/// or declares `[[early_fragment_tests]]` does; the consumer then passes no mask.
#[cfg_attr(feature = "serde", serde(default))]
pub sample_mask: Option<u32>,
/// The fragment function reads textures through snapshots (`VariantKey::snapshot_textures`):
/// each draw of the pipeline is drawn twice in its subpass, the texture's attachment in
/// `VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT`, first with every color write mask 0,
/// then with the pipeline's own (`PushHole::SnapshotPhase`), which it sets for every color
/// blend element: `dynamic_states` holds `VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT`. The consumer
/// creates the pipeline with `VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT`. Its
/// requirements name `attachmentFeedbackLoopLayout` and `extendedDynamicState3ColorWriteMask`.
#[cfg_attr(feature = "serde", serde(default))]
pub snapshot_reads: bool,
/// `VkPipelineColorBlendStateCreateInfo::logicOp` with `logicOpEnable`: the descriptor's
/// private `logicOperation`
/// ([`PrivateRenderState::logic_operation`](crate::pipeline::PrivateRenderState::logic_operation)),
@@ -364,11 +326,8 @@ impl GraphicsState {
max_vertex_amplification_count: 1,
declares_layer: false,
tessellation: None,
fragment_imageblock: None,
vertex_writes_memory: false,
writes_viewport_index: false,
storage_attachments: Vec::new(),
shadow_stencil: None,
line_band: None,
writes_point_size: false,
writes_depth: false,
@@ -377,7 +336,6 @@ impl GraphicsState {
fragment_writes_memory: false,
color_outputs: 0,
sample_mask: None,
snapshot_reads: false,
logic_op: None,
}
}
@@ -570,9 +528,6 @@ fn dynamic_state_feature(state: vk::DynamicState) -> Result<Option<VkFeature>, E
// `VK_EXT_extended_dynamic_state2`'s first feature (core in Vulkan 1.3 without one), made
// dynamic only where the profile has it.
D::PRIMITIVE_RESTART_ENABLE => Some(VkFeature::ExtendedDynamicState2),
// `VK_EXT_extended_dynamic_state3`'s color write masks, dynamic only in a pipeline that
// reads through snapshots (`GraphicsState::snapshot_reads`).
D::COLOR_WRITE_MASK_EXT => Some(VkFeature::ExtendedDynamicState3ColorWriteMask),
other => {
return Err(Error::Internal(InternalError::new(
InternalKind::Invariant,
@@ -585,56 +540,6 @@ fn dynamic_state_feature(state: vk::DynamicState) -> Result<Option<VkFeature>, E
})
}
/// How a render pipeline's fragment function reaches the render pass's imageblock.
///
/// Metal keeps a fragment imageblock in tile memory: per pixel, for the whole render pass, its
/// contents undefined when the pass begins, and every pipeline of the pass that declares
/// `[[imageblock_data]]` sees the same bytes at its layout's offsets.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FragmentImageblock {
/// The representation the profile's capabilities chose.
pub mechanism: ImageblockMechanism,
/// The 32-bit words of each pixel's cell the function reaches: the pass's storage needs at
/// least this many, and the largest over the pass's pipelines.
pub words: u32,
/// The fingerprint of the master layout the fragment function's views view: SHA-256 over
/// its data size and the layout's Merkle digest (SHA-256 over each member's offset, size,
/// array length, user key, and nested layout's digest). Equal fingerprints are structurally
/// equal masters. A view of another master of the same `data_size` and `alignment` in the
/// same pass reaches the same bytes at its own offsets, as each layout's words in the storage
/// hold them (measured on an M3 Max and an M4 without Metal's API validation, which stops
/// such a pass); which bytes one of another size or alignment reaches is not read in full, so a
/// consumer refuses such a pass (the translator sees one pipeline at a time and cannot).
pub master: Hash256,
/// The bytes of a cell (`air.imageblock_data_size`).
pub data_size: u32,
/// The alignment Metal states for the fragment function's views (`air.arg_type_align_size`:
/// their master layout's). With `data_size` it gives Metal's `imageblockSampleLength` of the
/// pipeline (measured on an M3 Max): `data_size` plus the bytes its color attachments pack to,
/// rounded up to 8 and then to `alignment`.
pub alignment: u32,
}
/// The representation of a fragment imageblock.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ImageblockMechanism {
/// One coherent `R32Uint` 2D-array storage image per render pass instance: layer `w` holds
/// word `w` of the cell of pixel `(x, y)` at texel `(x, y)`, the pixel's framebuffer
/// coordinate (`FragCoord`). The fragment function reads its input view and writes its
/// output view inside the ordered pixel-interlock critical section
/// (`fragmentShaderPixelInterlock`), which orders overlapping fragments of the pass in
/// primitive order across draws, as Metal's raster order groups do. The consumer creates the
/// image with `STORAGE` usage, an extent covering the pass's render area's offset plus its
/// extent (texel `(x, y)` is framebuffer pixel `(x, y)`, not relative to the area), and at
/// least `words` layers, keeps it in `GENERAL` layout for the whole pass, binds it to every
/// draw of the pass, and draws only pipelines of one `master` in the pass.
StorageImageInterlock,
}
/// One color attachment's format, write mask, and blend state.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -715,271 +620,6 @@ impl BlendState {
}
}
/// A color attachment a render pipeline's fragment function reads, and may write, as a storage
/// image inside the ordered pixel interlock (`GraphicsState::storage_attachments`).
///
/// The draw orders every fragment's read, body, and write of a pixel after the earlier fragments
/// of the pixel in primitive order, across draws and instances of the subpass, as Metal orders
/// framebuffer fetch. The consumer:
///
/// - leaves the attachment out of the color attachments of every subpass a pipeline that names
/// it draws in (its color reference there is `VK_ATTACHMENT_UNUSED`): an image a subpass
/// writes as an attachment is no storage image of the same subpass;
/// - binds the image `view` names, in `format` with the identity mapping, as the plan's
/// `WriteSource::TileAttachment { color_index, format, view }` (which carries the same `view`),
/// in `GENERAL` layout, texel `(x, y)` being framebuffer pixel `(x, y)` (so the image covers
/// the render area's offset plus its extent):
/// - [`StorageAttachmentView::Attachment`]: a 2D view of the attachment's own image, of the
/// render pass's layer and level, the image created with `STORAGE` usage (beside its own).
/// In a pipeline of more than one sample that image is the pass's multisampled attachment,
/// of the pipeline's `GraphicsState::rasterization_samples`, the one sample count of the
/// pipeline and its storage images, and the fragment function runs once per covered sample,
/// reading and writing its own sample; the pipeline's requirements name
/// `shaderStorageImageMultisample` and the count's `storageImageSampleCounts` bit;
/// - [`StorageAttachmentView::SamplePlanes`] `{ layers }` (a pipeline of more than one sample
/// on a device without multisampled storage images): a 2D-array view
/// (`VK_IMAGE_VIEW_TYPE_2D_ARRAY`) of all `layers` layers of the attachment's sample planes,
/// a single-sample 2D-array image the consumer keeps beside the attachment, of `format`, with
/// `STORAGE` usage and `layers` (the pipeline's `rasterization_samples`) layers, never a 2D
/// view and never the multisampled attachment itself. The fragment function runs once per
/// covered sample and reads and writes sample `s` of pixel `(x, y)` at texel `(x, y)` of
/// layer `s`, so the planes need no multisampled storage image and no
/// `storageImageSampleCounts` bit. The consumer fills layer `s` from sample `s` of the
/// attachment's image before the draws (no copy changes a sample count, so a per-sample
/// shader read does), and after them writes layer `s` back into sample `s` (a sample-rate
/// pass that writes only its own sample), or, where the pass resolves the attachment or the
/// attachment is memoryless, resolves from the planes as Metal resolves the samples;
/// - makes earlier writes of the image visible to the fragment shader's storage reads before
/// the draws (a color attachment write of an earlier subpass or pass, a transfer, a load
/// operation), and the fragment shader's storage writes visible to later uses after them.
///
/// A pass of more than one layer, and an amplified draw, are not implemented: the binder refuses
/// them.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct StorageAttachmentUse {
pub color_index: u32,
/// The attachment's format, which the storage view takes.
pub format: vk::Format,
/// The fragment function writes the attachment (otherwise it only reads it).
pub writes: bool,
/// The function declares the storage image without a format (`Unknown`), so the view's
/// format ([`view_format`](Self::view_format)) supports storage reads (and, when `writes`,
/// writes) without one (`VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT` and its write
/// twin); otherwise the declaration names the view's format's SPIR-V image format.
pub formatless: bool,
/// The image the consumer binds and how it views it: the attachment's own image, or its
/// sample planes (see the type's docs). The plan's `WriteSource::TileAttachment` carries the
/// same value.
#[cfg_attr(feature = "serde", serde(default))]
pub view: StorageAttachmentView,
/// Where `Some`, the storage view is in this format, not in `format`, which stays the
/// attachment's own ([`view_alias_of`](Self::view_alias_of) decides it from `format` and the
/// device):
///
/// - an 8-bit sRGB attachment's unsigned-integer format of its texel size (`R32_UINT` for a
/// 4-byte texel): its format has no storage access, and the function unpacks the texels in
/// `format`'s byte order and decodes and encodes them itself, by Metal's measured
/// conversions;
/// - a BGRA-order attachment's RGBA-order twin (`R8G8B8A8_UNORM` for `B8G8R8A8_UNORM`,
/// `A2B10G10R10_UNORM_PACK32` for `A2R10G10B10_UNORM_PACK32`) on a device that neither
/// reads nor writes `format` without a format (SPIR-V names no image format for it): the
/// function exchanges red and blue on every read and write, and the device converts each
/// channel as it converts `format`'s.
///
/// The consumer binds such a view of an image made with `VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT`
/// (and `VK_IMAGE_CREATE_EXTENDED_USAGE_BIT` where `format` has no storage access), whose
/// `VkImageFormatListCreateInfo` lists `format` and this format, with `STORAGE` usage (the
/// sample planes of [`StorageAttachmentView::SamplePlanes`] in this format); its draws that
/// do not fetch render the image through a view in `format`. `None` for any other format, and
/// on a device that accesses a BGRA-order format without one: the view is in `format`.
#[cfg_attr(feature = "serde", serde(default, alias = "uint_view"))]
pub view_alias: Option<vk::Format>,
/// The channels the function's write keeps from the texel it reads first, by the pipeline's
/// write mask: empty where it does not write the attachment or the mask covers every channel of
/// the format, all four where it covers none of them (the write stores nothing), else those of
/// the format the mask leaves out. One module serves every write mask that keeps some of a
/// format's channels (a blended 8-bit unorm attachment with alpha: each of alpha alone, one
/// color channel, and more): the binder writes these into each draw's push bytes, where the
/// function reads them. Nothing for the consumer to do.
#[cfg_attr(feature = "serde", serde(default))]
pub kept: vk::ColorComponentFlags,
}
/// The image a storage view of a color attachment binds, and how it is viewed
/// (`StorageAttachmentUse::view`, `WriteSource::TileAttachment`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum StorageAttachmentView {
/// A 2D view (`VK_IMAGE_VIEW_TYPE_2D`) of the attachment's own image, of the pass's layer
/// and level: single-sample in a pass of one sample, of the pass's samples in a multisampled
/// pass.
#[default]
Attachment,
/// A 2D-array view (`VK_IMAGE_VIEW_TYPE_2D_ARRAY`) of every layer of the attachment's sample
/// planes: a single-sample 2D-array image of `layers` layers (the pipeline's
/// `rasterization_samples`), layer `s` holding sample `s` of each pixel, which the consumer
/// fills from the multisampled attachment before the draws and writes back (or resolves)
/// after them.
SamplePlanes { layers: u32 },
}
impl StorageAttachmentUse {
/// Color attachment `color_index` of `format` bound as a storage image through `view`, written
/// where `writes`, declared without a format where `formatless`.
pub fn new(
color_index: u32,
format: vk::Format,
writes: bool,
formatless: bool,
view: StorageAttachmentView,
) -> StorageAttachmentUse {
StorageAttachmentUse {
color_index,
format,
writes,
formatless,
view,
view_alias: None,
kept: vk::ColorComponentFlags::empty(),
}
}
/// The use whose write keeps `kept` from the texel ([`kept`](Self::kept)).
pub fn with_kept(self, kept: vk::ColorComponentFlags) -> StorageAttachmentUse {
StorageAttachmentUse { kept, ..self }
}
/// The use with its storage view in `view_alias` ([`view_alias`](Self::view_alias)).
pub fn with_view_alias(self, view_alias: vk::Format) -> StorageAttachmentUse {
StorageAttachmentUse {
view_alias: Some(view_alias),
..self
}
}
/// The format of the storage view: [`view_alias`](Self::view_alias) where it is set, else
/// `format`.
pub fn view_format(&self) -> vk::Format {
self.view_alias.unwrap_or(self.format)
}
/// The format other than `format` a fetching draw views a color attachment of `format` in,
/// where a fragment function reads it in the storage form on `profile`
/// ([`view_alias`](Self::view_alias)): `R32_UINT` for `B8G8R8A8_SRGB` and `R8G8B8A8_SRGB`,
/// `R16_UINT` for `R8G8_SRGB` and `R8_UINT` for `R8_SRGB`, on every device; `R8G8B8A8_UNORM`
/// for `B8G8R8A8_UNORM` and `A2B10G10R10_UNORM_PACK32` for `A2R10G10B10_UNORM_PACK32` where
/// the device neither reads nor writes the attachment's format without a format, and stores
/// the twin and declares it (without a format, or by its SPIR-V image format,
/// `shaderStorageImageExtendedFormats` for an extended one); `None` for any other format and
/// device. The compile layer and a consumer that makes an attachment's image before it knows
/// the pipeline (a memoryless attachment's backing, a render target's free usage) both take
/// it from here, so the image is made mutable to the view the pipeline binds. The compile
/// layer sets an sRGB view only where it builds the form (today the four-byte formats).
pub fn view_alias_of(format: vk::Format, profile: &DeviceProfile) -> Option<vk::Format> {
crate::metal::format::fetch_view_alias(format, profile)
}
/// The format usages the consumer's image and view need: `StorageImage` of the view's
/// format, and the without-format accesses of a formatless declaration.
pub(crate) fn format_usages(
&self,
) -> Vec<(vk::Format, crate::device::requirements::FormatUsage)> {
use crate::device::requirements::FormatUsage as U;
let view = self.view_format();
let mut out = vec![(view, U::StorageImage)];
if self.formatless {
out.push((view, U::StorageImageReadWithoutFormat));
if self.writes {
out.push((view, U::StorageImageWriteWithoutFormat));
}
}
out
}
}
/// A render pipeline whose fragment function's `[[stencil]]` output is a shader-side stencil
/// (`GraphicsState::shadow_stencil`).
///
/// Metal tests and writes the stencil with the function's output as the reference of both faces
/// (its low 8 bits): `(r & readMask) cmp (s & readMask)`, then `s' = (s & ~writeMask) |
/// (op(s, r) & writeMask)`, before the depth test, per sample in primitive order. Without
/// `VK_EXT_shader_stencil_export` no fixed-function state takes a per-fragment reference, so the
/// function does it: inside the ordered pixel interlock it reads the pixel's value from a shadow
/// of the stencil, applies the face's test and operation from the encoder's state
/// (`BindState::depth_stencil`, written as `PushField::ShadowStencilState`), writes the shadow,
/// and kills a fragment that fails. A discarded fragment changes nothing. The depth test stays
/// fixed-function, after the function. In a pipeline of more than one sample the shadow holds
/// each sample, the function tests each sample of its coverage, and its `SampleMask` output keeps
/// the samples that pass.
///
/// The consumer, for each draw with such a pipeline:
///
/// - creates the pipeline with the stencil test disabled (`stencilTestEnable` false, or
/// `vkCmdSetStencilTestEnable(false)` where the pipeline makes it dynamic): the function is the
/// test, and the attachment's stencil is not written during the draw;
/// - keeps the shadow: a 2D image of `format` and `samples` samples (the pipeline's) with
/// `STORAGE` and transfer usage, of the stencil attachment's extent, whose texel `(x, y)` (each
/// sample) is framebuffer pixel `(x, y)` (that sample), bound in `GENERAL` layout as the plan's
/// `WriteSource::ShadowStencil`;
/// - copies the stencil into the shadow before the draw and back after it, outside the render
/// pass: of one sample, `vkCmdCopyImageToBuffer` of the attachment's stencil aspect (one byte
/// per texel) then `vkCmdCopyBufferToImage` into the shadow, and the reverse afterwards; of more,
/// `vkCmdCopyImage` between the stencil aspect and the shadow, both ways, which
/// `VK_KHR_maintenance8`'s depth/stencil-to-color copies allow (no buffer copy takes a
/// multisampled image; the pipeline requires `maintenance8` then). A render pass instance
/// that holds such a draw is therefore split around it: end the pass, copy in, begin it again
/// loading every attachment, draw, end it, copy out, and begin it again. Consecutive such draws
/// share one copy in and one copy out while nothing else writes the stencil between them. Each
/// copy needs its barriers: attachment writes before the copy out of the stencil, the copy into
/// the shadow before the fragment shader's storage reads and writes, those before the copy
/// back, and that copy before the next attachment access;
/// - sets `BindState::depth_stencil` to the encoder's `MTLDepthStencilDescriptor` for the draw.
/// The binder refuses a state whose stencil write could depend on the depth test, typed as
/// needing the extension: a depth attachment, a depth comparison other than `Always`, and a
/// face whose depth-failure operation differs from its pass operation. The stencil references
/// are unused (the function's output is the reference of both faces), and the front face is the
/// pipeline's, from the encoder's winding.
///
/// The split costs a render pass instance per such draw (or run of draws). Synchronizing the
/// shadow inside the pass (an input-attachment read of the stencil under a feedback-loop layout,
/// and an in-pass write-back) would avoid it; that is a possible later optimisation, not part of
/// this contract.
///
/// An amplified draw and a pass of more than one layer are not implemented: the binder refuses
/// them. Alpha to coverage, which changes a fragment's samples before Metal's stencil test, is
/// refused at link as needing the extension.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShadowStencilUse {
/// The shadow's format, `R8_UINT`.
pub format: vk::Format,
/// The function declares the shadow without a format (`Unknown`), so the format supports
/// storage reads and writes without one (`VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT`
/// and its write twin); otherwise the declaration names `R8ui`.
pub formatless: bool,
/// The shadow's samples: the pipeline's rasterization samples.
pub samples: u32,
}
impl ShadowStencilUse {
/// The format usages the consumer's shadow image and view need: `StorageImage`, and the
/// without-format accesses of a formatless declaration.
pub(crate) fn format_usages(
&self,
) -> Vec<(vk::Format, crate::device::requirements::FormatUsage)> {
use crate::device::requirements::FormatUsage as U;
let mut out = vec![(self.format, U::StorageImage)];
if self.formatless {
out.push((self.format, U::StorageImageReadWithoutFormat));
out.push((self.format, U::StorageImageWriteWithoutFormat));
}
out
}
}
/// A framebuffer-fetch input: color attachment `color_index` read as input attachment
/// `input_attachment_index`. The consumer's render pass provides the self-dependency (or
/// `dynamicRenderingLocalRead` mapping) that the contract names, and, without
+2 -63
View File
@@ -351,8 +351,8 @@ pub struct StageInterface {
/// a buffer or a texture, or updates one atomically (`spirv::requirements::writes_memory`).
/// Metal runs a multisampled fragment function with such a side effect once per covered
/// sample. The `ExecutionStatus` buffer's words, which the resident-miss count updates, are not
/// the function's, nor a color's interlocked storage form's or `half` shadow's, which carry
/// Metal's color attachment write.
/// the function's, nor a tile function's color attachment's, which carry Metal's color
/// attachment write.
#[cfg_attr(feature = "serde", serde(default))]
pub writes_memory: bool,
/// An object or mesh function's payload arena's bytes (`memory::arena::payload_bytes` of its
@@ -430,22 +430,6 @@ pub struct StageInterface {
/// its helper invocations, clamped as the coordinate is. Empty for every other stage.
#[cfg_attr(feature = "serde", serde(default))]
pub own_pixel_textures: Vec<u32>,
/// Those of `own_pixel_textures` a draw can read through a snapshot an earlier draw of the
/// same primitives took, sorted (`spirv::requirements::snapshot_textures`): no value a fetch
/// of the slot returns reaches, directly or through a call, a derivative, a sample, a quad or
/// subgroup operation, a branch, an integer divisor, a dynamic vector index, or a store other
/// than to a `Function`, `Private` or `Output` variable, so a helper invocation's value of it
/// reaches no fragment's result and gives it no undefined behavior; and the function writes no
/// memory and holds no interlock. Its variant (`LoweringInputs::snapshot_textures`) reads the slot through
/// the snapshot. Empty for every other stage.
#[cfg_attr(feature = "serde", serde(default))]
pub snapshot_textures: Vec<u32>,
/// Why each slot of `own_pixel_textures` that `snapshot_textures` leaves out is left out:
/// every [`SnapshotRefusal`] that holds for it, sorted by slot and then by refusal, so a slot
/// may appear more than once. Empty for every other stage, and for a function compiled to read
/// slots through snapshots (`LoweringInputs::snapshot_textures`), which judges none.
#[cfg_attr(feature = "serde", serde(default))]
pub snapshot_refusals: Vec<(u32, SnapshotRefusal)>,
/// The levels of its bound view that each texture slot's reads reach, one entry a slot, sorted
/// by slot ([`LevelReads`]): what a runtime needs to tell whether a slot whose texture presents
/// a color attachment of the draw's render pass instance at some level reads that level.
@@ -478,51 +462,6 @@ pub struct SamplerArray {
pub samplers: Vec<crate::pipeline::sym::SamplerRef>,
}
/// What leaves an own-pixel texture slot of a fragment function out of the slots a draw can read
/// through a snapshot an earlier draw of the same primitives took
/// (`StageInterface::snapshot_refusals`, `StageModule::snapshot_refusals`). A helper invocation
/// reads a constant from the snapshot, so the slot is left out where a helper's value of it could
/// reach another invocation's result, give it undefined behavior, or where the snapshot cannot be
/// made beside the function. The first eight say where a value that a fetch of the slot reaches,
/// through any instruction, phi, call, or `Function`, `Private` or `Output` variable, is used.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SnapshotRefusal {
/// It decides a conditional branch or a switch, but for a selection whose arms leave through
/// its merge alone and hold no derivative, implicit-level sample or level-of-detail query,
/// subgroup or quad operation, loop, or operand undefined at a value that is not a constant,
/// nor call a function that does (a helper may take either of those arms).
Branch,
/// It is an operand of a derivative.
Derivative,
/// It is an operand of a sample, a gather or a level-of-detail query of any image.
Sample,
/// It is an operand of a subgroup or quad operation.
GroupOperation,
/// It is stored to a storage class other than `Function`, `Private` or `Output`, or through
/// a function parameter's pointer.
Store,
/// It is an operand of an atomic.
Atomic,
/// It is an operand of an image write or a texel pointer.
ImageWrite,
/// It is an operand an instruction's behavior is undefined for at some value: an integer
/// divisor, the dividend of a signed division or remainder whose divisor may be `-1`, or a
/// dynamic vector component index.
UndefinedOperand,
/// The function writes memory (`StageInterface::writes_memory`).
WritesMemory,
/// The module holds a fragment interlock critical section.
Interlock,
/// The module has a `Coherent` resource or uses the Vulkan memory model.
Coherent,
/// Anything else: the slot's index is 128 or more, its values take more than 16 passes over
/// the module to settle, or one is an operand of a ray query, a mesh output count or a call
/// whose callee's parameters it does not match, or the entry's returned value.
Other,
}
/// The levels of its bound view that a texture slot's reads reach, each counted from the view's
/// first level (`StageInterface::level_reads`, `StageModule::level_reads`), as the module's
/// instructions decide them (`spirv::requirements::level_reads`, structural). A sample's level is
@@ -141,9 +141,6 @@ pub enum BindingSource {
stage: Stage,
sampler: CombinedSampler,
},
/// The snapshot of the texture the draw binds at this fragment texture slot
/// (`ResourceKind::SnapshotTexels`), bound as a storage image.
SnapshotTexels(u32),
/// A constexpr sampler array of `stage` (`ResourceKind::SamplerArray`) that samples set-1
/// heap images, made for the use with comparison or without (`compare`) of an integer texture
/// or not (`integer`): its samplers are the binding's `immutable_samplers`, which take no
+8 -27
View File
@@ -40,7 +40,7 @@
//! descriptors; otherwise the same layout is used as a pooled set.
//! - **Render state** ([`vertex`], [`graphics`]): `VertexInputState` and `GraphicsState` from the
//! descriptor, checked against the vertex stage's compiled fetch projection, with the fragment
//! stage's imageblock ([`imageblock`]) and interlocked framebuffer fetch ([`fetch`]), and the
//! stage's framebuffer fetch over input attachments ([`fetch`]), and the
//! precision notes of the formats fixed-function vertex input converts for the vertex stage
//! (`vertex::fixed_function_notes`), which the module, shared by every such format, cannot
//! record, with the measured properties a conversion relies on in place of a note. A mesh
@@ -52,9 +52,7 @@ pub mod band;
pub mod contract;
pub mod fetch;
pub mod graphics;
pub mod imageblock;
pub mod mesh;
pub mod stencil;
pub mod tessellation;
pub mod varyings;
pub mod vertex;
@@ -517,15 +515,6 @@ fn render_state(
ts: Option<crate::pipeline::graphics::TessellationState>,
p: &DeviceProfile,
) -> Result<GraphicsState, Error> {
// The imageblock's refusals first: a multisampled imageblock is the specific reason where
// its storage writes would also refuse the sample invocations.
let ib = imageblock::fragment_imageblock(r, fragment)?;
// The interlocked fetch's form against this pipeline's state, before the sample invocations
// its storage writes would also refuse.
let storage = fetch::storage_attachments(r, fragment, p)?;
// The shader-side stencil against this pipeline's state, before the sample invocations its
// shadow writes would also refuse.
let shadow = stencil::shadow_stencil(r, fragment, p)?;
// The extended-range blends the fragment computes over input attachments, against this
// pipeline's attachments.
let input_blends = fetch::input_blends(r, fragment, p)?;
@@ -551,22 +540,16 @@ fn render_state(
(r.alpha_to_coverage, r.texture_write_rounding_mode),
p,
)?;
gs.fragment_imageblock = ib;
gs.color_outputs = color_outputs(fs, &storage)?;
gs.storage_attachments = storage;
gs.shadow_stencil = shadow;
gs.color_outputs = color_outputs(fs)?;
Ok(gs)
}
/// The color attachments fragment stage `fs` writes (`GraphicsState::color_outputs`), bit `n`
/// for attachment `n`: those a first (index 0) color output of its function names, and those it
/// writes in the interlocked storage form (`storage`). An index past the mask is no output link
/// admits (`maxFragmentOutputAttachments` and Metal's eight colors are below it).
fn color_outputs(
fs: Option<&StageInterface>,
storage: &[crate::pipeline::graphics::StorageAttachmentUse],
) -> Result<u32, Error> {
let outputs = fs
/// for attachment `n`: those a first (index 0) color output of its function names. An index past
/// the mask is no output link admits (`maxFragmentOutputAttachments` and Metal's eight colors are
/// below it).
fn color_outputs(fs: Option<&StageInterface>) -> Result<u32, Error> {
let mut outputs = fs
.into_iter()
.flat_map(|f| &f.io.outputs)
.filter_map(|o| match o.role {
@@ -576,8 +559,7 @@ fn color_outputs(
} => Some(attachment),
_ => None,
});
let stored = storage.iter().filter(|s| s.writes).map(|s| s.color_index);
outputs.chain(stored).try_fold(0u32, |mask, color| {
outputs.try_fold(0u32, |mask, color| {
1u32.checked_shl(color)
.map(|bit| mask | bit)
.ok_or_else(|| {
@@ -719,7 +701,6 @@ fn binding_source(slot: ResourceSlot) -> BindingSource {
stage: slot.stage,
sampler: CombinedSampler::from_heap_index(sampler, slot.index),
},
ResourceKind::SnapshotTexels(texture) => BindingSource::SnapshotTexels(texture),
ResourceKind::YCbCrPlanes(_) => BindingSource::YCbCrPlanes(metal(SlotClass::Texture)),
ResourceKind::SamplerArray { compare, integer } => BindingSource::SamplerArray {
stage: slot.stage,
@@ -384,8 +384,6 @@ impl LineBand {
rounded_colors: Vec::new(),
specialized_notes: Vec::new(),
own_pixel_textures: Vec::new(),
snapshot_textures: Vec::new(),
snapshot_refusals: Vec::new(),
level_reads: Vec::new(),
private_bytes: 0,
stats,
+4 -153
View File
@@ -1,28 +1,4 @@
//! A render pipeline's interlocked framebuffer fetch: `GraphicsState::storage_attachments` from the
//! fragment stage's `RuntimeFact::InterlockedFramebufferFetch`.
//!
//! On a device that orders framebuffer fetch only through the ordered pixel interlock, the fragment
//! function reads each color attachment, and writes it, as a storage image inside the interlock
//! where the pipeline's state lets that form be exact (`lower::fragment`'s `fetch`). The function
//! compiled under its pipeline's state (`LoweringInputs::framebuffer_fetch`); link decides the form
//! again from the state of the pipeline it links into, with the same rule, and a stage whose form,
//! attachment format, kept channels (a write mask short of the format's channels), or in-shader
//! blend (an extended-range or 16-bit float attachment's) that state would not choose (a write
//! before a depth or stencil attachment's tests only where the function states
//! `RuntimeFact::TestedStorageWrites`, which each draw's plan checks) was compiled for another
//! pipeline: `NeedsInput(FramebufferFetch)`. A write mask that keeps some of a format's channels
//! compiles as its class (`FramebufferFetchInputs::of`), so the comparison holds across the masks
//! of a class, and the pipeline's own kept channels go in `StorageAttachmentUse::kept`, which the
//! binder writes into each draw's push bytes. An attachment the function reads in the storage form
//! is no color attachment of the subpass (`graphics_state` gives it no state), and the consumer
//! binds it as `GraphicsState::storage_attachments` states.
//!
//! In a multisampled pipeline the form is per sample. Where the device has multisampled storage
//! images, the image has the pipeline's samples, so the device's `storageImageSampleCounts` must
//! hold that count (`VkProperty::StorageImageSampleCount`), as for the shader-side stencil's
//! shadow; otherwise the fetch is refused naming it. Elsewhere the image holds the samples as
//! planes (`StorageAttachmentView::SamplePlanes`), a single-sample image of one layer per sample,
//! which needs no sample count of storage images.
//! A render pipeline's framebuffer fetch computed over input attachments.
//!
//! On a device that orders framebuffer fetch through rasterization-order input attachments, the
//! function computes an extended-range attachment's blend over its input attachment
@@ -43,142 +19,17 @@
use std::collections::BTreeMap;
use crate::device::requirements::VkProperty;
use crate::device::DeviceProfile;
use crate::error::{
Capability, Error, Feature, InternalError, InternalKind, RuntimeInput, Unsupported,
};
use crate::error::{Error, InternalError, InternalKind, RuntimeInput};
use crate::library::FunctionArtifact;
use crate::lower::fragment::{
inputs_order, interlock_orders, kept_channels, storage_form, ColorUse, StorageSamples,
};
use crate::lower::fragment::{inputs_order, kept_channels};
use crate::metal::format::ExtendedRange;
use crate::metal::state::color_write_mask;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::graphics::{StorageAttachmentUse, StorageAttachmentView};
use crate::pipeline::link::RenderLinkInputs;
use crate::pipeline::lower_inputs::{BlendEquation, FramebufferFetchInputs};
use crate::pipeline::lower_inputs::BlendEquation;
use crate::pipeline::stage_io::IoRole;
/// The attachments the fragment stage `fragment` of render inputs `r` reads in the storage form
/// on `p`, by color index (see the module docs).
pub fn storage_attachments(
r: &RenderLinkInputs,
fragment: Option<&FunctionArtifact>,
p: &DeviceProfile,
) -> Result<Vec<StorageAttachmentUse>, Error> {
let Some(fragment) = fragment else {
return Ok(Vec::new());
};
let reads: Vec<(
u32,
crate::vk::Format,
bool,
bool,
crate::vk::ColorComponentFlags,
(Option<crate::pipeline::lower_inputs::BlendEquation>, bool),
)> = fragment
.facts
.iter()
.filter_map(|fact| match *fact {
RuntimeFact::InterlockedFramebufferFetch {
color,
format,
writes,
early_tests,
kept,
blend,
rounded,
} => Some((color, format, writes, early_tests, kept, (blend, rounded))),
_ => None,
})
.collect();
if reads.is_empty() {
return Ok(Vec::new());
}
if !interlock_orders(p) {
return Err(Error::Internal(InternalError::new(
InternalKind::Invariant,
"an interlocked framebuffer fetch on a device that orders fetch otherwise",
)));
}
let inputs = FramebufferFetchInputs::of(
reads.iter().map(|&(color, ..)| color),
&r.color_attachments,
r.depth_format.is_some() || r.stencil_format.is_some(),
r.alpha_to_coverage,
r.max_vertex_amplification_count,
);
let multisampled = r.raster_sample_count > 1 && r.rasterization_enabled;
// A write before the tests, which each draw's plan checks.
let draw_tested = fragment.facts.iter().any(|f| {
matches!(
f,
RuntimeFact::TestedStorageWrites {
early_tests: false,
..
}
)
});
let mut out = Vec::with_capacity(reads.len());
let mut multisampled_image = false;
for (color, format, writes, early_tests, kept, (blend, rounded)) in reads {
let math = match rounded {
true => crate::lower::arith::extended_range::blend::BlendMath::Rounded,
false => crate::lower::arith::extended_range::blend::BlendMath::Fast,
};
let use_ = ColorUse {
writes,
early_tests,
draw_tested,
math,
logic_op: fragment.interface.io.logic_operation,
};
match storage_form(color, &inputs, multisampled, use_, p)? {
Ok(view) if view.format == format && view.kept == kept && view.blend == blend => {
multisampled_image |= view.samples == StorageSamples::Multisampled;
let view_of = match view.samples {
StorageSamples::One | StorageSamples::Multisampled => {
StorageAttachmentView::Attachment
}
StorageSamples::Planes => StorageAttachmentView::SamplePlanes {
layers: r.raster_sample_count,
},
};
// The pipeline's own kept channels, not the class the function compiled under.
let kept = match r.color_attachments.get(color as usize).copied().flatten() {
Some(a) => {
color_write_mask(kept_channels(a.pixel_format, a.write_mask, writes))?
}
None => return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)),
};
out.push(StorageAttachmentUse {
color_index: color,
format,
writes,
formatless: view.formatless(),
view: view_of,
view_alias: view.uint_view.or(view.rgba_view),
kept,
});
}
_ => return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)),
}
}
// The per-sample form's multisampled image has the pipeline's samples.
if multisampled_image {
let property = VkProperty::StorageImageSampleCount(r.raster_sample_count);
if !p.fields().enabled.properties.contains(&property) {
return Err(Unsupported::needs(
Feature::FramebufferFetch,
Capability::Property(property),
)
.into());
}
}
Ok(out)
}
/// The extended-range attachments whose blend fragment stage `fragment` computes over their
/// input attachments (`RuntimeFact::ExtendedRangeInputBlend`), or whose codes it merges there
/// (`RuntimeFact::WordInputMerge` of such an attachment), and the attachments held with their
@@ -51,21 +51,18 @@
//! scissor, depth bias, blend constants, and the stencil reference and masks; with extended
//! dynamic state also cull mode, front face, topology, the depth/stencil test state, and the
//! vertex strides of `PerBind` layouts.
//! - **Storage attachments**: an attachment the fragment stage reads in the interlocked storage
//! form (`ResourceKind::TileAttachment`) has no color attachment state: the subpass leaves it
//! out, and `link::fetch` states how the consumer binds it.
//! - **Input attachments**: one per framebuffer-fetch binding of the fragment stage. Metal orders
//! each fetch after the earlier fragments of the draw that cover the pixel; Vulkan does only
//! under rasterization-order attachment access, so a pipeline with input attachments on a profile
//! with `rasterizationOrderColorAttachmentAccess` states `rasterization_order_attachment_access`
//! (and the compiled pipeline requires the feature). Without the feature a fragment stage reads
//! an input attachment only on a device without the pixel interlock either
//! (`lower::fragment::color`), whose consumer orders the draws by barriers alone. In a
//! an input attachment ordered between draws alone (`lower::fragment::color`), whose consumer
//! orders the draws by barriers. In a
//! multisampled pipeline
//! (`rasterSampleCount` above 1) Metal runs a function that reads a color attachment once per
//! covered sample, each invocation reading its own sample (measured), so the stage, compiled for
//! the pipeline (`LoweringInputs::multisampled`), reads a multisampled `SubpassData` image (or,
//! in the storage form, a multisampled storage image) at its `SampleId`, whose input runs it once
//! the pipeline (`LoweringInputs::multisampled`), reads a multisampled `SubpassData` image at
//! its `SampleId`, whose input runs it once
//! per covered sample: it is a per-sample function under the sample invocations below. A fetching
//! stage compiled for the other kind of pipeline (one sample against more, or the reverse)
//! declares an image of the wrong sample count: `NeedsInput(Multisampled)`. A color input the
@@ -357,16 +354,6 @@ pub fn graphics_state(
};
let written = colors(false);
let declared = colors(true);
// An attachment the function reads in the interlocked storage form is no color attachment of
// the subpass (`link::fetch`).
let storage: BTreeSet<u32> = fs
.into_iter()
.flat_map(|f| &f.descriptors)
.filter_map(|d| match d.slot.kind {
ResourceKind::TileAttachment(color) => Some(color),
_ => None,
})
.collect();
// A blend into a bfloat attachment is Metal's pipeline error, whatever the fragment function
// writes there and whatever the mask: its pipeline validation asserts that the format is not
// blendable (an Apple M3 Max under macOS 27.0.1, with and without the validation layer, with
@@ -387,7 +374,6 @@ pub fn graphics_state(
for (index, a) in r.color_attachments.iter().take(used as usize).enumerate() {
color_attachments.push(match a {
None => None,
Some(_) if storage.contains(&(index as u32)) => None,
Some(a) => {
let state = || -> Result<ColorAttachmentState, Error> {
// A word attachment renders through the view of its word, which the function
@@ -499,8 +485,8 @@ pub fn graphics_state(
}
// A mask of some of the codes one word holds, which a stage compiled for
// this pipeline merges where the device orders fetch (one that reaches here
// was compiled for another): on a device that orders it in neither form,
// the orderings the merge needs.
// was compiled for another): on a device that does not, the ordering the
// merge needs.
(Some(form), None) => {
extended_write_mask(form, descriptor_mask).map_err(|e| {
let unordered = crate::lower::fragment::fetch::fetch_unordered(p);
@@ -526,9 +512,9 @@ pub fn graphics_state(
(false, false) => blend_factors(a, p)?,
(false, true) if alpha_red => alpha_in_red_blend(a, p)?,
// A blend no Vulkan state on the rotated image gives, which a stage
// compiled for this pipeline computes itself, in the storage form (no
// color attachment here) or over the input attachment (above): one that
// does not was compiled for another pipeline. Unwritten, it writes nothing.
// compiled for this pipeline computes itself over the input attachment
// (above): one that does not was compiled for another pipeline. Unwritten,
// it writes nothing.
(false, true) if color_writes::shader_rotated_blend(a, p) => {
match written_here {
true => {
@@ -537,8 +523,7 @@ pub fn graphics_state(
false => None,
}
}
// Where the device orders fetch in neither form, the orderings that
// blend needs.
// Where the device does not order fetch, the ordering that blend needs.
(false, true) if color_writes::rotated_blend_in_shader(a, p) => {
return Err(
crate::lower::fragment::fetch::unordered_extended_fetch().into()
@@ -659,12 +644,12 @@ pub fn graphics_state(
}
let textured = textured_fetches(r, fs)?;
let rasterization_samples = samples(r.raster_sample_count)?;
// A fetched attachment is read (and, in the storage form, written) at the invocation's own
// A fetched attachment is read at the invocation's own
// sample by a stage compiled for a multisampled pipeline, and at the pixel by one compiled
// for one sample (see the module docs): a stage compiled for the other kind declares an image
// of the wrong sample count.
if let Some(fs) = fs {
let fetches = !input_attachments.is_empty() || !storage.is_empty() || textured;
let fetches = !input_attachments.is_empty() || textured;
if fetches && fs.io.multisampled != (r.raster_sample_count > 1) {
return Err(Error::NeedsInput(RuntimeInput::Multisampled));
}
@@ -719,15 +704,6 @@ pub fn graphics_state(
dynamic_states.push(D::VERTEX_INPUT_BINDING_STRIDE);
}
}
// A fragment stage that binds a snapshot reads through it, drawn twice with its color write
// masks as dynamic state (`GraphicsState::snapshot_reads`).
let snapshot_reads = fs
.into_iter()
.flat_map(|f| &f.descriptors)
.any(|d| matches!(d.slot.kind, ResourceKind::SnapshotTexels(_)));
if snapshot_reads {
dynamic_states.push(D::COLOR_WRITE_MASK_EXT);
}
let state = GraphicsState {
topology: match tessellation {
Some(_) => vk::PrimitiveTopology::PATCH_LIST,
@@ -748,11 +724,6 @@ pub fn graphics_state(
max_vertex_amplification_count,
declares_layer,
tessellation,
// The fragment stage's facts decide it (`link::imageblock`).
fragment_imageblock: None,
// The fragment stage's facts decide them (`link::fetch`).
storage_attachments: Vec::new(),
shadow_stencil: None,
vertex_writes_memory: vs.writes_memory,
// Stored as the builtin or (on a device with one viewport) nowhere: the raw varying is
// written in both.
@@ -774,10 +745,9 @@ pub fn graphics_state(
reads_barycentric_coord: fs.is_some_and(|fs| reads_barycentric_coord(&fs.io)),
reads_primitive_id: fs.is_some_and(|fs| reads_primitive_id(&fs.io)),
fragment_writes_memory: fs.is_some_and(|fs| fs.writes_memory),
// The storage form's writes join the outputs' once `link::fetch` decided them.
// The outputs' writes, once the color attachments are decided.
color_outputs: 0,
sample_mask: None,
snapshot_reads,
// The pipeline's private logic operation, once compile decided it
// (`private_state::logic_operation`).
logic_op: None,
@@ -1072,12 +1042,11 @@ fn uniform_blend(
/// (`BGR10_XR`'s word, `RGB10A2Unorm_sRGB`'s, the two-plane forms' color word) is
/// `NotImplemented(Format)` here: no mask of the raw components keeps one code of a word and
/// writes another. A stage that writes `BGR10_XR` or a two-plane form so merges the codes
/// (`color_writes::merged_extended`): in the interlocked storage form, which leaves the attachment
/// out of the subpass, where the device orders fetch through the pixel interlock, and over the
/// input attachment, whose write the caller makes of every raw component, where it orders fetch
/// through rasterization-order input attachments, so a stage that reaches here so was compiled
/// for another pipeline (the caller answers `NeedsInput(FramebufferFetch)`); on a device that
/// orders it in neither form, the caller names the orderings the merge needs. A bfloat form's channels
/// (`color_writes::merged_extended`) over the input attachment, whose write the caller makes of
/// every raw component, where the device orders fetch through rasterization-order input
/// attachments, so a stage that reaches here so was compiled for another pipeline (the caller
/// answers `NeedsInput(FramebufferFetch)`); on a device that does not order it so, the caller names
/// the ordering the merge needs. A bfloat form's channels
/// are its own (red; red and green; all four), each a raw component; a mask of some of them is
/// unmeasured and refused as above.
fn extended_write_mask(
@@ -1,59 +0,0 @@
//! A render pipeline's fragment imageblock: `GraphicsState::fragment_imageblock` from the fragment
//! stage's `RuntimeFact::FragmentImageblock`.
//!
//! The fragment function reads and writes the pass's imageblock storage, one plane of cells per
//! pixel, and per sample in a multisampled pass (`ImageblockMechanism::StorageImageInterlock`),
//! and writes it inside its body. Its depth and stencil tests run before its write: its module
//! declares early tests, or each draw's plan checks them (`RuntimeFact::TestedStorageWrites`,
//! `lower::fragment::imageblock`). Link refuses:
//!
//! - a function compiled for another sample count than the pipeline's (`NeedsInput(Multisampled)`):
//! one compiled for a multisampled pipeline reaches its own sample's cell, one compiled for one
//! sample the pixel's;
//! - as not implemented, a pipeline whose alpha to coverage can drop a fragment after the function
//! wrote its imageblock: Metal drops the write with the fragment (measured on the M3 Max, at one
//! sample and at four), and the storage already holds it.
use crate::error::{Error, Feature, RuntimeInput, Unsupported};
use crate::library::FunctionArtifact;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::graphics::{FragmentImageblock, ImageblockMechanism};
use crate::pipeline::link::RenderLinkInputs;
/// The fragment imageblock of render inputs `r` whose fragment stage is `fragment` (see the
/// module docs).
pub fn fragment_imageblock(
r: &RenderLinkInputs,
fragment: Option<&FunctionArtifact>,
) -> Result<Option<FragmentImageblock>, Error> {
let Some(fragment) = fragment else {
return Ok(None);
};
let Some((words, writes, master, data_size, alignment)) =
fragment.facts.iter().find_map(|fact| match *fact {
RuntimeFact::FragmentImageblock {
words,
writes,
master,
data_size,
alignment,
} => Some((words, writes, master, data_size, alignment)),
_ => None,
})
else {
return Ok(None);
};
if fragment.interface.io.multisampled != (r.raster_sample_count > 1) {
return Err(Error::NeedsInput(RuntimeInput::Multisampled));
}
if writes && r.alpha_to_coverage {
return Err(Unsupported::not_implemented(Feature::Imageblocks).into());
}
Ok(Some(FragmentImageblock {
mechanism: ImageblockMechanism::StorageImageInterlock,
words,
master,
data_size,
alignment,
}))
}
@@ -1,88 +0,0 @@
//! A render pipeline's shader-side stencil: `GraphicsState::shadow_stencil` from the fragment
//! stage's `RuntimeFact::ShadowStencil`.
//!
//! On a device without `VK_EXT_shader_stencil_export`, a fragment function's `[[stencil]]`
//! output is tested and written by the function itself against a shadow of the stencil
//! (`lower::fragment`'s `stencil`). Link checks the pipeline's state against the function's form:
//!
//! - the form follows the pipeline's samples: a function compiled for a pipeline of more than one
//! sample (`LoweringInputs::multisampled`) tests each sample of a multisampled shadow, and one
//! linked into a pipeline of another kind is `NeedsInput(Multisampled)`;
//! - a multisampled shadow (or the neutral that stands in for it) is a storage image of the
//! pipeline's samples (`storageImageSampleCounts`), and the consumer copies it to and from the
//! stencil with image copies (`maintenance8`): where the device lacks either, the output is
//! refused naming the extension or what the form lacks;
//! - alpha to coverage changes the fragment's samples before Metal's stencil test, after the
//! function's write: refused as needing the extension;
//! - a pipeline without a stencil attachment states no shadow (Metal's output reaches no
//! attachment): the binder binds a neutral image and the function tests nothing.
use crate::device::requirements::{VkExtension, VkFeature, VkProperty};
use crate::device::DeviceProfile;
use crate::error::{Capability, Error, Feature, RuntimeInput, Unsupported};
use crate::library::FunctionArtifact;
use crate::lower::fragment::SHADOW_FORMAT;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::graphics::ShadowStencilUse;
use crate::pipeline::link::RenderLinkInputs;
/// The shader-side stencil of the fragment stage `fragment` of render inputs `r` on `p` (see the
/// module docs).
pub fn shadow_stencil(
r: &RenderLinkInputs,
fragment: Option<&FunctionArtifact>,
p: &DeviceProfile,
) -> Result<Option<ShadowStencilUse>, Error> {
let Some((formatless, multisampled)) = fragment.and_then(|f| {
f.facts.iter().find_map(|fact| match *fact {
RuntimeFact::ShadowStencil {
formatless,
multisampled,
} => Some((formatless, multisampled)),
_ => None,
})
}) else {
return Ok(None);
};
if !r.rasterization_enabled {
return Ok(None);
}
let samples = r.raster_sample_count.max(1);
if multisampled != (samples > 1) {
return Err(Error::NeedsInput(RuntimeInput::Multisampled));
}
if r.alpha_to_coverage {
return Err(Unsupported::needs(
Feature::StencilExport,
Capability::Extension(VkExtension::ExtShaderStencilExport),
)
.into());
}
let attached = r.stencil_format.is_some();
if samples > 1 {
let f = p.fields();
let mut missing = Vec::new();
let property = VkProperty::StorageImageSampleCount(samples);
if !f.enabled.properties.contains(&property) {
missing.push(Capability::Property(property));
}
if attached && !f.enabled.features.contains(&VkFeature::Maintenance8) {
missing.push(Capability::Feature(VkFeature::Maintenance8));
}
if !missing.is_empty() {
return Err(Unsupported::needs_any_of(
Feature::StencilExport,
vec![
vec![Capability::Extension(VkExtension::ExtShaderStencilExport)],
missing,
],
)
.into());
}
}
Ok(attached.then_some(ShadowStencilUse {
format: SHADOW_FORMAT,
formatless,
samples,
}))
}
@@ -429,8 +429,6 @@ pub fn synthesized_stages(
rounded_colors: Vec::new(),
specialized_notes: Vec::new(),
own_pixel_textures: Vec::new(),
snapshot_textures: Vec::new(),
snapshot_refusals: Vec::new(),
level_reads: Vec::new(),
private_bytes: 0,
stats,
@@ -136,8 +136,6 @@ pub(super) fn iface(
unbound_storage_textures: false,
numbered_samplers: Vec::new(),
own_pixel_textures: Vec::new(),
snapshot_textures: Vec::new(),
snapshot_refusals: Vec::new(),
level_reads: Vec::new(),
private_bytes: 0,
sampler_arrays: Vec::new(),
@@ -1347,138 +1347,6 @@ fn a_framebuffer_fetch_links_into_the_sample_count_it_was_compiled_for() {
}
}
/// A fragment stage that reads color attachment 0 in the interlocked storage form links into a
/// pipeline whose state chooses that form with the format the stage declares: the attachment is a
/// storage attachment, with no color attachment state and no input attachment. A pipeline whose
/// state chooses otherwise (another format, a blending attachment) did not compile the stage:
/// `NeedsInput(FramebufferFetch)`, and one of more samples did not compile it for its sample count:
/// `NeedsInput(Multisampled)`, and one with a depth attachment did not compile it with early tests.
/// A device that orders fetch otherwise never compiles such a stage. Compiled for more than one
/// sample, the stage reads planes where the device has no multisampled storage image (MoltenVK),
/// which need no sample count of storage images, and the pipeline's multisampled attachment
/// elsewhere (RADV).
#[test]
fn an_interlocked_fetch_links_only_into_the_state_it_was_compiled_for() {
use crate::error::{InternalKind, RuntimeInput};
use crate::metal::BlendFactor;
use crate::pipeline::descriptor::ColorAttachmentDescriptor;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::graphics::{StorageAttachmentUse, StorageAttachmentView};
let p = profile("moltenvk-m3");
let va = artifact(iface(Stage::Vertex, vec![], vec![]), None);
let fr = Stage::Fragment;
let storage = StageDescriptor::new(
res(fr, ResourceKind::TileAttachment(0), 0),
vk::DescriptorType::STORAGE_IMAGE,
1,
);
let mut fa = artifact(iface(fr, vec![storage], vec![]), None);
// Compiled without a depth or stencil attachment: no early tests.
fa.facts.push(RuntimeFact::InterlockedFramebufferFetch {
color: 0,
format: vk::Format::R32_SFLOAT,
writes: true,
early_tests: false,
kept: vk::ColorComponentFlags::empty(),
blend: None,
rounded: false,
});
// Blending adds the destination: a blend of one and zero, added, stores the source as no
// blending does, and links into the storage form.
let state_with = |format, blending: bool, samples: u32, depth: bool| {
let mut r = RenderLinkInputs::new();
let mut c = ColorAttachmentDescriptor::new(format);
if blending {
c.blending_enabled = true;
c.destination_rgb_blend_factor = BlendFactor::One;
}
r.color_attachments[0] = Some(c);
r.raster_sample_count = samples;
r.depth_format = depth.then_some(PixelFormat::Depth32Float);
LinkInputs::Render(Box::new(r))
};
let state = |format, blending: bool, samples: u32| state_with(format, blending, samples, false);
let g = link(&[&va, &fa], &state(PixelFormat::R32Float, false, 1), &p)
.expect("link")
.graphics
.expect("graphics");
assert_eq!(
g.storage_attachments,
[StorageAttachmentUse {
color_index: 0,
format: vk::Format::R32_SFLOAT,
writes: true,
// Declared without a format where the device grants that.
formatless: crate::metal::format::accessed_without_format(
vk::Format::R32_SFLOAT,
crate::metal::format::StorageUse::texture(true, true),
&p
),
view: StorageAttachmentView::Attachment,
view_alias: None,
kept: vk::ColorComponentFlags::empty(),
}]
);
assert_eq!(g.color_attachments, [None]);
assert!(g.input_attachments.is_empty());
assert!(!g.rasterization_order_attachment_access);
for other in [
state(PixelFormat::RGBA8Unorm, false, 1),
state(PixelFormat::R32Float, true, 1),
// Its writes would precede a failed depth test.
state_with(PixelFormat::R32Float, false, 1, true),
] {
assert_eq!(
link(&[&va, &fa], &other, &p).unwrap_err(),
Error::NeedsInput(RuntimeInput::FramebufferFetch),
"{other:?}"
);
}
assert_eq!(
link(&[&va, &fa], &state(PixelFormat::R32Float, false, 4), &p).unwrap_err(),
Error::NeedsInput(RuntimeInput::Multisampled)
);
// Compiled for more than one sample: planes without multisampled storage images.
let mut per_sample = fa.clone();
per_sample.interface.io.multisampled = true;
per_sample
.interface
.io
.builtins
.push(crate::pipeline::stage_io::StageBuiltin::SampleId);
let radv = profile("amd-rdna3-radv");
for (p, view) in [
(&p, StorageAttachmentView::SamplePlanes { layers: 4 }),
(&radv, StorageAttachmentView::Attachment),
] {
let g = link(
&[&va, &per_sample],
&state(PixelFormat::R32Float, false, 4),
p,
)
.expect("link")
.graphics
.expect("graphics");
assert_eq!(
g.storage_attachments
.iter()
.map(|a| a.view)
.collect::<Vec<_>>(),
[view]
);
assert_eq!(g.rasterization_samples, vk::SampleCountFlags::COUNT_4);
}
match link(
&[&va, &fa],
&state(PixelFormat::R32Float, false, 1),
&profile("lavapipe"),
) {
Err(Error::Internal(e)) => assert_eq!(e.kind, InternalKind::Invariant),
other => panic!("{other:?}"),
}
}
/// A color attachment that no output of the fragment function names keeps its contents, as Metal
/// kept one where measured: its write mask is empty, while every attachment the function writes
/// keeps the descriptor's mask and every attachment its blend state. A pipeline without a fragment
@@ -17,7 +17,7 @@ use crate::metal;
use crate::pipeline::descriptor::{
StageInputDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor,
};
use crate::pipeline::sym::{SampledType, SlotRef, SnapshotForm, VaryingKey};
use crate::pipeline::sym::{SampledType, SlotRef, VaryingKey};
use crate::vk;
/// Per-function lowering inputs, public projection.
@@ -90,8 +90,8 @@ pub struct LoweringInputs {
/// `InterpolateAtOffset` at offset 0 on a device with interpolation functions whose offset
/// reads from the center (`VkProperty::InterpolateAtOffsetCentered`): the pixel center whatever
/// samples its invocation shades (`StageIo::{multisampled, varyings_at_pixel}`). A function
/// that reads its color attachments (`framebuffer_fetch`) reads, and in the storage form
/// writes, each one's multisampled image at its `SampleId`, running once per covered sample, as
/// that reads its color attachments (`framebuffer_fetch`) reads each one's multisampled image
/// at its `SampleId`, running once per covered sample, as
/// Metal does. `Device::compile_render_pipeline` sets it for a `Function` fragment stage, and a
/// fragment compiled on its own for such a pipeline compiles under it: link refuses one
/// compiled without it whose sample-rate invocations would read either elsewhere, or that reads
@@ -131,20 +131,15 @@ pub struct LoweringInputs {
/// states `RuntimeFact::MergedDraws`. Any other stage compiles as without it.
#[cfg_attr(feature = "serde", serde(default))]
pub merged_draws: bool,
/// The render pipeline state a fragment function's framebuffer fetch takes its form from, on
/// a device that orders a fetch only through the ordered pixel interlock (no
/// `rasterizationOrderColorAttachmentAccess`, with `fragmentShaderPixelInterlock`): there each
/// color attachment the function reads is read, and written, as a storage image inside the
/// interlock where the pipeline's state lets that form be exact, and otherwise is refused.
/// `Device::compile_render_pipeline`
/// sets it for a `Function` fragment stage that declares a `[[color(n)]]` input on such a
/// device, and a fragment compiled on its own for such a pipeline compiles under the same
/// state; without it such a function is `NeedsInput(FramebufferFetch)`. On a device that orders
/// fetch through rasterization-order input attachments, the state of each extended-range
/// attachment the function writes where the pipeline blends it, whose blend the function
/// computes over its input attachment (its depth, coverage and amplification bits unset,
/// which that blend does not read); without it such a function is
/// `NeedsInput(FramebufferFetch)` there too. `None` on every other device and for every other
/// The render pipeline state of the attachments whose writes a fragment function computes
/// over their input attachments, on a device that orders fetch through rasterization-order
/// input attachments: an extended-range attachment the pipeline blends, one held with its
/// channels rotated whose blend no Vulkan state gives, a word or extended-range attachment
/// written under a mask of some of a word's channels, and an attachment a private logic
/// operation the function computes serves. `Device::compile_render_pipeline` sets it for a
/// `Function` fragment stage on such a device, and a fragment compiled on its own for such a
/// pipeline compiles under the same state; without it such a function is
/// `NeedsInput(FramebufferFetch)`. `None` on every other device and for every other
/// function.
#[cfg_attr(feature = "serde", serde(default))]
pub framebuffer_fetch: Option<FramebufferFetchInputs>,
@@ -156,20 +151,6 @@ pub struct LoweringInputs {
/// `PrecisionNote::SrgbTexelDecode`. A slot of no such access is ignored.
#[cfg_attr(feature = "serde", serde(default))]
pub srgb_textures: BTreeSet<SlotRef>,
/// Fragment texture slots of `StageInterface::snapshot_textures` the draw reads through a
/// snapshot (`VariantKey::snapshot_textures`), each with its snapshot's form, drawn twice
/// (`PushField::SnapshotPhase`). The entry opens with the ordered pixel interlock's critical
/// section, in which, in the draw that takes the snapshot, a non-helper invocation copies
/// each slot's texel at its pixel into the slot's snapshot (`ResourceKind::SnapshotTexels`),
/// in the slot's form; that draw then returns. In the draw that
/// reads it, the critical section is empty, and every read of the slot reads the snapshot, or
/// nothing in a helper invocation (`lower::fragment`'s `snapshot`). The binder names only slots
/// of that interface fact (`bind::graphics`); for another, the reads are not Metal's.
#[cfg_attr(
feature = "serde",
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub snapshot_textures: BTreeMap<SlotRef, SnapshotForm>,
/// Texture slots bound to a two-plane YCbCr texture whose planes are read in place
/// (`VariantKey::ycbcr_in_place`, `RuntimeFact::YCbCrInPlace`): each is declared as the
/// planes' uniform texel buffer, and its samples, reads and size queries read the codes and
@@ -492,7 +473,7 @@ pub struct LoweringInputs {
/// unblended (or blended with factors one and zero, added), under a write mask of all of the
/// format's channels or none, and that is not attachment 0 under alpha-to-coverage, of a format
/// the device samples but does not render (one written under a mask of some of its channels
/// is stored in the interlocked storage form instead, named in
/// is merged over the input attachment where the device orders fetch so, named in
/// [`framebuffer_fetch`](Self::framebuffer_fetch)). The function writes such an attachment
/// through an output variable of the word's unsigned integer, the word Metal stores for its
/// `float` or `half` output (`ChannelWrite::HalfUnorm`'s rule per channel); a dual-source
@@ -630,14 +611,6 @@ pub struct LoweringInputs {
/// `Function` fragment stage. Any other function compiles as with 0.
#[cfg_attr(feature = "serde", serde(default))]
pub depth_compare_clamp_mask: u32,
/// The depth and stencil tests of the draws that run the fragment function write neither
/// attachment and count no visibility result (`VariantKey::read_only_tests`): a function that
/// stores a color through the interlocked storage form and declares no early tests only
/// because it discards (`RuntimeFact::TestedStorageWrites`) is lowered with early fragment
/// tests, which then drop what Metal's later tests drop and leave the attachments as Metal's
/// do, and states the fact with `early_tests`. Any other function compiles as without it.
#[cfg_attr(feature = "serde", serde(default))]
pub read_only_tests: bool,
/// The color attachments the fragment function's render pipeline gives a format held with
/// its channels rotated (`metal::format::rotated_channels`, `ARGB8Unorm`), by color index:
/// each such attachment's image holds Metal's alpha, red, green and blue in its red, green,
@@ -659,7 +632,7 @@ pub struct LoweringInputs {
/// red), so alpha to coverage through attachment 0 reads Metal's alpha as Metal's does; a
/// color input (`[[color(n)]]`) of one reads the image's red as Metal's alpha, `(0, 0, 0, r)`,
/// as Metal reads an `A8Unorm` attachment (probe `a8`'s uses on an M3 Max under macOS
/// 27.0.1), through the input attachment or the interlocked storage form alike.
/// 27.0.1), through the input attachment.
/// `Device::compile_render_pipeline` sets it for a `Function` fragment stage from the
/// pipeline's color attachments, and link refuses a fragment compiled under another set as
/// `NeedsInput(ColorWrites)`. Empty for any other function.
@@ -1020,8 +993,9 @@ impl AmplificationDraws {
}
}
/// The render pipeline state a fragment function's interlocked framebuffer fetch depends on
/// (`LoweringInputs::framebuffer_fetch`).
/// The render pipeline state a fragment function's computed writes over its input attachments
/// depend on (`LoweringInputs::framebuffer_fetch`): the attachments whose blend, merge or logic
/// operation the function computes over the texel it reads.
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@@ -1029,26 +1003,14 @@ pub struct FramebufferFetchInputs {
/// Each color attachment index the function declares a `[[color(n)]]` input for: the
/// descriptor's attachment there, `None` where the descriptor sets none.
pub attachments: BTreeMap<u32, Option<FetchedAttachment>>,
/// The pipeline has a depth or a stencil attachment, whose tests can drop a fragment after
/// its function ran.
pub depth_or_stencil: bool,
/// The descriptor enables alpha to coverage.
pub alpha_to_coverage: bool,
/// The descriptor's `maxVertexAmplificationCount` is above 1: the pipeline may draw
/// multiview.
pub amplified: bool,
}
impl FramebufferFetchInputs {
/// The state of a pipeline whose color attachments are `colors` (by Metal index), whose depth
/// and stencil formats are `depth` and `stencil`, under `alpha_to_coverage` and
/// `max_vertex_amplification_count`, for a function that declares color inputs at `read`.
/// The state of a pipeline whose color attachments are `colors` (by Metal index), for a
/// function whose writes at `read` the function computes over its input attachments.
pub fn of(
read: impl IntoIterator<Item = u32>,
colors: &[Option<crate::pipeline::descriptor::ColorAttachmentDescriptor>],
depth_or_stencil: bool,
alpha_to_coverage: bool,
max_vertex_amplification_count: u32,
) -> FramebufferFetchInputs {
FramebufferFetchInputs {
attachments: read
@@ -1073,14 +1035,12 @@ impl FramebufferFetchInputs {
(color, attachment)
})
.collect(),
depth_or_stencil,
alpha_to_coverage,
amplified: max_vertex_amplification_count > 1,
}
}
}
/// What the interlocked framebuffer fetch reads of one color attachment's descriptor.
/// What a function's computed write over its input attachment reads of one color attachment's
/// descriptor.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@@ -1137,28 +1097,6 @@ impl BlendEquation {
alpha_operation: c.alpha_blend_operation,
})
}
/// Whether a factor reads the fragment's second output (`[[color(n), index(1)]]`): dual-source
/// blending.
pub(crate) fn reads_second_source(&self) -> bool {
use metal::BlendFactor as F;
[
self.source_rgb,
self.destination_rgb,
self.source_alpha,
self.destination_alpha,
]
.into_iter()
.any(|f| {
matches!(
f,
F::Source1Color
| F::OneMinusSource1Color
| F::Source1Alpha
| F::OneMinusSource1Alpha
)
})
}
}
impl LoweringInputs {
+4 -6
View File
@@ -117,16 +117,15 @@ pub use descriptor::{
VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor,
};
pub use graphics::{
BandPrimitive, BlendState, ColorAttachmentState, FragmentImageblock, GraphicsState,
ImageblockMechanism, InputAttachmentUse, LineBandState, ShadowStencilUse, StorageAttachmentUse,
StorageAttachmentView, TessellationState,
BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, InputAttachmentUse,
LineBandState, TessellationState,
};
pub use indirect_draws::IndirectDrawLayout;
pub use interface::{
AccessSet, AttributeFetch, BufferForm, BufferKind, BufferSlot, CommandWrites, DescriptorView,
LevelReads, NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc,
PushPlacement, SampledLevels, SamplerArray, SamplerLevels, SamplerSlot, SlotInterface,
SnapshotRefusal, TextureAccess, TextureSlot, ThreadgroupArgument, Window,
TextureAccess, TextureSlot, ThreadgroupArgument, Window,
};
pub use layout::{
BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange,
@@ -159,8 +158,7 @@ pub use crate::lower::simd::workgroup::arena_bytes;
pub use sym::{
AccelerationStructureLevel, AirUserKey, Axis, CombinedSampler, HandleClass, ImageAccess,
ImageDim, ImageHandleClass, PushField, ResourceKind, ResourceSlot, SampledType, SamplerRef,
SlotClass, SlotRef, SnapshotForm, SpecKey, Stage, StorageFormatClass, Symbol, SyntheticBinding,
VaryingKey,
SlotClass, SlotRef, SpecKey, Stage, StorageFormatClass, Symbol, SyntheticBinding, VaryingKey,
};
pub use vertex::{PulledAttribute, VertexAttribute, VertexBinding, VertexInputState, VertexStride};
@@ -63,8 +63,8 @@
//! (`PrecisionNote::NativeLogicOperation`, [`note_vulkan_codes`]). An integer output past the
//! channel's range, which Metal saturates first, Vulkan's conversion leaves undefined
//! (lavapipe and an RTX 3090 saturate it, as Metal does). A device without it that
//! orders framebuffer fetch (the
//! pixel interlock, or rasterization-order input attachments) has the fragment function compute
//! orders framebuffer fetch through rasterization-order input attachments has the fragment
//! function compute
//! the operation itself, over the texel its first output's write reads (`lower::fragment`'s
//! `logic`; probe `logic_operation` on an Apple M3 Max, macOS 27.0.1: every operation into
//! `R8Unorm`, `A8Unorm`, `RGBA8Unorm`, `BGRA8Unorm`, `R16Unorm`, `RGBA16Unorm`, `RGB10A2Unorm`,
@@ -77,8 +77,8 @@
//! operate on their codes widened to 16 bits, the result narrowed back. It refuses formats
//! outside that rule (`RGB10A2Uint` and the packed 16-bit formats, whose operation Metal
//! computes otherwise), color 0 under alpha to coverage, and a function that writes the attachment
//! through a shadow stencil, an imageblock or a merged word ([`logic_operated`]). A device that
//! orders fetch in neither form refuses the operation naming the features. So is an operation
//! through a merged word ([`logic_operated`]). A device that does not order fetch refuses the
//! operation naming Vulkan's operation and rasterization-order access. So is an operation
//! other than copy and no-op refused where Vulkan's form is not Metal's: an sRGB attachment
//! (Vulkan applies none there), a float attachment that blends under Vulkan's operation (which
//! turns every blend off), a format whose operation Metal was not measured with
@@ -327,18 +327,15 @@ pub(crate) fn shader_sample_mask(
applied_masks(d).filter(|m| !uniform(m) || observes_sample_mask(a))
}
/// [`GraphicsState::sample_mask`] for the pipeline `d`, its fragment function `fragment` and
/// its graphics state `g`, or the refusal where neither Vulkan's mask nor the function's own
/// [`GraphicsState::sample_mask`] for the pipeline `d` and its fragment function `fragment`, or
/// the refusal where neither Vulkan's mask nor the function's own
/// (`StageIo::sample_mask`) is Metal's. A function that could tell Vulkan's mask from Metal's,
/// or of a pipeline whose masks differ between the places of a quad, applies the masks itself,
/// and the pipeline has no Vulkan mask; one compiled without them, or for others, is compiled for
/// the pipeline again (`NeedsInput(SampleMask)`). A pipeline whose fragment function writes an
/// attachment itself (a storage attachment, a shadow stencil or an imageblock, none measured
/// under the masks) is refused, naming the sample coverage where it is not 1.
/// the pipeline again (`NeedsInput(SampleMask)`).
pub(crate) fn sample_mask(
d: &RenderPipelineDescriptor,
fragment: Option<&FunctionArtifact>,
g: &GraphicsState,
) -> Result<Option<u32>, Error> {
let applied = applied_masks(d);
let own = fragment.and_then(|f| f.interface.io.sample_mask);
@@ -348,15 +345,6 @@ pub(crate) fn sample_mask(
let Some(masks) = applied else {
return Ok(None);
};
let writes_itself = !g.storage_attachments.is_empty()
|| g.shadow_stencil.is_some()
|| g.fragment_imageblock.is_some();
if writes_itself {
return Err(refused(match d.private.sample_coverage == 1.0 {
true => PrivateRenderField::SampleMask,
false => PrivateRenderField::SampleCoverage,
}));
}
match (own, fragment) {
(Some(_), _) => Ok(None),
(None, Some(f)) if observes_sample_mask(f) || !uniform(&masks) => {
@@ -488,14 +476,11 @@ pub(crate) fn logic_operation<'a>(
let op = LOGIC_OPS[(d.private.logic_operation & 15) as usize];
let blendless = matches!(op, vk::LogicOp::COPY | vk::LogicOp::NO_OP);
let shader = !blendless && !p.fields().enabled.features.contains(&VkFeature::LogicOp);
if shader
&& !(crate::lower::fragment::interlock_orders(p) || crate::lower::fragment::inputs_order(p))
{
if shader && !crate::lower::fragment::inputs_order(p) {
return Err(Unsupported::needs_any_of(
Feature::PrivateRenderState(PrivateRenderField::LogicOperation),
vec![
vec![Capability::Feature(VkFeature::LogicOp)],
vec![Capability::Feature(VkFeature::FragmentShaderPixelInterlock)],
vec![Capability::Feature(
VkFeature::RasterizationOrderColorAttachmentAccess,
)],
@@ -549,16 +534,13 @@ pub(crate) fn logic_operation<'a>(
/// `Ok` where the linked pipeline `g` draws its logic operation `draw` ([`logic_operation`]) as
/// Metal's. Vulkan's operation applies to the color attachments of the subpass alone, so a
/// pipeline whose fragment function writes an attachment itself (a storage attachment, a shadow
/// stencil, an imageblock, or a word it merges with its input attachment's) is refused
/// pipeline whose fragment function merges a word with its input attachment's is refused
/// (`PrivateRenderField::LogicOperation`), Metal's answer there unmeasured. The operation the
/// fragment function computes must be the one it compiled under (`StageIo::logic_operation`,
/// else `NeedsInput(LogicOperation)`), and is refused beside a shadow stencil, an imageblock or a
/// merged word, which it does not compute over.
/// else `NeedsInput(LogicOperation)`).
pub(crate) fn logic_operated(
draw: Option<LogicDraw>,
fragment: Option<&FunctionArtifact>,
g: &GraphicsState,
) -> Result<(), Error> {
let compiled = fragment.and_then(|f| f.interface.io.logic_operation);
let Some(draw) = draw else {
@@ -575,16 +557,12 @@ pub(crate) fn logic_operated(
)
})
});
let beside = g.shadow_stencil.is_some() || g.fragment_imageblock.is_some() || merges;
match draw {
LogicDraw::Vulkan(_) if beside || !g.storage_attachments.is_empty() => {
Err(refused(PrivateRenderField::LogicOperation))
}
LogicDraw::Vulkan(_) if merges => Err(refused(PrivateRenderField::LogicOperation)),
LogicDraw::Vulkan(_) => match compiled {
Some(_) => Err(Error::NeedsInput(RuntimeInput::LogicOperation)),
None => Ok(()),
},
LogicDraw::Shader(_) if beside => Err(refused(PrivateRenderField::LogicOperation)),
LogicDraw::Shader(op) => match compiled == Some(op) {
true => Ok(()),
false => Err(Error::NeedsInput(RuntimeInput::LogicOperation)),
@@ -28,9 +28,8 @@
//! different color and alpha operations (`rotated_blend` refuses them `NotImplemented(Format)`).
//! Where the device orders framebuffer fetch, the function reads the texel, rotates it into
//! Metal's order, and computes Metal's 8-bit unorm blend over it
//! (`color_writes::shader_rotated_blend`: the interlocked storage form, or over the input
//! attachment); a device that orders fetch in neither form refuses the pipeline naming both
//! orderings. A factor of the second source (Metal's own second output beside one the rotation
//! (`color_writes::shader_rotated_blend`, over the input attachment); a device that does not
//! order fetch so refuses the pipeline naming rasterization-order access. A factor of the second source (Metal's own second output beside one the rotation
//! needs, or any `Source1` factor where no Vulkan state gives the blend) stays
//! `NotImplemented(Format)`. A one minus a value the function would compute is not offered
//! among Vulkan's factors: it would round apart from the blend's own.
+5 -6
View File
@@ -157,8 +157,8 @@ pub struct StageIo {
#[cfg_attr(feature = "serde", serde(default))]
pub coverage_loop: CoverageLoop,
/// How the fragment function writes each color attachment whose format converts its float
/// output (`LoweringInputs::color_writes`), for every attachment it writes, through an output
/// variable or in the storage form: link refuses a stage compiled for another map than the
/// output (`LoweringInputs::color_writes`), for every attachment it writes through an output
/// variable: link refuses a stage compiled for another map than the
/// pipeline's (`NeedsInput(ColorWrites)`).
#[cfg_attr(feature = "serde", serde(default))]
pub color_writes: BTreeMap<u32, [Option<ChannelWrite>; 4]>,
@@ -202,8 +202,8 @@ pub struct StageIo {
pub rotated_colors: std::collections::BTreeSet<u32>,
/// The attachments whose image holds Metal's alpha in red
/// (`LoweringInputs::alpha_in_red_colors`) that the fragment function writes through an output
/// variable of either dual-source index, or reads (`[[color(n)]]`) through an input attachment
/// or the interlocked storage form, by color index: each such output holds Metal's alpha in
/// variable of either dual-source index, or reads (`[[color(n)]]`) through an input
/// attachment, by color index: each such output holds Metal's alpha in
/// the image's alpha lane too, which alpha to coverage reads, and each read takes the image's
/// red as Metal's alpha. Link refuses a stage compiled for another set than the pipeline's
/// (`NeedsInput(ColorWrites)`).
@@ -323,8 +323,7 @@ pub struct StageIo {
#[cfg_attr(feature = "serde", serde(default))]
pub float_blend_colors: Vec<u32>,
/// The attachments a `half` color output of a module compiled with fast math
/// (`air.compile.fast_math_enable`) reaches as color attachments, by color index, sorted (not
/// one the function writes in the storage form).
/// (`air.compile.fast_math_enable`) reaches as color attachments, by color index, sorted.
/// Metal's compiler folds the attachment's blend and conversion into the function under fast
/// math, so the pipeline's stage records `PrecisionNote::HalfOutputFastMathBlend` where one of
/// these attachments stores some channel (`color_writes::stores_output`). One whose write mask
+4 -139
View File
@@ -87,111 +87,6 @@ pub enum SampledType {
Uint64,
}
/// How a draw read through a snapshot keeps a texture's texel in the snapshot
/// (`VariantKey::snapshot_textures`): the texel's codes, from which the read gives back the
/// fetched value bit for bit, in as few bytes as hold them, or the fetched lanes' bits.
///
/// The copy takes the codes from the value the fetch returns, and the read decodes them as Metal
/// reads the format: a normalized code `c` as `c / (2^b - 1)` correctly rounded (a signed one's
/// magnitude so, `-1` at most), a half-float code widened exactly, an integer code extended. A
/// device whose own decode is exactly that (its value one Metal reads) is given back its fetched
/// value; one whose decode is not is given Metal's.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SnapshotForm {
/// The fetched `vec4`'s 32 bits a lane (`R32G32B32A32_UINT`): any texel.
Bits,
/// Four 8-bit unsigned normalized codes (`R8G8B8A8_UINT`).
Unorm8,
/// Four 8-bit signed normalized codes (`R8G8B8A8_UINT`, two's complement).
Snorm8,
/// Four 16-bit unsigned normalized codes (`R16G16B16A16_UINT`).
Unorm16,
/// Four 16-bit signed normalized codes (`R16G16B16A16_UINT`, two's complement).
Snorm16,
/// Four half-float codes (`R16G16B16A16_UINT`).
Half,
/// Four 8-bit unsigned integer codes (`R8G8B8A8_UINT`).
Uint8,
/// Four 8-bit signed integer codes (`R8G8B8A8_UINT`, two's complement).
Sint8,
/// Four 16-bit unsigned integer codes (`R16G16B16A16_UINT`).
Uint16,
/// Four 16-bit signed integer codes (`R16G16B16A16_UINT`, two's complement).
Sint16,
}
impl SnapshotForm {
/// The form a texture slot of sampled type `ty` keeps its texels in, read through a sampled
/// view of `format`: the codes of an 8- or 16-bit normalized, half-float or integer format
/// whose class is the slot's, one, two or four channels; [`Bits`](Self::Bits) for any other
/// format (an sRGB format's view decodes its codes, so its texels are no codes' values).
pub fn of(format: vk::Format, ty: SampledType) -> SnapshotForm {
use vk::Format as F;
let form = match format {
F::R8_UNORM
| F::R8G8_UNORM
| F::R8G8B8A8_UNORM
| F::B8G8R8A8_UNORM
| F::A8B8G8R8_UNORM_PACK32 => SnapshotForm::Unorm8,
F::R8_SNORM | F::R8G8_SNORM | F::R8G8B8A8_SNORM | F::A8B8G8R8_SNORM_PACK32 => {
SnapshotForm::Snorm8
}
F::R16_UNORM | F::R16G16_UNORM | F::R16G16B16A16_UNORM => SnapshotForm::Unorm16,
F::R16_SNORM | F::R16G16_SNORM | F::R16G16B16A16_SNORM => SnapshotForm::Snorm16,
F::R16_SFLOAT | F::R16G16_SFLOAT | F::R16G16B16A16_SFLOAT => SnapshotForm::Half,
F::R8_UINT | F::R8G8_UINT | F::R8G8B8A8_UINT | F::A8B8G8R8_UINT_PACK32 => {
SnapshotForm::Uint8
}
F::R8_SINT | F::R8G8_SINT | F::R8G8B8A8_SINT | F::A8B8G8R8_SINT_PACK32 => {
SnapshotForm::Sint8
}
F::R16_UINT | F::R16G16_UINT | F::R16G16B16A16_UINT => SnapshotForm::Uint16,
F::R16_SINT | F::R16G16_SINT | F::R16G16B16A16_SINT => SnapshotForm::Sint16,
_ => SnapshotForm::Bits,
};
let class = match form {
SnapshotForm::Bits => return form,
SnapshotForm::Uint8 | SnapshotForm::Uint16 => SampledType::Uint,
SnapshotForm::Sint8 | SnapshotForm::Sint16 => SampledType::Sint,
_ => SampledType::Float,
};
match class == ty {
true => form,
false => SnapshotForm::Bits,
}
}
/// The snapshot's format: an unsigned integer format of the codes' width, four channels.
pub fn format(self) -> vk::Format {
match self {
SnapshotForm::Bits => vk::Format::R32G32B32A32_UINT,
SnapshotForm::Unorm8
| SnapshotForm::Snorm8
| SnapshotForm::Uint8
| SnapshotForm::Sint8 => vk::Format::R8G8B8A8_UINT,
SnapshotForm::Unorm16
| SnapshotForm::Snorm16
| SnapshotForm::Half
| SnapshotForm::Uint16
| SnapshotForm::Sint16 => vk::Format::R16G16B16A16_UINT,
}
}
/// The width in bits of each code, and whether it is signed; `None` for
/// [`Bits`](Self::Bits).
pub(crate) fn code(self) -> Option<(u8, bool)> {
match self {
SnapshotForm::Bits => None,
SnapshotForm::Unorm8 | SnapshotForm::Uint8 => Some((8, false)),
SnapshotForm::Snorm8 | SnapshotForm::Sint8 => Some((8, true)),
SnapshotForm::Unorm16 | SnapshotForm::Half | SnapshotForm::Uint16 => Some((16, false)),
SnapshotForm::Snorm16 | SnapshotForm::Sint16 => Some((16, true)),
}
}
}
/// Whether an image is sampled or used as a storage image.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -289,9 +184,9 @@ pub enum SyntheticBinding {
/// instanceStride:`), a read-only storage buffer of a tessellation pipeline's synthesized
/// control stage, declared with the vertex stage's symbols.
TessellationFactors,
/// The render pass's fragment imageblock: a coherent `R32Uint` 2D-array storage image
/// whose layer `w` holds word `w` of every pixel's imageblock cell, read and written inside the
/// fragment's ordered pixel-interlock critical section.
/// The render pass's imageblock storage: a coherent `R32Uint` 2D-array storage image whose
/// layer `w` holds word `w` of every pixel's imageblock cell, which a tile dispatch whose
/// function's explicit imageblock stands alone stages its tile's cells from and back.
Imageblock,
/// The sampler table: the handle table's layout over the argument buffers' samplers, whose
/// resource ids live apart from the textures' (the sampler half): 16-byte entries `{id low, id
@@ -301,11 +196,6 @@ pub enum SyntheticBinding {
/// the index of the entry its id finds (0 for an id the table lacks), and every use of it reads
/// that entry's element and word.
SamplerTable,
/// The shadow of the render pass's stencil attachment a fragment function's shader-side
/// stencil tests and writes (`GraphicsState::shadow_stencil`): a coherent `R8Uint` 2D storage
/// image holding pixel `(x, y)`'s stencil value at texel `(x, y)`, read and written inside the
/// fragment's ordered pixel-interlock critical section.
ShadowStencil,
/// The function-table directory: the handle table's layout over the visible-function tables
/// the pipeline state made, whose resource ids live apart from textures' and samplers'.
FunctionTableDirectory,
@@ -377,11 +267,6 @@ pub enum ResourceKind {
/// constexpr sampler is the binding's immutable sampler. `ResourceSlot::index` is the use
/// ([`ResourceSlot::separate_sampler`]), as a heap sampler's is.
SeparateSampler(SamplerRef),
/// The snapshot of the texture bound at fragment texture slot `n` (`ResourceSlot::index` too)
/// for a draw that reads it through one (`LoweringInputs::snapshot_textures`): an
/// `R32G32B32A32_UINT` 2D storage image covering the draw's render area, each texel the bits
/// of the four values a fetch of the texture's level 0 there returned.
SnapshotTexels(u32),
/// The planes of the two-plane YCbCr texture bound at the stage's texture slot
/// `ResourceSlot::index`, held as an image of the multi-planar format that the device's own
/// sampler Y′CbCr conversion samples (`LoweringInputs::ycbcr_planes_sampled`): a combined
@@ -948,12 +833,6 @@ pub enum PushField {
/// sequences ([`PushField::IndirectSequence`]) from 0, and pushes each part's first here. 0
/// for a direct draw. Placed beside the addresses, so the vertex window always holds it.
IndirectBase,
/// Which draw of a fragment function compiled under `LoweringInputs::snapshot_textures` runs
/// (`u32`): a hole the consumer fills (`PushHole::SnapshotPhase`), placed beside the addresses
/// so the fragment window always holds it. 1 in the draw that takes the snapshot, whose
/// fragments copy their pixels' texels into it and run nothing else; 0 in the draw that reads
/// it, whose fragments copy nothing and run the function.
SnapshotPhase,
// The three amplification words come right after the addresses in the order, so every stage
// window holds them (at most 32 bytes before them, 12 of them): a draw of one amplification
// writes them alone, between its draws, never through an `ArgumentTable`.
@@ -1033,13 +912,6 @@ pub enum PushField {
/// the device replay's preprocess module reads (`bind::replay`). No translated function
/// reads it.
CommandRecordsAddress,
/// The render encoder's stencil state for a fragment function's shader-side stencil
/// (`RuntimeFact::ShadowStencil`), a `uvec2`: the front face's word, then the back face's.
/// Each word holds the face's `MTLCompareFunction` in bits 0 to 2, its stencil-failure and
/// depth-stencil-pass `MTLStencilOperation`s in bits 3 to 5 and 6 to 8, its read mask in bits
/// 9 to 16, its write mask in bits 17 to 24, and in bit 31 whether the draw's pass has a
/// stencil attachment for the function to test against (`bind::shadow_stencil_words`).
ShadowStencilState,
/// The whole indices (`u64`) from an indexed indirect draw's bound index offset to its index
/// buffer's end, which the index-clamp prepass reads. No translated function reads it.
IndexCapacity,
@@ -1086,12 +958,6 @@ pub enum PushField {
/// reads its raw index at `PushField::CaptureIndexAddress`, and its vertex is that index plus
/// the base vertex.
CaptureLayout,
/// The channels each storage-form color attachment's write keeps from its texel, where the
/// fragment function takes them from the draw: one `u32` whose bits `4c` to `4c + 3` are color
/// `c`'s `R`, `G`, `B` and `A`, set where the pipeline's write mask leaves the channel out
/// (`StorageAttachmentUse::kept`), so every write mask that keeps some of a format's channels
/// shares one module.
StorageKeptChannels,
/// The channel widths of the storage texture bound to the slot (`u32`;
/// `metal::format::integer_channels_word`, 0 where the binder binds a neutral): byte `c`
/// holds `32 - bits` of channel `c` (red to alpha) of an integer format narrower than 32 bits,
@@ -1107,7 +973,7 @@ pub enum PushField {
BicubicTexels(SlotRef),
/// The render encoder's blend color (`setBlendColorRed:green:blue:alpha:`) for a fragment
/// function that computes a blend in the shader under a blend that reads it (an
/// extended-range attachment's, or a fetched attachment's in the storage form): one `uvec4`
/// extended-range attachment's, or a rotated one's): one `uvec4`
/// holding the four `f32`s' bits as the encoder set them (`BindState::blend_color`).
HalfBlendColor,
/// The render encoder's alpha test reference (`setAlphaTestReferenceValue:`) for a fragment
@@ -1289,7 +1155,6 @@ mod tests {
PushField::RootTableAddress,
PushField::ExecutionStatusAddress,
PushField::CaptureIndexAddress,
PushField::SnapshotPhase,
PushField::DispatchRegion,
PushField::ReplayRegionAddress,
PushField::BaseVertexInstance,
@@ -75,8 +75,6 @@ pub struct ModuleBuilder {
/// Every storage buffer and storage image resource is decorated `Coherent`
/// (`ModuleBuilder::coherent_resources`).
coherent: bool,
/// Storage-image resources decorated `Coherent` one by one (`ModuleBuilder::coherent`).
coherent_images: BTreeSet<GlobalId>,
/// Storage-image resources decorated `Volatile` (`ModuleBuilder::volatile`).
volatile: BTreeSet<GlobalId>,
/// Buffer bindings whose memory nothing in the module writes (`ModuleBuilder::unwritten_buffer`).
@@ -850,31 +848,6 @@ impl ModuleBuilder {
self.coherent = true;
}
/// Decorate storage-image resource `g` `Coherent`: under the `GLSL450` memory model each access
/// to its texels is made available and visible at device scope, as
/// [`coherent_resources`](ModuleBuilder::coherent_resources) makes every shared resource's,
/// for one image whose accesses an ordered fragment-interlock critical section orders while
/// the module's other resources keep plain accesses. Only a `UniformConstant` resource whose
/// type is a storage image can be; the Vulkan memory model bans the decoration
/// ([`ModuleBuilder::finalize`]).
pub fn coherent(&mut self, g: GlobalId) -> BResult<()> {
let gv = self.global(g)?;
let storage = gv.class == StorageClass::UniformConstant
&& matches!(gv.kind, GlobalKind::Resource(_))
&& matches!(
self.types.get(gv.pointee)?,
Type::Image(ImageType {
usage: ImageUsage::Storage,
..
})
);
if !storage {
return Err(BuildError::Global(GlobalRule::CoherentTarget));
}
self.coherent_images.insert(g);
Ok(())
}
/// Decorate storage-image resource `g` `Volatile`: under the `GLSL450` memory model every
/// access to its texels is a volatile access, so a load never returns a value the invocation
/// stored to that out-of-bounds location and the device's robustness discarded. Vulkan lets
@@ -1260,15 +1233,14 @@ impl ModuleBuilder {
if !self.volatile.is_empty() && vulkan {
return Err(BuildError::Global(GlobalRule::VolatileTarget));
}
if (self.coherent || !self.coherent_images.is_empty()) && vulkan {
if self.coherent && vulkan {
return Err(BuildError::Global(GlobalRule::CoherentTarget));
}
let mut coherent = if self.coherent {
let coherent = if self.coherent {
shared_resources(&self.types, &self.globals)?
} else {
BTreeSet::new()
};
coherent.extend(self.coherent_images);
Ok(TypedModule {
types: self.types,
consts: self.consts,
@@ -867,57 +867,6 @@ fn only_storage_images_are_volatile_and_never_under_the_vulkan_model() {
);
}
/// `coherent` decorates the one storage image it names `Coherent`, leaving the module's other
/// shared resources plain, and refuses a sampled image.
#[test]
fn coherent_decorates_one_storage_image_alone() {
let texture = |index| ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::Texture,
index,
};
let image = |t: &mut T, usage, format| {
let u = t.u32();
t.ty(Type::Image(ImageType {
sampled_type: u,
dim: Dim::D2,
depth: false,
arrayed: false,
multisampled: false,
usage,
format,
}))
};
let mut t = T::new();
let storage = image(
&mut t,
ImageUsage::Storage,
crate::spv::ImageFormat::Rgba32ui,
);
let sampled = image(
&mut t,
ImageUsage::Sampled,
crate::spv::ImageFormat::Unknown,
);
let one =
t.b.resource(texture(0), StorageClass::UniformConstant, storage)
.expect("image");
let other =
t.b.resource(texture(1), StorageClass::UniformConstant, storage)
.expect("other image");
let read =
t.b.resource(texture(2), StorageClass::UniformConstant, sampled)
.expect("sampled");
t.b.coherent(one).expect("a storage image");
assert_eq!(
t.b.coherent(read).err(),
Some(BuildError::Global(GlobalRule::CoherentTarget))
);
let m = finish_compute(t.b).expect("a GLSL450 module with one coherent image");
assert_eq!(m.coherent, BTreeSet::from([one]));
assert!(!m.coherent.contains(&other));
}
/// `coherent_resources` decorates every storage buffer and storage image resource of the module
/// `Coherent` (a descriptor array of storage images included, those declared after it too), and no
/// uniform buffer or sampled image; a module under the Vulkan memory model, which bans the
@@ -90,12 +90,10 @@ fn independence_needed(widths: &BTreeSet<u8>) -> Independence {
mod level_reads;
mod own_pixel;
mod snapshot;
mod writes;
pub use level_reads::level_reads;
pub use own_pixel::own_pixel_textures;
pub use snapshot::{snapshot_copies_alone, snapshot_textures, Judged};
pub use writes::writes_memory;
#[cfg(test)]
@@ -1,624 +0,0 @@
//! Which own-pixel texture slots a fragment module can read through a snapshot an earlier draw of
//! the same primitives took (`StageInterface::snapshot_textures`).
//!
//! A runtime may serve a draw that reads a texture its own render pass renders, at the fragment's
//! own pixel alone (`own_pixel`), by drawing the draw twice with one pipeline: first with every
//! color write mask zero, each fragment copying the texel it would read into a snapshot image, then
//! with the draw's own masks, each fragment reading the snapshot (the runtime's
//! `texture/attached_reads.rs`). A helper invocation reads nothing there: its pixel may hold no
//! fragment of the draw, so no copy wrote its snapshot texel, and the by-region barriers that order
//! a copy before the reads order it for fragments of the same pixel alone. So the slot's value in a
//! helper invocation is a constant, which is exact only where no fragment's result depends on a
//! helper's value of it, and only where the constant gives the helper no undefined behavior.
//!
//! A helper invocation's values reach other invocations' results only through derivatives and quad
//! operations ("When performing derivative or quad group operations in a fragment shader,
//! additional invocations may be spawned in order to ensure correct results", the Shaders
//! chapter's Helper Invocations), and its stores have no effect ("Stores and atomics performed by
//! helper invocations must not have any effect on memory except for the Function, Private and
//! Output storage classes"). A value that decides a branch can also move a helper off its quad's
//! path, which changes what a derivative there reads, or keep it in a loop the texture's own texel
//! would end. And where a helper's constant is an operand that an instruction's behavior is
//! undefined for, the helper has undefined behavior that Metal's read of the texel need not give
//! it: an integer division's ("Behavior is undefined if any component of Operand 2 is 0", the
//! SPIR-V specification's `OpUDiv`, `OpUMod`; `OpSDiv`, `OpSRem` and `OpSMod` also at `-1` beside
//! the minimum) and a dynamic component index's ("Behavior is undefined if Index's value is less
//! than zero or greater than or equal to the number of components in Vector",
//! `OpVectorExtractDynamic`, `OpVectorInsertDynamic`). So a slot qualifies only where no value that
//! a fetch of it reaches, through any instruction, phi, or `Function`, `Private` or `Output`
//! variable it is stored in and loaded from, is an operand of:
//!
//! - a derivative, a sample, gather or level-of-detail query of any image, a subgroup or quad
//! operation, an atomic, an image write or texel pointer, a ray query, a mesh output count, or a
//! store to any other storage class;
//! - a conditional branch or a switch, but for a selection whose arms a helper may take in place
//! of a fragment's to no one's harm (below), or the entry's returned value;
//! - the divisor of an integer division or remainder, the dividend of a signed one whose divisor
//! is not a constant without a `-1` lane, or a dynamic vector component index.
//!
//! A selection on such a value keeps the slot where its arms leave through its merge block alone
//! (no break, continue, return, `OpKill`, `OpTerminateInvocation` or unreachable end) and hold no
//! derivative, implicit-level sample or level-of-detail query, subgroup or quad operation, loop,
//! or operand undefined at some value that is not a constant, nor do the functions they call
//! ([`arms`]). A helper whose constant takes it down another arm than the texel would then
//! changes nothing another invocation reads: no tangled instruction runs in its arms ("When performing derivative or quad
//! group operations in a fragment shader, additional invocations may be spawned in order to ensure
//! correct results", so only those read a helper's values), it reaches the merge as a fragment
//! does, and `OpDemoteToHelperInvocation` in an arm leaves it what it is ("is not considered a
//! flow control instruction"). What it leaves behind, the merge's phis and what its arms store in
//! `Function`, `Private` and `Output` variables, takes the condition's reach, and its uses are
//! judged as any other. A loop's exit is a branch out of it, which no such selection holds.
//!
//! A call is followed into its callee: "Argument N is the object to copy to parameter N of
//! Function" (`OpFunctionCall`), so each argument's reach is its parameter's, a pointer argument's
//! memory is its parameter's (what either side stores through it the other may load), and the
//! values the callee returns reach the call's result. The callee's instructions are the module's,
//! judged as any other; a callee called from several sites takes the reach of them all.
//!
//! A module that already holds an interlock critical section has none: the variant's entry opens
//! its own. Nor has one with a `Coherent` resource or under the Vulkan memory model: the variant
//! decorates its snapshot `Coherent`. The test is structural, never a name.
//!
//! Each slot left out is stated with every clause that leaves it out ([`SnapshotRefusal`],
//! `StageInterface::snapshot_refusals`): the analysis keeps one reach for each clause.
//!
//! [`snapshot_copies_alone`] checks a variant compiled to read such slots through snapshots: its
//! only texel access of each is the entry's copy.
use crate::budget::Meter;
use crate::error::Error;
use crate::pipeline::interface::SnapshotRefusal;
use crate::pipeline::sym::ResourceKind;
use crate::spirv::ids::Value;
use crate::spirv::ir::{
BinOp, ConstKind, Constant, ExecModel, GlobalKind, Inst, StorageClass, Terminator, Type,
TypedModule, UnOp, ValueOrigin,
};
use super::own_pixel::{carried_on, holds_image, use_of, Use};
use arms::Arms;
/// The most passes over the module the reach is followed for; a module whose values take more to
/// settle (a chain of loop-carried copies longer than this) has no slot.
const MOST_PASSES: u32 = 16;
/// No slot's image.
const NONE: u32 = u32::MAX;
mod arms;
#[cfg(test)]
mod tests;
/// What [`snapshot_textures`] finds of a fragment module's own-pixel texture slots.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Judged {
/// The slots a draw can read through a snapshot (`StageInterface::snapshot_textures`), sorted.
pub slots: Vec<u32>,
/// Each other slot with every clause that leaves it out
/// (`StageInterface::snapshot_refusals`), sorted by slot and then by clause.
pub refusals: Vec<(u32, SnapshotRefusal)>,
}
/// The slots among `own` (fragment module `m`'s own-pixel texture slots, `own_pixel_textures`,
/// sorted) whose fetched values reach none of the uses the module docs list, in a module that
/// holds no interlock, coherent resource or Vulkan memory model, of a function that writes no
/// memory (`writes_memory`, `StageInterface::writes_memory`), and every clause that leaves out
/// each other one: those of the module and the function, and those of the uses its values reach,
/// which the walk states in every case. A slot at or past 128 is left out unwalked. Nothing for a
/// module of another stage. It charges `meter` for its tables while it holds them.
pub fn snapshot_textures(
m: &TypedModule,
own: &[u32],
writes_memory: bool,
meter: &mut Meter,
) -> Result<Judged, Error> {
if own.is_empty() || m.entry().model != ExecModel::Fragment {
return Ok(Judged::default());
}
let interlocked = m
.blocks()
.iter()
.flat_map(|b| &b.insts)
.any(|n| matches!(n.inst, Inst::BeginInterlock | Inst::EndInterlock));
// The variant decorates its snapshot `Coherent`, which the Vulkan memory model bans, beside
// which no other resource of the function may be coherent (`lower::sync::memory_model`).
let coherent = !m.coherent.is_empty() || super::uses_vulkan_memory_model(m.requirements());
let walked: Vec<u32> = own.iter().copied().filter(|&s| s < 128).collect();
let every: u128 = walked.iter().fold(0, |acc, &s| acc | (1u128 << s));
let mut refused = Refused::default();
for (holds, why) in [
(writes_memory, SnapshotRefusal::WritesMemory),
(interlocked, SnapshotRefusal::Interlock),
(coherent, SnapshotRefusal::Coherent),
] {
if holds {
refused.add(why, every);
}
}
if !walked.is_empty() {
let n = m.values().len();
// Each value's slot image (`NONE` for none), its reach (the slots whose fetched values it
// holds), the reach of the memory behind it where it is a variable's pointer, and the
// variable a pointer points into; each block's function, and the reach each function
// returns; and the walks over the selections' arms.
let (blocks, functions) = (m.blocks().len(), m.functions().len());
let tables =
n * (4 + 16 + 16 + 4) + 4 * blocks + 16 * functions + Arms::bytes(blocks, functions);
meter.charge(tables)?;
let result = reach(m, &walked, n, &mut refused);
meter.release(tables);
result?;
}
let mut judged = refused.judged(&walked);
let past = own.iter().filter(|&&s| s >= 128);
(judged.refusals).extend(past.map(|&s| (s, SnapshotRefusal::Other)));
judged.refusals.sort_unstable();
Ok(judged)
}
/// The slots each clause leaves out, as masks of slot bits, indexed by [`SnapshotRefusal`].
#[derive(Default)]
struct Refused([u128; 12]);
impl Refused {
/// The clauses each mask stands for, in the masks' order.
const CLAUSES: [SnapshotRefusal; 12] = [
SnapshotRefusal::Branch,
SnapshotRefusal::Derivative,
SnapshotRefusal::Sample,
SnapshotRefusal::GroupOperation,
SnapshotRefusal::Store,
SnapshotRefusal::Atomic,
SnapshotRefusal::ImageWrite,
SnapshotRefusal::UndefinedOperand,
SnapshotRefusal::WritesMemory,
SnapshotRefusal::Interlock,
SnapshotRefusal::Coherent,
SnapshotRefusal::Other,
];
/// Leave out the slots of `reach` for `why`.
fn add(&mut self, why: SnapshotRefusal, reach: u128) {
let at = Self::CLAUSES.iter().position(|&c| c == why);
if let Some(mask) = at.and_then(|i| self.0.get_mut(i)) {
*mask |= reach;
}
}
/// Whether any clause leaves `slot` out.
fn any(&self, slot: u32) -> bool {
self.0.iter().any(|mask| mask & (1u128 << slot) != 0)
}
/// The slots of `own` none leaves out, and each other one with every clause that does.
fn judged(&self, own: &[u32]) -> Judged {
let mut judged = Judged::default();
for &slot in own {
if !self.any(slot) {
judged.slots.push(slot);
}
for (mask, &why) in self.0.iter().zip(&Self::CLAUSES) {
if mask & (1u128 << slot) != 0 {
judged.refusals.push((slot, why));
}
}
}
judged
}
}
/// [`snapshot_textures`]'s walk once its tables are charged: each slot of `own` the uses its
/// values reach leave out, added to `bad`.
fn reach(m: &TypedModule, own: &[u32], n: usize, bad: &mut Refused) -> Result<(), Error> {
let mut carried = vec![NONE; n];
let mut base: Vec<u32> = (0..n as u32).collect();
for g in m.globals() {
if let GlobalKind::Resource(slot) = &g.kind {
let texture = match slot.kind {
ResourceKind::Texture
| ResourceKind::CombinedTextureSampler(_)
| ResourceKind::YCbCrPlanes(_) => Some(slot.index),
ResourceKind::SeparateTexture(_) => slot.separate_texture_of().map(|(t, _)| t),
_ => None,
};
if let (Some(t), Some(c)) = (texture, carried.get_mut(g.value.index())) {
*c = t;
}
}
}
let mut mask = vec![0u128; n];
let mut memory = vec![0u128; n];
let mut function = vec![NONE; m.blocks().len()];
for (i, f) in m.functions().iter().enumerate() {
for b in &f.blocks {
if let Some(at) = function.get_mut(b.index()) {
*at = i as u32;
}
}
}
let mut returned = vec![0u128; m.functions().len()];
let mut arms = Arms::new(m);
let wanted: u128 = own.iter().fold(0, |acc, &s| acc | (1u128 << s));
let get = |table: &[u128], v: Value| table.get(v.index()).copied().unwrap_or(0);
for _ in 0..MOST_PASSES {
let mut changed = false;
for (at, b) in m.blocks().iter().enumerate() {
for phi in &b.phis {
let reach = phi
.incoming
.iter()
.fold(0, |acc, (v, _)| acc | get(&mask, *v));
changed |= join(&mut mask, phi.result, reach);
}
for node in &b.insts {
let mut operands: u128 = 0;
node.inst.for_each_value(|v| operands |= get(&mask, v));
match &node.inst {
// What carries a slot's image on, and the variable a pointer points into.
inst if carried_on(inst).is_some() => {
let (Some(r), Some(from)) = (node.result, carried_on(inst)) else {
continue;
};
if holds_image(m, r)? {
let slot = carried.get(from.index()).copied().unwrap_or(NONE);
if let Some(c) = carried.get_mut(r.index()).filter(|c| **c != slot) {
*c = slot;
changed = true;
}
}
let mut reach = operands;
if let Inst::Load { ptr, .. } = inst {
reach |= get(&memory, root(&base, *ptr));
}
if let Inst::Unary {
op: UnOp::CopyObject,
a,
} = inst
{
changed |= point(&mut base, r, *a);
}
changed |= join(&mut mask, r, reach);
}
Inst::ImageFetch { image, .. } => {
let slot = carried.get(image.index()).copied().unwrap_or(NONE);
let source = match slot {
s if s < 128 && wanted & (1u128 << s) != 0 => 1u128 << s,
_ => 0,
};
if let Some(r) = node.result {
changed |= join(&mut mask, r, operands | source);
}
}
Inst::AccessChain { base: from, .. } => {
if let Some(r) = node.result {
changed |= point(&mut base, r, *from);
changed |= join(&mut mask, r, operands);
}
}
// What a kept branch's arms store takes its condition's reach too.
Inst::Store { ptr, value, .. } => {
let reach = get(&mask, *value) | get(&mask, *ptr) | arms.control(at);
if kept_class(m, *ptr)? {
let root = root(&base, *ptr);
changed |= join(&mut memory, root, reach);
} else {
bad.add(SnapshotRefusal::Store, reach);
}
}
// Each argument to its parameter, a pointer argument's memory both ways, and the
// callee's returned reach to the result.
Inst::Call { func, args } => {
let params = m.functions().get(func.index()).map(|f| f.params.as_slice());
let Some(params) = params.filter(|p| p.len() == args.len()) else {
bad.add(SnapshotRefusal::Other, operands);
continue;
};
for (&arg, &param) in args.iter().zip(params) {
let reach = get(&mask, arg);
changed |= join(&mut mask, param, reach);
if matches!(m.types().get(m.value(arg)?.ty)?, Type::Pointer { .. }) {
let at = root(&base, arg);
let (caller, callee) = (get(&memory, at), get(&memory, param));
changed |= join(&mut memory, param, caller);
changed |= join(&mut memory, at, callee);
}
}
if let Some(r) = node.result {
let back = returned.get(func.index()).copied().unwrap_or(0);
changed |= join(&mut mask, r, back);
}
}
// A divisor, and a signed dividend beside a divisor that may be `-1`.
Inst::Binary {
op:
op @ (BinOp::UDiv | BinOp::SDiv | BinOp::UMod | BinOp::SRem | BinOp::SMod),
a,
b,
..
} => {
bad.add(SnapshotRefusal::UndefinedOperand, get(&mask, *b));
let unsigned = matches!(op, BinOp::UDiv | BinOp::UMod);
if !unsigned && !lanes_all(m, *b, |bits, ones| bits != ones)? {
bad.add(SnapshotRefusal::UndefinedOperand, get(&mask, *a));
}
if let Some(r) = node.result {
changed |= join(&mut mask, r, operands);
}
}
Inst::VectorExtractDynamic { index, .. }
| Inst::VectorInsertDynamic { index, .. } => {
bad.add(SnapshotRefusal::UndefinedOperand, get(&mask, *index));
if let Some(r) = node.result {
changed |= join(&mut mask, r, operands);
}
}
inst @ (Inst::Derivative { .. }
| Inst::ImageSample { .. }
| Inst::ImageGather { .. }
| Inst::ImageDrefGather { .. }
| Inst::ImageQueryLod { .. }
| Inst::Group { .. }
| Inst::Atomic { .. }
| Inst::AtomicLoad { .. }
| Inst::AtomicStore { .. }
| Inst::AtomicCompareExchange { .. }
| Inst::ImageWrite { .. }
| Inst::ImageTexelPointer { .. }
| Inst::RayQuery(_)
| Inst::SetMeshOutputs { .. }) => {
bad.add(refused_by(inst), operands);
if let Some(r) = node.result {
changed |= join(&mut mask, r, operands);
}
}
_ => {
if let Some(r) = node.result {
changed |= join(&mut mask, r, operands);
}
}
}
}
match &b.term {
// A selection whose arms a helper may take in place of a fragment's hands its
// condition's reach to its merge's phis and its arms' stores alone.
Terminator::CondBranch { cond: v, .. } | Terminator::Switch { sel: v, .. } => {
let reach = get(&mask, *v);
if reach != 0 {
match arms.keeps(m, at, reach)? {
Some((merge, grew)) => {
changed |= grew;
for phi in
m.blocks().get(merge.index()).map_or(&[][..], |b| &b.phis)
{
changed |= join(&mut mask, phi.result, reach);
}
}
None => bad.add(SnapshotRefusal::Branch, reach),
}
}
}
// A callee's returned value reaches its calls' results; the entry's, the stage.
Terminator::ReturnValue(v) => {
let f = function.get(at).copied().unwrap_or(NONE);
let reach = get(&mask, *v);
match f {
f if f == m.entry().func.index() as u32 => {
bad.add(SnapshotRefusal::Other, reach)
}
f => match returned.get_mut(f as usize) {
Some(r) if *r | reach != *r => {
*r |= reach;
changed = true;
}
Some(_) => {}
None => bad.add(SnapshotRefusal::Other, reach),
},
}
}
_ => {}
}
}
if !changed {
return Ok(());
}
}
bad.add(SnapshotRefusal::Other, wanted);
Ok(())
}
/// The clause an operand of `inst`, an instruction that leaves out every slot whose values reach
/// it, leaves them out for.
fn refused_by(inst: &Inst) -> SnapshotRefusal {
match inst {
Inst::Derivative { .. } => SnapshotRefusal::Derivative,
Inst::ImageSample { .. }
| Inst::ImageGather { .. }
| Inst::ImageDrefGather { .. }
| Inst::ImageQueryLod { .. } => SnapshotRefusal::Sample,
Inst::Group { .. } => SnapshotRefusal::GroupOperation,
Inst::Atomic { .. }
| Inst::AtomicLoad { .. }
| Inst::AtomicStore { .. }
| Inst::AtomicCompareExchange { .. } => SnapshotRefusal::Atomic,
Inst::ImageWrite { .. } | Inst::ImageTexelPointer { .. } => SnapshotRefusal::ImageWrite,
_ => SnapshotRefusal::Other,
}
}
/// Whether module `m`, compiled to read texture slots `slots` through snapshots
/// (`LoweringInputs::snapshot_textures`), reads each slot's texels in the entry's copy alone,
/// with the one `OpImageFetch` of the slot's image that copy makes. Every other use of the slot's
/// images is one that carries them
/// on or queries their size. A read the lowering left on the texture would race the draw's own
/// color writes, and shows here as a fetch the copy does not make. It charges `meter` for its
/// table while it holds it.
pub fn snapshot_copies_alone(
m: &TypedModule,
slots: &[u32],
meter: &mut Meter,
) -> Result<bool, Error> {
let n = m.values().len();
let table = 4 * n;
meter.charge(table)?;
let result = copies_alone(m, slots, n);
meter.release(table);
result
}
/// [`snapshot_copies_alone`] once its table is charged.
fn copies_alone(m: &TypedModule, slots: &[u32], n: usize) -> Result<bool, Error> {
let mut carried = vec![NONE; n];
for g in m.globals() {
if let GlobalKind::Resource(slot) = &g.kind {
let texture = match slot.kind {
ResourceKind::Texture
| ResourceKind::CombinedTextureSampler(_)
| ResourceKind::YCbCrPlanes(_) => Some(slot.index),
ResourceKind::SeparateTexture(_) => slot.separate_texture_of().map(|(t, _)| t),
_ => None,
};
if let (Some(t), Some(c)) = (texture, carried.get_mut(g.value.index())) {
*c = t;
}
}
}
let mut settled = false;
for _ in 0..MOST_PASSES {
let mut changed = false;
for node in m.blocks().iter().flat_map(|b| &b.insts) {
let (Some(r), Some(from)) = (node.result, carried_on(&node.inst)) else {
continue;
};
let slot = carried.get(from.index()).copied().unwrap_or(NONE);
if slot != NONE && holds_image(m, r)? {
if let Some(c) = carried.get_mut(r.index()).filter(|c| **c != slot) {
*c = slot;
changed = true;
}
}
}
if !changed {
settled = true;
break;
}
}
if !settled {
return Ok(false);
}
let watched = |v: Value| {
carried
.get(v.index())
.copied()
.filter(|s| slots.contains(s))
};
let mut fetches = vec![0u32; slots.len()];
let mut elsewhere = false;
for b in m.blocks() {
let merged = b
.phis
.iter()
.flat_map(|phi| phi.incoming.iter().map(|(v, _)| *v));
let returned = match &b.term {
Terminator::ReturnValue(v) => Some(*v),
_ => None,
};
if merged.chain(returned).any(|v| watched(v).is_some()) {
return Ok(false);
}
for node in &b.insts {
node.inst.for_each_value(|v| {
let Some(slot) = watched(v) else {
return;
};
match use_of(node, v) {
Use::NoTexel => {}
Use::Fetch { .. } => {
let at = slots.iter().position(|&s| s == slot);
if let Some(f) = at.and_then(|i| fetches.get_mut(i)) {
*f += 1;
}
}
Use::Elsewhere => elsewhere = true,
}
});
}
}
Ok(!elsewhere && fetches.iter().all(|&f| f == 1))
}
/// Add `reach` to `table[v]`; whether it grew.
fn join(table: &mut [u128], v: Value, reach: u128) -> bool {
match table.get_mut(v.index()) {
Some(t) if *t | reach != *t => {
*t |= reach;
true
}
_ => false,
}
}
/// Point pointer `r` into the variable `from` points into; whether that changed.
fn point(base: &mut [u32], r: Value, from: Value) -> bool {
let to = base
.get(from.index())
.copied()
.unwrap_or(from.index() as u32);
match base.get_mut(r.index()) {
Some(b) if *b != to => {
*b = to;
true
}
_ => false,
}
}
/// The value of the variable pointer `ptr` points into, as far as the passes found it.
fn root(base: &[u32], ptr: Value) -> Value {
let at = base.get(ptr.index()).copied().unwrap_or(ptr.index() as u32);
Value::new(at)
}
/// Whether `v` is a plain integer constant each of whose lanes' bits, within the lane's width,
/// pass `keep(bits, ones)`, `ones` every bit of the width set.
fn lanes_all(m: &TypedModule, v: Value, keep: impl Fn(u64, u64) -> bool) -> Result<bool, Error> {
let ValueOrigin::Const(c) = m.value(v)?.origin else {
return Ok(false);
};
let elem = match m.types().get(m.value(v)?.ty)? {
Type::Vector { elem, .. } => *elem,
_ => m.value(v)?.ty,
};
let Type::Int { width, .. } = m.types().get(elem)? else {
return Ok(false);
};
let ones = match *width {
64.. => u64::MAX,
w => (1u64 << w) - 1,
};
let lane = |bits: u64| keep(bits & ones, ones);
Ok(match &m.consts().get(c)?.kind {
ConstKind::Plain(Constant::Scalar { bits, .. }) => lane(bits.0),
ConstKind::Plain(Constant::Composite { parts, .. }) => parts
.iter()
.all(|part| m.consts().scalar_bits(*part).is_some_and(|b| lane(b.0))),
ConstKind::Plain(Constant::Null { .. }) => lane(0),
_ => false,
})
}
/// Whether a store through `ptr` keeps its value where the module's own loads read it alone: a
/// `Function`, `Private` or `Output` variable's.
fn kept_class(m: &TypedModule, ptr: Value) -> Result<bool, Error> {
let class = match m.types().get(m.value(ptr)?.ty)? {
Type::Pointer { class, .. } => *class,
_ => return Ok(false),
};
let origin_ok = !matches!(m.value(ptr)?.origin, ValueOrigin::Param { .. });
Ok(origin_ok
&& matches!(
class,
StorageClass::Function | StorageClass::Private | StorageClass::Output
))
}
@@ -1,279 +0,0 @@
//! Which branches on a snapshot slot's fetched value keep the slot: the selections whose arms hold
//! nothing a helper invocation's path through them could pass on (the module docs of
//! [`super`]).
//!
//! A selection's arms are the blocks a walk from its header's targets reaches before its merge
//! block, and the blocks of every function a call in them reaches. The branch keeps the slot only
//! where the walk leaves the arms through the merge alone: no arm block is the merge or continue
//! target of a construct the selection lies in (a loop's break or continue, a switch's break),
//! returns, ends the invocation (`OpKill`, `OpTerminateInvocation`) or is unreachable; and where
//! no arm block or callee holds a tangled instruction (`Inst::is_tangled`: an implicit-level
//! sample or level-of-detail query, a derivative, a subgroup or quad operation), a loop, or an
//! operand an instruction's behavior is undefined for at some value that is not a constant
//! (an integer divisor, a signed one that may be `-1`, a dynamic vector component index).
//!
//! The merge then post-dominates the header, so whatever follows it runs in a helper as in a
//! fragment, and what the arms leave behind is all a helper's other path can change: the merge's
//! phis and the `Function`, `Private` and `Output` variables an arm or its callees store to. Those
//! take the branch's reach ([`Arms::control`]), and the walk judges their uses as any other.
use crate::error::Error;
use crate::spirv::ids::BlockId;
use crate::spirv::ir::{BinOp, Block, Inst, Merge, Terminator, TypedModule, ValueOrigin};
use super::{lanes_all, NONE};
/// A block declared by more than one header.
const MANY: u32 = u32::MAX - 1;
/// A header's verdict, before it is judged.
const UNJUDGED: u8 = 0;
/// A header whose arms keep the slot.
const KEPT: u8 = 1;
/// A header whose arms leave it out.
const LEFT_OUT: u8 = 2;
/// The tables of the walks over a module's selections, one entry for each block or function.
pub(super) struct Arms {
/// The header that declares each block its merge or continue target, `NONE` for none, `MANY`
/// for more than one.
declared: Vec<u32>,
/// The walk that last reached each block, and each function.
walked: Vec<u32>,
walked_fn: Vec<u32>,
walks: u32,
/// Each header's verdict.
verdict: Vec<u8>,
/// The reach each kept header has handed its arms.
applied: Vec<u128>,
/// Each block's reach of the branches it is control dependent on: the slots whose fetched
/// values decide a kept branch whose arms hold it.
control: Vec<u128>,
/// The blocks a walk reached, and its open blocks and functions.
reached: Vec<u32>,
stack: Vec<BlockId>,
calls: Vec<u32>,
}
impl Arms {
/// The bytes the tables take for a module of `blocks` blocks and `functions` functions.
pub(super) fn bytes(blocks: usize, functions: usize) -> usize {
blocks * (4 + 4 + 1 + 16 + 16 + 4 + 4) + functions * (4 + 4)
}
/// The tables of module `m`.
pub(super) fn new(m: &TypedModule) -> Arms {
let blocks = m.blocks().len();
let mut declared = vec![NONE; blocks];
for (at, b) in m.blocks().iter().enumerate() {
let targets = match b.merge {
Some(Merge::Selection { merge }) => [Some(merge), None],
Some(Merge::Loop { merge, cont }) => [Some(merge), Some(cont)],
_ => [None, None],
};
for t in targets.into_iter().flatten() {
if let Some(d) = declared.get_mut(t.index()) {
*d = if *d == NONE { at as u32 } else { MANY };
}
}
}
Arms {
declared,
walked: vec![0; blocks],
walked_fn: vec![0; m.functions().len()],
walks: 0,
verdict: vec![UNJUDGED; blocks],
applied: vec![0; blocks],
control: vec![0; blocks],
reached: Vec::with_capacity(blocks),
stack: Vec::with_capacity(blocks),
calls: Vec::with_capacity(m.functions().len()),
}
}
/// The reach of the kept branches block `at` is control dependent on.
pub(super) fn control(&self, at: usize) -> u128 {
self.control.get(at).copied().unwrap_or(0)
}
/// Whether the branch ending block `header`, whose condition holds the fetched values of the
/// slots of `reach`, keeps them: its merge block where it does, which takes `reach` into its
/// phis, its arms taking it into [`Arms::control`] (and whether that grew); `None` where it
/// leaves them out.
pub(super) fn keeps(
&mut self,
m: &TypedModule,
header: usize,
reach: u128,
) -> Result<Option<(BlockId, bool)>, Error> {
let verdict = self.verdict.get(header).copied().unwrap_or(LEFT_OUT);
let applied = self.applied.get(header).copied().unwrap_or(0);
let merge = match verdict {
LEFT_OUT => return Ok(None),
KEPT if applied | reach == applied => {
return Ok(merge_of(m, header).map(|b| (b, false)))
}
_ => self.walk(m, header)?,
};
let Some(merge) = merge else {
if let Some(v) = self.verdict.get_mut(header) {
*v = LEFT_OUT;
}
return Ok(None);
};
if let Some(v) = self.verdict.get_mut(header) {
*v = KEPT;
}
if let Some(a) = self.applied.get_mut(header) {
*a |= reach;
}
let mut grew = false;
for &b in &self.reached {
if let Some(c) = self.control.get_mut(b as usize) {
grew |= *c | reach != *c;
*c |= reach;
}
}
Ok(Some((merge, grew)))
}
/// Walk the arms of the selection block `header` heads, recording the blocks reached in
/// `reached`: its merge block where the arms keep the slot, else `None`.
fn walk(&mut self, m: &TypedModule, header: usize) -> Result<Option<BlockId>, Error> {
let Some(merge) = merge_of(m, header) else {
return Ok(None);
};
let blocks = m.blocks();
self.walks += 1;
let w = self.walks;
self.reached.clear();
self.stack.clear();
self.calls.clear();
if let Some(s) = self.walked.get_mut(header) {
*s = w;
}
let Some(head) = blocks.get(header) else {
return Ok(None);
};
targets(&head.term, |t| self.stack.push(t));
while let Some(b) = self.stack.pop() {
let at = b.index();
if b == merge || (self.walked.get(at) == Some(&w) && at != header) {
continue;
}
// Back at the header, or at a merge or continue target of a construct the selection
// lies in: the arm leaves it.
let declared = self.declared.get(at).copied().unwrap_or(MANY);
let inner = declared == NONE || self.walked.get(declared as usize) == Some(&w);
if at == header || !inner {
return Ok(None);
}
if let Some(s) = self.walked.get_mut(at) {
*s = w;
}
let Some(block) = blocks.get(at) else {
return Ok(None);
};
if !self.clean(m, block, w)? {
return Ok(None);
}
match block.term {
Terminator::Branch(_)
| Terminator::CondBranch { .. }
| Terminator::Switch { .. } => {}
_ => return Ok(None),
}
self.reached.push(at as u32);
targets(&block.term, |t| self.stack.push(t));
}
// Every function a call in the arms reaches runs in them; its returns go back to them.
while let Some(f) = self.calls.pop() {
let Some(func) = m.functions().get(f as usize) else {
return Ok(None);
};
for &b in &func.blocks {
let Some(block) = blocks.get(b.index()) else {
return Ok(None);
};
if !self.clean(m, block, w)? {
return Ok(None);
}
match block.term {
Terminator::Branch(_)
| Terminator::CondBranch { .. }
| Terminator::Switch { .. }
| Terminator::Return
| Terminator::ReturnValue(_) => {}
_ => return Ok(None),
}
self.reached.push(b.index() as u32);
}
}
Ok(Some(merge))
}
/// Whether block `block` of walk `w` heads no loop and holds no tangled instruction and no
/// operand undefined at some value that is not a constant; each function it calls is queued.
fn clean(&mut self, m: &TypedModule, block: &Block, w: u32) -> Result<bool, Error> {
if matches!(block.merge, Some(Merge::Loop { .. })) {
return Ok(false);
}
for node in &block.insts {
let inst = &node.inst;
if inst.is_tangled() {
return Ok(false);
}
let defined = match inst {
Inst::Binary { op, b, .. } => match op {
BinOp::UDiv | BinOp::UMod => lanes_all(m, *b, |bits, _| bits != 0)?,
BinOp::SDiv | BinOp::SRem | BinOp::SMod => {
lanes_all(m, *b, |bits, ones| bits != 0 && bits != ones)?
}
_ => true,
},
Inst::VectorExtractDynamic { index, .. }
| Inst::VectorInsertDynamic { index, .. } => {
matches!(m.value(*index)?.origin, ValueOrigin::Const(_))
}
Inst::Call { func, .. } => {
if let Some(s) = self.walked_fn.get_mut(func.index()).filter(|s| **s != w) {
*s = w;
self.calls.push(func.index() as u32);
}
true
}
_ => true,
};
if !defined {
return Ok(false);
}
}
Ok(true)
}
}
/// The merge block of the selection block `header` heads, if it heads one.
fn merge_of(m: &TypedModule, header: usize) -> Option<BlockId> {
match m.blocks().get(header)?.merge {
Some(Merge::Selection { merge }) => Some(merge),
_ => None,
}
}
/// Call `f` on each block `term` may branch to.
fn targets(term: &Terminator, mut f: impl FnMut(BlockId)) {
match term {
Terminator::Branch(t) => f(*t),
Terminator::CondBranch { t, f: e, .. } => {
f(*t);
f(*e);
}
Terminator::Switch { default, cases, .. } => {
f(*default);
for &(_, t) in cases {
f(t);
}
}
_ => {}
}
}
@@ -1,663 +0,0 @@
//! [`snapshot_textures`] on hand-built fragment modules: a fetched value that reaches only
//! arithmetic and an output qualifies, directly, through a variable or through a call; one that
//! reaches a derivative, an implicit sample, a quad operation, an integer divisor or a dynamic
//! index, a store elsewhere, an atomic or an image write, directly, through a variable, or into
//! and out of a callee, does not; nor does a module with an interlock or a coherent resource, of a
//! function that writes memory, or a slot past 127. A selection on it qualifies where its arms
//! leave through its merge alone and hold nothing tangled, no loop and no undefined operand, and
//! what its arms leave behind reaches nothing that leaves the slot out. Each slot left out is
//! stated with the clauses that leave it out.
use super::snapshot_textures;
use crate::budget::{Budget, Meter};
use crate::pipeline::interface::SnapshotRefusal;
use crate::pipeline::sym::{CombinedSampler, ResourceKind, ResourceSlot, SamplerRef, Stage};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, KillForm, LoopSpec};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::ids::{TypeId, Value};
use crate::spirv::ir::{
natural_layout, AtomicOp, BinOp, ConstBits, Constant, ConvOp, DerivOp, Dim, ExecMode,
ExecModel, ImageOperands, ImageType, ImageUsage, IoDir, LayoutRule, MemAccess, QuadDirection,
Scope, Semantics, StorageClass, TexelMemory, Type, TypedModule,
};
/// Where slot 0's fetched value goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Sink {
/// Added to itself and stored to a `Private` variable.
Output,
/// Through a `Function` variable to the output.
ThroughVariable,
/// Its derivative stored to the output.
Derivative,
/// Through a `Function` variable to a derivative.
DerivativeThroughVariable,
/// Compared, and the comparison branched on.
Branch,
/// The coordinate of an implicit-level sample of slot 1.
SampleCoordinate,
/// An output, in a module whose entry also holds an interlock.
Interlocked,
/// Through a call whose callee returns its square.
ThroughCall,
/// Its derivative, of a call's result that returns it.
DerivativeOfCall,
/// Through a call whose callee branches on it.
BranchInCall,
/// Stored in a variable whose pointer a callee takes, loads through, and branches on.
BranchInCallThroughPointer,
/// Handed to a callee that stores it through a pointer the caller loads and branches on.
StoredByCallee,
/// Its bits the divisor of an unsigned division.
Divisor,
/// Its bits the dividend of an unsigned division by 3.
UnsignedDividend,
/// Its bits the dividend of a signed division by 3.
SignedDividend,
/// Its bits the dividend of a signed division by -1.
SignedDividendByMinusOne,
/// Its bits, masked, the index of a dynamic extract.
DynamicIndex,
/// The vector of a dynamic extract at a constant index.
DynamicVector,
/// Compared, and the invocation demoted where the comparison holds.
DemoteGuard,
/// Compared, and the invocation demoted in the else arm of the comparison.
DemoteInElse,
/// Compared, and the invocation demoted and the output written where the comparison holds.
DemoteAndStore,
/// Compared, the invocation demoted where the comparison holds, and the arms' different values
/// merged.
DemoteMergingValues,
/// Swapped across the quad.
QuadSwap,
/// Compared, and an arm on the comparison stores the position to a `Private` variable.
ArmStores,
/// Compared, and an arm on the comparison takes a derivative of the position.
ArmDerivative,
/// Compared, and an arm on the comparison calls a callee that takes a derivative.
ArmCallsDerivative,
/// Compared, and an arm on the comparison ends the invocation.
ArmKills,
/// Compared, and an arm on the comparison runs a loop.
ArmLoop,
/// Compared, and an arm on the comparison divides by the position's bits.
ArmDivides,
/// Compared, and a loop left where the comparison holds.
LoopExit,
/// Compared, an arm on the comparison storing to a `Function` variable whose value after the
/// merge reaches a derivative.
ArmToDerivative,
/// Compared, the arms' different values of the position merged and the merge's derivative
/// taken.
MergeToDerivative,
/// Its bits stored to a storage buffer's word.
StorageStore,
/// Its bits added to a storage buffer's word by an atomic.
AtomicAdd,
/// Written to a storage image of slot 3.
ImageWrite,
/// An output, in a module whose storage image of slot 3 is `Coherent`.
CoherentImage,
}
/// Whether lane 0 of `v` is above one half.
fn above_half(f: &mut FunctionBuilder<'_>, v: Value, f32_: TypeId) -> Value {
let x = f.composite_extract(v, &[0]).expect("x");
let half = scalar(f, f32_, u64::from(0.5f32.to_bits()));
f.binary(BinOp::FOrdGreaterThan, x, half).expect("compare")
}
/// Branch on whether lane 0 of `v` is above one half.
fn branch_on(f: &mut FunctionBuilder<'_>, v: Value, f32_: TypeId) {
let c = above_half(f, v, f32_);
let arm: crate::spirv::builder::constructs::ArmFn<'_, ()> =
Box::new(|_, _| Ok(ArmEnd::FallThrough(Vec::new())));
f.if_(&mut (), c, arm, None).expect("if");
}
fn scalar(f: &mut FunctionBuilder<'_>, ty: crate::spirv::ids::TypeId, bits: u64) -> Value {
let c = f
.module()
.constant(Constant::Scalar {
ty,
bits: ConstBits(bits),
})
.expect("constant");
f.module().const_value(c).expect("value")
}
fn module(sink: Sink) -> TypedModule {
let mut b = ModuleBuilder::new();
let u32_ = b
.ty(Type::Int {
width: 32,
signed: false,
})
.expect("uint");
let f32_ = b.ty(Type::Float { width: 32 }).expect("float");
let vec2 = b.ty(Type::Vector { elem: f32_, len: 2 }).expect("vec2");
let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 }).expect("vec4");
let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 }).expect("uvec2");
let image = b
.ty(Type::Image(ImageType {
sampled_type: f32_,
dim: Dim::D2,
depth: false,
arrayed: false,
multisampled: false,
usage: ImageUsage::Sampled,
format: crate::spv::ImageFormat::Unknown,
}))
.expect("image");
let sampled = b.ty(Type::SampledImage { image }).expect("sampled image");
let t = b
.resource(
ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::Texture,
index: 0,
},
StorageClass::UniformConstant,
image,
)
.expect("slot 0");
let u = b
.resource(
ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::CombinedTextureSampler(CombinedSampler::new(
SamplerRef::Slot(1),
false,
false,
)),
index: 1,
},
StorageClass::UniformConstant,
sampled,
)
.expect("slot 1");
// A storage buffer of words at buffer slot 2, and a float storage image at texture slot 3,
// for the sinks that write them.
let words = match sink {
Sink::StorageStore | Sink::AtomicAdd => {
let rta = b
.ty(Type::RuntimeArray {
elem: u32_,
stride: Some(4),
})
.expect("array");
let layout =
natural_layout(b.types(), LayoutRule::Std430, true, &[rta]).expect("layout");
let block = b
.ty(Type::Struct {
members: [rta].into(),
layout: Some(layout),
})
.expect("block");
let slot = ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::Buffer,
index: 2,
};
Some(
b.resource(slot, StorageClass::StorageBuffer, block)
.expect("slot 2"),
)
}
_ => None,
};
let storage = match sink {
Sink::ImageWrite | Sink::CoherentImage => {
let ty = b
.ty(Type::Image(ImageType {
sampled_type: f32_,
dim: Dim::D2,
depth: false,
arrayed: false,
multisampled: false,
usage: ImageUsage::Storage,
format: crate::spv::ImageFormat::Rgba32f,
}))
.expect("storage image");
let slot = ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::Texture,
index: 3,
};
let g = b
.resource(slot, StorageClass::UniformConstant, ty)
.expect("slot 3");
if sink == Sink::CoherentImage {
b.coherent(g).expect("coherent");
}
Some(g)
}
_ => None,
};
let out = b
.builtin(crate::spv::BuiltIn::FragCoord, IoDir::Input, vec4)
.expect("FragCoord");
let color = b
.plain_global(StorageClass::Private, vec4, None)
.expect("color");
let i32_ = b
.ty(Type::Int {
width: 32,
signed: true,
})
.expect("int");
let void = b.ty(Type::Void).expect("void");
let ptr = b
.ty(Type::Pointer {
class: StorageClass::Function,
pointee: vec4,
})
.expect("pointer");
let callee = match sink {
Sink::ArmCallsDerivative => {
let mut g = b.function(vec4).expect("routine");
let x = g.param(vec4).expect("x");
let d = g.derivative(DerivOp::DPdx, x).expect("derivative");
g.ret(Some(d)).expect("ret");
Some(g.finish().expect("callee"))
}
Sink::ThroughCall | Sink::DerivativeOfCall | Sink::BranchInCall => {
let mut g = b.function(vec4).expect("routine");
let x = g.param(vec4).expect("x");
let y = match sink {
Sink::BranchInCall => {
branch_on(&mut g, x, f32_);
x
}
_ => g.binary(BinOp::FMul, x, x).expect("square"),
};
g.ret(Some(y)).expect("ret");
Some(g.finish().expect("callee"))
}
Sink::BranchInCallThroughPointer => {
let mut g = b.function(void).expect("routine");
let p = g.param(ptr).expect("p");
let v = g.load(p, MemAccess::default()).expect("load");
branch_on(&mut g, v, f32_);
g.ret(None).expect("ret");
Some(g.finish().expect("callee"))
}
Sink::StoredByCallee => {
let mut g = b.function(void).expect("routine");
let p = g.param(ptr).expect("p");
let x = g.param(f32_).expect("x");
let zero = scalar(&mut g, u32_, 0);
let e = g.access_chain(p, &[zero]).expect("lane");
g.store(e, x, MemAccess::default()).expect("store");
g.ret(None).expect("ret");
Some(g.finish().expect("callee"))
}
_ => None,
};
let mut f = b.function(void).expect("main");
let tv = f.module().global_value(t).expect("t");
let uv = f.module().global_value(u).expect("u");
let position = f.module().global_value(out).expect("position");
let cv = f.module().global_value(color).expect("color");
let img = f.load(tv, MemAccess::default()).expect("t image");
let zero = scalar(&mut f, u32_, 0);
let coord = f.composite_construct(uvec2, &[zero, zero]).expect("coord");
let ops = ImageOperands {
lod: Some(zero),
..ImageOperands::default()
};
if sink == Sink::Interlocked {
f.begin_interlock().expect("begin");
}
let texel = f.fetch(img, coord, &ops).expect("fetch");
if sink == Sink::Interlocked {
f.end_interlock().expect("end");
}
let value = match sink {
Sink::Output | Sink::Interlocked | Sink::CoherentImage => {
f.binary(BinOp::FAdd, texel, texel).expect("sum")
}
Sink::QuadSwap => f
.group_quad_swap(texel, QuadDirection::Horizontal)
.expect("quad swap"),
Sink::StorageStore | Sink::AtomicAdd => {
let words = f
.module()
.global_value(words.expect("words"))
.expect("words");
let word = f.access_chain(words, &[zero, zero]).expect("word");
let x = f.composite_extract(texel, &[0]).expect("x");
let bits = f.convert(ConvOp::Bitcast, x, u32_).expect("bits");
match sink {
Sink::StorageStore => f.store(word, bits, MemAccess::default()).expect("store"),
_ => {
f.atomic(
AtomicOp::IAdd,
word,
Scope::Device,
Semantics::RELAXED,
bits,
)
.expect("atomic");
}
}
texel
}
Sink::ImageWrite => {
let g = f
.module()
.global_value(storage.expect("storage"))
.expect("image");
let image = f.load(g, MemAccess::default()).expect("storage image");
f.write(
image,
coord,
texel,
&ImageOperands::default(),
TexelMemory::Private { volatile: false },
)
.expect("write");
texel
}
Sink::ThroughVariable | Sink::DerivativeThroughVariable => {
let var = f.local_var(vec4, None).expect("var");
let p = f.var_ptr(var).expect("pointer");
f.store(p, texel, MemAccess::default()).expect("store");
let back = f.load(p, MemAccess::default()).expect("load");
match sink {
Sink::DerivativeThroughVariable => {
f.derivative(DerivOp::DPdx, back).expect("derivative")
}
_ => back,
}
}
Sink::Derivative => f.derivative(DerivOp::DPdx, texel).expect("derivative"),
Sink::Branch => {
branch_on(&mut f, texel, f32_);
texel
}
Sink::ThroughCall | Sink::BranchInCall | Sink::DerivativeOfCall => {
let callee = callee.expect("callee");
let r = f.call(callee, &[texel]).expect("call").expect("result");
match sink {
Sink::DerivativeOfCall => f.derivative(DerivOp::DPdx, r).expect("derivative"),
_ => r,
}
}
Sink::BranchInCallThroughPointer | Sink::StoredByCallee => {
let callee = callee.expect("callee");
let var = f.local_var(vec4, None).expect("var");
let p = f.var_ptr(var).expect("pointer");
if sink == Sink::StoredByCallee {
let x = f.composite_extract(texel, &[0]).expect("x");
f.call(callee, &[p, x]).expect("call");
let back = f.load(p, MemAccess::default()).expect("load");
branch_on(&mut f, back, f32_);
} else {
f.store(p, texel, MemAccess::default()).expect("store");
f.call(callee, &[p]).expect("call");
}
texel
}
Sink::Divisor | Sink::UnsignedDividend => {
let x = f.composite_extract(texel, &[0]).expect("x");
let bits = f.convert(ConvOp::Bitcast, x, u32_).expect("bits");
let other = scalar(&mut f, u32_, 3);
let (a, d) = match sink {
Sink::Divisor => (other, bits),
_ => (bits, other),
};
f.binary(BinOp::UDiv, a, d).expect("quotient");
texel
}
Sink::SignedDividend | Sink::SignedDividendByMinusOne => {
let x = f.composite_extract(texel, &[0]).expect("x");
let bits = f.convert(ConvOp::Bitcast, x, i32_).expect("bits");
let d = match sink {
Sink::SignedDividend => 3,
_ => u64::from(u32::MAX),
};
let d = scalar(&mut f, i32_, d);
f.binary(BinOp::SDiv, bits, d).expect("quotient");
texel
}
Sink::DynamicIndex | Sink::DynamicVector => {
let index = match sink {
Sink::DynamicIndex => {
let x = f.composite_extract(texel, &[0]).expect("x");
let bits = f.convert(ConvOp::Bitcast, x, u32_).expect("bits");
let three = scalar(&mut f, u32_, 3);
f.binary(BinOp::BitwiseAnd, bits, three).expect("index")
}
_ => zero,
};
f.vector_extract_dynamic(texel, index).expect("lane");
texel
}
Sink::DemoteGuard | Sink::DemoteAndStore => {
let c = above_half(&mut f, texel, f32_);
let store = sink == Sink::DemoteAndStore;
let arm: crate::spirv::builder::constructs::ArmFn<'_, ()> = Box::new(move |f, _| {
f.demote()?;
if store {
f.store(cv, texel, MemAccess::default())?;
}
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), c, arm, None).expect("if");
texel
}
Sink::DemoteInElse | Sink::DemoteMergingValues => {
let c = above_half(&mut f, texel, f32_);
let merging = sink == Sink::DemoteMergingValues;
let other = f.binary(BinOp::FAdd, texel, texel).expect("sum");
let kept: crate::spirv::builder::constructs::ArmFn<'_, ()> = Box::new(move |_, _| {
Ok(ArmEnd::FallThrough(match merging {
true => vec![other],
false => Vec::new(),
}))
});
let demoted: crate::spirv::builder::constructs::ArmFn<'_, ()> =
Box::new(move |f, _| {
f.demote()?;
Ok(ArmEnd::FallThrough(match merging {
true => vec![texel],
false => Vec::new(),
}))
});
let merged = f.if_(&mut (), c, kept, Some(demoted)).expect("if");
merged.0.first().copied().unwrap_or(texel)
}
Sink::ArmStores
| Sink::ArmDerivative
| Sink::ArmCallsDerivative
| Sink::ArmKills
| Sink::ArmLoop
| Sink::ArmDivides => {
let c = above_half(&mut f, texel, f32_);
let pos = f.load(position, MemAccess::default()).expect("position");
let arm: ArmFn<'_, ()> = Box::new(move |f, _| {
match sink {
Sink::ArmStores => f.store(cv, pos, MemAccess::default())?,
Sink::ArmDerivative => {
f.derivative(DerivOp::DPdx, pos)?;
}
Sink::ArmCallsDerivative => {
f.call(callee.expect("callee"), &[pos])?;
}
Sink::ArmKills => {
f.kill(KillForm::Kill)?;
return Ok(ArmEnd::Exits);
}
Sink::ArmLoop => {
f.loop_(
&mut (),
LoopSpec::default(),
Box::new(|f, _, exits| exits.break_(f)),
)?;
}
_ => {
let x = f.composite_extract(pos, &[0])?;
let bits = f.convert(ConvOp::Bitcast, x, u32_)?;
let three = scalar(f, u32_, 3);
f.binary(BinOp::UDiv, three, bits)?;
}
}
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), c, arm, None).expect("if");
texel
}
Sink::LoopExit => {
let c = above_half(&mut f, texel, f32_);
let body: crate::spirv::builder::constructs::LoopFn<'_, ()> =
Box::new(move |f, _, exits| {
let arm: ArmFn<'_, ()> = Box::new(move |f, _| {
exits.break_(f)?;
Ok(ArmEnd::Exits)
});
f.if_(&mut (), c, arm, None)?;
Ok(())
});
f.loop_(&mut (), LoopSpec::default(), body).expect("loop");
texel
}
Sink::ArmToDerivative | Sink::MergeToDerivative => {
let c = above_half(&mut f, texel, f32_);
let pos = f.load(position, MemAccess::default()).expect("position");
let twice = f.binary(BinOp::FAdd, pos, pos).expect("twice");
let left = match sink {
Sink::ArmToDerivative => {
let var = f.local_var(vec4, None).expect("var");
let p = f.var_ptr(var).expect("pointer");
f.store(p, pos, MemAccess::default()).expect("store");
let arm: ArmFn<'_, ()> = Box::new(move |f, _| {
f.store(p, twice, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), c, arm, None).expect("if");
f.load(p, MemAccess::default()).expect("load")
}
_ => {
let then: ArmFn<'_, ()> =
Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![pos])));
let other: ArmFn<'_, ()> =
Box::new(move |_, _| Ok(ArmEnd::FallThrough(vec![twice])));
let merged = f.if_(&mut (), c, then, Some(other)).expect("if");
merged.0.first().copied().expect("merged")
}
};
f.derivative(DerivOp::DPdx, left).expect("derivative");
texel
}
Sink::SampleCoordinate => {
let si = f.load(uv, MemAccess::default()).expect("u");
let xy = f.vector_shuffle(texel, texel, &[0, 1]).expect("xy");
let _ = vec2;
f.sample(si, xy, None, false, &ImageOperands::default())
.expect("sample")
}
};
f.store(cv, value, MemAccess::default()).expect("output");
f.ret(None).expect("ret");
let main = f.finish().expect("finish");
let modes = match sink {
Sink::Interlocked => vec![ExecMode::PixelInterlockOrdered],
_ => Vec::new(),
};
b.entry(ExecModel::Fragment, main, modes).expect("entry");
b.finalize().expect("finalize")
}
/// A fetched value that reaches arithmetic and a color output alone, directly, through a
/// `Function` variable or through a call, qualifies, as does an unsigned dividend, a signed one
/// beside a constant divisor without `-1`, and a dynamically indexed vector; a derivative of it,
/// directly, through a variable or of a call's result, an implicit sample at it, a quad swap of
/// it, a divisor, a signed dividend beside `-1`, a dynamic index, a store of it to a storage
/// buffer, an atomic of it, or an image write of it leaves the slot out, as does an interlock or a
/// coherent resource anywhere in the module. A selection on it qualifies, in the entry or in a
/// callee it reaches as an argument, through a pointer argument's memory or back out of it: with
/// an arm that is empty, demotes (in either arm, also writing, or with the arms' values merging
/// apart) or stores to a `Private` variable. One whose arm takes a derivative or calls a function
/// that does, ends the invocation, runs a loop or divides by a value that is not a constant leaves
/// the slot out for its branch, as does a loop it leaves; one whose arm's store or whose merge's
/// phi reaches a derivative, for the derivative. Each slot left out is stated with the one clause
/// that leaves it out. The analysis releases every charge.
#[test]
fn only_values_no_helper_can_pass_on_qualify() {
use SnapshotRefusal as R;
for (sink, refused) in [
(Sink::Output, None),
(Sink::ThroughVariable, None),
(Sink::Derivative, Some(R::Derivative)),
(Sink::DerivativeThroughVariable, Some(R::Derivative)),
(Sink::Branch, None),
(Sink::SampleCoordinate, Some(R::Sample)),
(Sink::Interlocked, Some(R::Interlock)),
(Sink::ThroughCall, None),
(Sink::DerivativeOfCall, Some(R::Derivative)),
(Sink::BranchInCall, None),
(Sink::BranchInCallThroughPointer, None),
(Sink::StoredByCallee, None),
(Sink::Divisor, Some(R::UndefinedOperand)),
(Sink::UnsignedDividend, None),
(Sink::SignedDividend, None),
(Sink::SignedDividendByMinusOne, Some(R::UndefinedOperand)),
(Sink::DynamicIndex, Some(R::UndefinedOperand)),
(Sink::DynamicVector, None),
(Sink::DemoteGuard, None),
(Sink::DemoteInElse, None),
(Sink::DemoteAndStore, None),
(Sink::DemoteMergingValues, None),
(Sink::ArmStores, None),
(Sink::ArmDerivative, Some(R::Branch)),
(Sink::ArmCallsDerivative, Some(R::Branch)),
(Sink::ArmKills, Some(R::Branch)),
(Sink::ArmLoop, Some(R::Branch)),
(Sink::ArmDivides, Some(R::Branch)),
(Sink::LoopExit, Some(R::Branch)),
(Sink::ArmToDerivative, Some(R::Derivative)),
(Sink::MergeToDerivative, Some(R::Derivative)),
(Sink::QuadSwap, Some(R::GroupOperation)),
(Sink::StorageStore, Some(R::Store)),
(Sink::AtomicAdd, Some(R::Atomic)),
(Sink::ImageWrite, Some(R::ImageWrite)),
(Sink::CoherentImage, Some(R::Coherent)),
] {
let mut meter = Meter::new(&Budget::default());
let judged = snapshot_textures(&module(sink), &[0], false, &mut meter).expect("analysis");
assert_eq!(meter.ledger(), 0, "{sink:?}: every charge released");
let (slots, refusals): (&[u32], Vec<(u32, SnapshotRefusal)>) = match refused {
None => (&[0], Vec::new()),
Some(why) => (&[], vec![(0, why)]),
};
assert_eq!(judged.slots, slots, "{sink:?}");
assert_eq!(judged.refusals, refusals, "{sink:?}");
}
}
/// A function that writes memory leaves every slot out for it, beside what the walk finds of its
/// values: the qualifying output alone, and the derivative too. A slot past 127 is left out
/// unwalked, beside a slot below it that qualifies.
#[test]
fn a_slot_left_out_by_the_function_or_its_index_says_so() {
use SnapshotRefusal as R;
let mut meter = Meter::new(&Budget::default());
let mut judged = |sink: Sink, own: &[u32], writes: bool| {
snapshot_textures(&module(sink), own, writes, &mut meter).expect("analysis")
};
let written = judged(Sink::Output, &[0], true);
assert!(written.slots.is_empty(), "writes memory");
assert_eq!(written.refusals, [(0, R::WritesMemory)], "writes memory");
let both = judged(Sink::Derivative, &[0], true);
assert_eq!(
both.refusals,
[(0, R::Derivative), (0, R::WritesMemory)],
"writes memory, and a derivative"
);
let past = judged(Sink::Output, &[0, 200], false);
assert_eq!(past.slots, [0], "slot 0 qualifies");
assert_eq!(past.refusals, [(200, R::Other)], "slot 200 is not walked");
assert_eq!(meter.ledger(), 0, "every charge released");
}
@@ -24,17 +24,10 @@
//! The trace also ends at an `OpIAdd` whose one operand is a load of the address member, whatever
//! the other: the guest does not hold the address, so no sum of the guest's has such an operand.
//!
//! The shader-side stencil's shadow (`Synthetic(ShadowStencil)`) is the product's too: its writes
//! carry Metal's stencil test, which Metal applies per sample whether the function runs per pixel
//! or per sample, so they do not make the function run per sample. An image write counts unless its
//! image is a load of that binding.
//!
//! So is a color attachment's interlocked storage form (`TileAttachment`): its writes carry
//! Metal's color attachment write, a
//! color output, which Metal masks as it masks any (a sample mask, a failed test) and stores per
//! sample whether the function runs per pixel or per sample, and which no other invocation or
//! command reads but through the attachment. A multisampled pipeline's storage form runs per sample
//! by its own `SampleId`. The function's other writes count as before.
//! A tile function's color attachment (`TileAttachment`) is the product's too: its writes carry
//! Metal's color attachment write, a color output, which no other invocation or command reads but
//! through the attachment. An image write counts unless its image is a load of that binding. The
//! function's other writes count as before.
#[cfg(test)]
mod tests;
@@ -93,8 +86,7 @@ fn class(m: &TypedModule, ptr: Value) -> BResult<StorageClass> {
struct Status<'m> {
/// The variables of the `Synthetic(ExecutionStatus)` binding.
bindings: Vec<Value>,
/// The variables of the `Synthetic(ShadowStencil)`, `TileAttachment` and `SnapshotTexels`
/// bindings, and the loads of them.
/// The variables of the `TileAttachment` bindings, and the loads of them.
shadows: Vec<Value>,
/// The push block's variable.
block: Option<Value>,
@@ -119,12 +111,7 @@ impl<'m> Status<'m> {
s.bindings.push(g.value);
}
GlobalKind::Resource(slot)
if matches!(
slot.kind,
ResourceKind::Synthetic(SyntheticBinding::ShadowStencil)
| ResourceKind::TileAttachment(_)
| ResourceKind::SnapshotTexels(_)
) =>
if matches!(slot.kind, ResourceKind::TileAttachment(_)) =>
{
s.shadows.push(g.value);
}
@@ -178,8 +165,8 @@ impl<'m> Status<'m> {
Ok(s)
}
/// Whether image `image` is the product's (the shadow of a shader-side stencil, the depth's
/// stand-in, a color's storage form or `half` shadow): a load of its binding.
/// Whether image `image` is the product's (a tile function's color attachment): a load of its
/// binding.
fn shadow(&self, image: Value) -> bool {
self.shadows.contains(&image)
}
@@ -234,20 +234,10 @@ fn image_write(kind: ResourceKind) -> TypedModule {
fragment(b, main)
}
/// The shader-side stencil's shadow is the product's, so its writes do not make the function run
/// per sample; a write of another storage image (the function's texture) does.
#[test]
fn the_shadow_stencils_writes_are_not_the_functions() {
let shadow = ResourceKind::Synthetic(SyntheticBinding::ShadowStencil);
assert!(!writes_memory(&image_write(shadow)).expect("shadow"));
let imageblock = ResourceKind::Synthetic(SyntheticBinding::Imageblock);
assert!(writes_memory(&image_write(imageblock)).expect("another image"));
}
/// A color's interlocked storage form is the product's, carrying Metal's color attachment write,
/// A tile function's color attachment is the product's, carrying Metal's color attachment write,
/// so its writes are not the function's; a texture's write is.
#[test]
fn a_colors_storage_form_writes_are_not_the_functions() {
fn a_tile_attachments_writes_are_not_the_functions() {
let color = ResourceKind::TileAttachment(2);
assert!(!writes_memory(&image_write(color)).expect("color"));
assert!(writes_memory(&image_write(ResourceKind::Texture)).expect("a texture"));
@@ -5,7 +5,7 @@
use crate::bind::{
ArgumentFunctionTable, ArgumentSampler, BindState, BoundBuffer, BoundSampler, BoundTexture,
BufferRanges, FragmentTests, ImageblockSize, ResourceClass, SamplerDescriptor, StageTable,
BufferRanges, ImageblockSize, ResourceClass, SamplerDescriptor, StageTable,
TessellationFactorBuffer, TessellationFactors, TextureFacts, TileThreadgroupArgument,
TileThreadgroupMemory, UsedResource, VertexAmplification,
};
@@ -247,10 +247,6 @@ fn states() -> Vec<BindState> {
}),
with(|s| s.kept_imageblock_bytes = Some(8)),
with(|s| s.depth_clamp_range = Some([0.0, 1.0])),
with(|s| {
s.interlocked_colors.insert(1);
}),
with(|s| s.fragment_tests = FragmentTests::Pass),
with(|s| s.quad_primitive_ids = true),
with(|s| s.private_list = true),
]
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more