A new memoryless texture's first move clears it to zero in render passes

What: Device::new_texture_image gives a new memoryless texture whose memory
is not lazily allocated its zeros at its first move (zero_memoryless). A
transient attachment takes no transfer, so for each level a render pass of
that level's view alone (render_target::clear_alone, the reach clears' pass
shape, loaded and stored in GENERAL) clears every aspect with
vkCmdClearAttachments over its layers, in runs of the device's framebuffer
layers. FirstMove::zero_in_passes holds the passes and framebuffers until
the submission that records them completes, and Taken::record follows them
with a barrier from every stage. A level larger than the device's
framebuffers is no pass's attachment and takes none. Counted:
WorkCounts::memoryless_textures_zeroed (a new public field, signatures
re-blessed). Lazily allocated memoryless memory (MoltenVK) keeps what it
does today. tests::memoryless_fresh now also asserts the count.

Why: a memoryless texture held what its image's memory held, and its first
pass's DontCare load kept that, where the depth and stencil tests or a
resolve read it. That memory may hold a released texture's samples, of
another process of a consumer whose processes share the device. A per-pass
clear of every DontCare memoryless depth cost the Iris Xe 1.17 ms a 4x
1080p pass (job 24160); one clear at the first move costs the texture's
first frame alone, and later passes load as before.

Verified: tests::memoryless_fresh and the runtime suite on lavapipe, and the
Iris's MEMORYLESS-COST, reported with this sha.
This commit is contained in:
Anees Iqbal committed 2026-11-12 21:16:23 -08:00
1 parent f489825ff1
commit 5cd01cff8e
6 files changed
+262 -30

No files matched your search

@@ -1577,24 +1577,31 @@ pub(super) fn later_resolve(
Ok((pass, framebuffer))
}
/// The render pass and framebuffer in which `vkCmdClearAttachments` clears `target`, a pass's
/// attachment (its depth/stencil attachment where `depth_stencil`), over `extent` from the origin
/// before its pass (`clear_reach.rs`), and the uses they make: one subpass of the attachment
/// alone, over the pass's layers, every aspect loaded and stored. Not a load operation's clear: a
/// device that renders through Metal (MoltenVK) clears a pass without a draw over the whole
/// attachment, as Metal does (lane `clear_reach` on MoltenVK).
pub(super) fn reach_pass(
/// The render pass of one attachment of `format` and `samples` alone (its depth/stencil
/// attachment where `depth_stencil`), every aspect loaded and stored, in `GENERAL`, in which
/// `vkCmdClearAttachments` clears it ([`reach_pass`], [`clear_alone`]); and the usage, stages and
/// accesses of the attachment there.
fn alone_pass(
device: &Device,
target: &Target,
format: metal2vulkan::vk::Format,
samples: u32,
depth_stencil: bool,
extent: [u32; 2],
) -> Result<(RenderPassObject, FramebufferObject, Vec<Use<ResourceKey>>), Error> {
) -> Result<
(
RenderPassObject,
metal2vulkan::vk::ImageUsageFlags,
vk::PipelineStageFlags2,
vk::AccessFlags2,
vk::AccessFlags2,
),
Error,
> {
let load = vk::AttachmentLoadOp::LOAD;
let store = vk::AttachmentStoreOp::STORE;
let shape = PassShape {
colors: ColorList::new(),
depth_stencil: None,
samples: target.samples,
samples,
color_resolves: ColorList::new(),
depth_stencil_resolve: None,
fetch_inputs: false,
@@ -1603,10 +1610,10 @@ pub(super) fn reach_pass(
view_mask: 0,
locations: ColorList::new(),
};
let (pass, usage, stages, read, write) = match depth_stencil {
let made = match depth_stencil {
false => {
let shape = PassShape {
colors: ColorList::of([Some(target.format)])?,
colors: ColorList::of([Some(format)])?,
color_resolves: ColorList::of([None])?,
..shape
};
@@ -1636,7 +1643,7 @@ pub(super) fn reach_pass(
}
true => {
let shape = PassShape {
depth_stencil: Some(target.format),
depth_stencil: Some(format),
..shape
};
let ops = Ops {
@@ -1664,6 +1671,39 @@ pub(super) fn reach_pass(
)
}
};
Ok(made)
}
/// The render pass and framebuffer in which `vkCmdClearAttachments` clears every aspect of
/// `view`, a view of one level and `layers` layers of an image of `format` and `samples`, over
/// `extent` from the origin: [`alone_pass`]'s pass. A new memoryless image's zeros, which no
/// transfer writes into a transient attachment (`Device::new_texture_image`, `FirstMove::zero_in_passes`).
pub(super) fn clear_alone(
device: &Device,
(format, samples, depth_stencil): (metal2vulkan::vk::Format, u32, bool),
view: vk::ImageView,
extent: [u32; 2],
layers: u32,
) -> Result<(RenderPassObject, FramebufferObject), Error> {
let (pass, ..) = alone_pass(device, format, samples, depth_stencil)?;
let framebuffer = made_framebuffer(device, &pass, &[view], extent, layers)?;
Ok((pass, framebuffer))
}
/// The render pass and framebuffer in which `vkCmdClearAttachments` clears `target`, a pass's
/// attachment (its depth/stencil attachment where `depth_stencil`), over `extent` from the origin
/// before its pass (`clear_reach.rs`), and the uses they make: one subpass of the attachment
/// alone, over the pass's layers, every aspect loaded and stored. Not a load operation's clear: a
/// device that renders through Metal (MoltenVK) clears a pass without a draw over the whole
/// attachment, as Metal does (lane `clear_reach` on MoltenVK).
pub(super) fn reach_pass(
device: &Device,
target: &Target,
depth_stencil: bool,
extent: [u32; 2],
) -> Result<(RenderPassObject, FramebufferObject, Vec<Use<ResourceKey>>), Error> {
let (pass, usage, stages, read, write) =
alone_pass(device, target.format, target.samples, depth_stencil)?;
let framebuffer = made_framebuffer(
device,
&pass,
@@ -6,8 +6,10 @@
//! `Depth32Float` depth, each cleared by a pass of no draw call and resolved, then released, and
//! a memoryless texture of the same descriptor made: it takes the parked image
//! (`WorkCounts::object_churn.images_recycled`), and a pass of no draw call that loads it
//! `DontCare` and resolves it writes zero into its resolve texture, never the earlier clear.
//! Its resolve is the only command that reads it.
//! `DontCare` and resolves it writes zero into its resolve texture, never the earlier clear,
//! its making counted (`WorkCounts::memoryless_textures_zeroed`). Its resolve is the only
//! command that reads it. Where memoryless memory is lazily allocated (MoltenVK) nothing is
//! zeroed and the reading is printed alone.
//! - **Cost** (a measurement, ignored): the GPU span of one such pass over a 1920x1080 4x
//! attachment, made once and passed again and again (each pass after its first),
//! `MEMORYLESS-COST`.
@@ -164,7 +166,9 @@ fn a_recycled_memoryless_texture_s_resolve_reads_zero_never_the_old_samples() {
assert!(Instant::now() < until, "{pf:?}: the image was parked");
std::thread::yield_now();
}
let zeroed = device.work_counts().memoryless_textures_zeroed;
let second = device.new_texture(&memoryless(pf, SIDE, SIDE)).unwrap();
let zeroed = device.work_counts().memoryless_textures_zeroed - zeroed;
let after = device.work_counts().object_churn;
assert_eq!(
after.images_recycled - before.images_recycled,
@@ -183,6 +187,13 @@ fn a_recycled_memoryless_texture_s_resolve_reads_zero_never_the_old_samples() {
(false, false) => "other bytes",
};
println!("MEMORYLESS-FRESH {pf:?} on {}: {what}", device.name());
// Lazily allocated memoryless memory (MoltenVK) holds nothing past a pass and is not
// zeroed.
if second.lazily_allocated() {
assert_eq!(zeroed, 0, "{pf:?}: a lazily allocated texture zeroed");
continue;
}
assert_eq!(zeroed, 1, "{pf:?}: the making counted as zeroed");
assert_eq!(what, "zero", "{pf:?}");
}
}
+94 -12
View File
@@ -128,7 +128,9 @@ use crate::release;
use ash::vk;
use ash::vk::Handle;
use decoded_twin::{Decoded, PassScratch};
use first_move::{FirstMove, Fresh, GpuKeep, Mine, Pattern, Patterned, TexelCopy, PATTERN_BYTES};
use first_move::{
FirstMove, Fresh, GpuKeep, Mine, PassClear, Pattern, Patterned, TexelCopy, PATTERN_BYTES,
};
use heap_tiled::{FreshDepth, FreshPattern};
use heap_two_planes::TwoPlaneHeapLayout;
use metal2vulkan::bind::{AstcDecode, EtcDecode, ImageViewDesc, PvrtcDecode, TextureFacts};
@@ -1190,6 +1192,19 @@ impl Image {
self.form.plan().unwrap_or(&self.plan)
}
/// Whether it lies in lazily allocated memory: a memoryless texture's, where the device has
/// such memory (`image_plan.rs`). MoltenVK runs such an image as Metal's memoryless storage,
/// which keeps no texels past the render pass that renders them.
fn lazily_allocated(&self) -> bool {
let (_, placement) = self.owner.releases();
placement.is_some_and(|placement| {
let memory = lock(&self.device.shared().memory);
memory
.type_flags(placement.type_index())
.is_some_and(|flags| flags.contains(vk::MemoryPropertyFlags::LAZILY_ALLOCATED))
})
}
/// Count, under the views lock, that the image lets its views go, or that its texture, a
/// shadow, moved in place (`texture/storage_form.rs`): the views a bind kept by what they
/// were made of are then stale (`DeviceShared::views_epoch`).
@@ -3948,7 +3963,10 @@ impl Device {
/// [`new_image`](Self::new_image)'s image for a texture of its own memory the program made
/// (`newTextureWithDescriptor:`, `newSharedTextureWithDescriptor:`), as Metal's new texture
/// starts on the Mac the device presents (`MacClass`). `Shared` and `Managed` ones read zero
/// in every texel, and a `Memoryless` one holds nothing. A `Private` one, on a device that
/// in every texel. A `Memoryless` one holds nothing past a pass on Metal; where its memory is
/// not lazily allocated, its first move clears it to zero in render passes
/// ([`zero_memoryless`](Self::zero_memoryless)), so a first pass that loads it `DontCare`
/// never reads what its memory held. A `Private` one, on a device that
/// presents a Mac keeping textures compressed
/// ([`metal_compresses_textures`](Self::metal_compresses_textures)), reads zero where Metal
/// keeps it uncompressed and Metal's fixed pattern where it compresses it (an Apple M4 under
@@ -3994,9 +4012,82 @@ impl Device {
if uncompressed {
self.shared().counts.private_texture_zero_filled();
}
if memoryless && !image.lazily_allocated() {
self.zero_memoryless(&image)?;
}
Ok(image)
}
/// Give `image`, a new memoryless texture's in memory that is not lazily allocated, its
/// zeros at its first move: a transient attachment takes no transfer, so a render pass of
/// each level's view alone clears every aspect over its layers (in runs of the device's
/// framebuffer layers), counted (`WorkCounts::memoryless_textures_zeroed`). A level larger
/// than the device's framebuffers is no pass's attachment, which no command reads, and takes
/// none.
fn zero_memoryless(&self, image: &Image) -> Result<(), Error> {
let plan = &image.plan;
let aspect = image_aspects(plan.format);
let depth_stencil = !aspect.contains(ImageAspectFlags::COLOR);
let usage = match depth_stencil {
true => ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT,
false => ImageUsageFlags::COLOR_ATTACHMENT,
};
let one_d = plan.image_type == metal2vulkan::vk::ImageType::TYPE_1D;
let volume = plan.image_type == metal2vulkan::vk::ImageType::TYPE_3D;
let [max_width, max_height, max_layers] = self.shared().max_framebuffer;
let shape = (plan.format, plan.samples.as_raw(), depth_stencil);
let mut passes = Vec::new();
for level in 0..plan.levels {
let extent = [
(plan.extent[0] >> level).max(1),
(plan.extent[1] >> level).max(1),
];
if extent[0] > max_width || extent[1] > max_height {
continue;
}
// A 3D image's depth planes are its attachments' layers (a 2D-array-compatible one).
let layers = match volume {
true => (plan.extent[2] >> level).max(1),
false => plan.layers,
};
let mut base = 0;
while base < layers {
let count = (layers - base).min(max_layers.max(1));
let view_type = match (one_d, count > 1) {
(true, true) => ImageViewType::TYPE_1D_ARRAY,
(true, false) => ImageViewType::TYPE_1D,
(false, true) => ImageViewType::TYPE_2D_ARRAY,
(false, false) => ImageViewType::TYPE_2D,
};
let view = image.own_view(&VkView {
view_type,
format: plan.format,
components: ComponentMapping::IDENTITY,
aspect,
base_level: level,
level_count: 1,
base_layer: base,
layer_count: count,
usage,
})?;
let (pass, framebuffer) =
crate::render_target::clear_alone(self, shape, view, extent, count)?;
passes.push(PassClear {
pass,
framebuffer,
extent,
layers: count,
});
base += count;
}
}
if let Some(first) = lock(&image.first_move).as_mut() {
first.zero_in_passes(passes);
self.shared().counts.memoryless_texture_zeroed();
}
Ok(())
}
/// Whether the Mac this device presents keeps textures losslessly compressed, as an Apple
/// silicon Mac's GPU does (`texture/heap_tiled.rs`, `metal_compresses`;
/// `DeviceProperties::lossless_compression`, decided in one place, `capabilities.rs`). The
@@ -5835,16 +5926,7 @@ impl Texture {
/// where the device has such memory (`image_plan.rs`). MoltenVK runs such an image as Metal's
/// memoryless storage, which keeps no texels past the render pass that renders them.
pub(super) fn lazily_allocated(&self) -> bool {
let Ok(image) = self.image() else {
return false;
};
let (_, placement) = image.owner.releases();
placement.is_some_and(|placement| {
let memory = lock(&image.device.shared().memory);
memory
.type_flags(placement.type_index())
.is_some_and(|flags| flags.contains(vk::MemoryPropertyFlags::LAZILY_ALLOCATED))
})
self.image().is_ok_and(|image| image.lazily_allocated())
}
/// The texture's `VkImage`; refused as [`image`](Self::image) is.
@@ -15,7 +15,9 @@
//! `Managed` texture, a stand-in) with the copies of the device's zeros ([`Zeros`]) that write
//! every texel. A new texture of every storage mode but `Memoryless` reads zero, a `Private` one
//! too; its image of a format a clear writes is cleared ([`FirstMove::cleared`]) rather than
//! copied over, single- or multisampled. An image that takes a rebind's new `VkImage` notes that
//! copied over, single- or multisampled. A new `Memoryless` one in memory that is not lazily
//! allocated is cleared to zero in render passes of each level alone
//! ([`FirstMove::zero_in_passes`]), as no transfer writes a transient attachment. An image that takes a rebind's new `VkImage` notes that
//! one's (`rebind.rs`). The image (or stand-in) is registered weakly once it is shared
//! ([`FirstMoves::register`]); an image that copies on the device's staging queue queues its
//! move and zeros there instead, which every submission of the device's makes there before its
@@ -158,6 +160,7 @@ use super::super::heap_sets::HeldSlots;
use super::super::image_barrier::{image_barrier, ImageDst};
use super::super::memory::{Memory, MemoryClass, Placement};
use super::super::release;
use super::super::render_target::{FramebufferObject, RenderPassObject};
use super::super::resource::{ObjectId, ResourceKey};
use super::super::tracker::Point;
use super::super::work_counts::Counters;
@@ -438,6 +441,19 @@ impl FirstMove {
self
}
/// Have the move also clear every texel of every aspect to zero in `passes`, which cover every
/// level and layer a pass may attach: a new memoryless texture's image, a transient
/// attachment, which no transfer writes (`Device::new_texture_image`).
pub(crate) fn zero_in_passes(&mut self, passes: Vec<PassClear>) {
self.zero = Some(Zero::Passes(passes));
}
/// Whether its zeros are written in render passes ([`zero_in_passes`](Self::zero_in_passes)):
/// the barrier after them is from the attachments' stages.
fn clears_in_passes(&self) -> bool {
matches!(self.zero, Some(Zero::Passes(_)))
}
/// The move, which also writes `patterned`'s pattern into its levels; its zeros then write
/// only the levels after them. Its zeros' copies, if any, cover every level from the first.
pub(crate) fn patterned(mut self, patterned: Patterned) -> FirstMove {
@@ -515,6 +531,48 @@ impl FirstMove {
exit_guard::called(Call::CmdCopyBufferToImage);
}
}
Some(Zero::Passes(passes)) => {
let attachments = [vk::ClearAttachment {
aspect_mask: self.aspects,
color_attachment: 0,
clear_value: vk::ClearValue::default(),
}];
for clear in passes {
let [width, height] = clear.extent;
let area = vk::Rect2D {
offset: vk::Offset2D { x: 0, y: 0 },
extent: vk::Extent2D { width, height },
};
let begin = vk::RenderPassBeginInfo::default()
.render_pass(clear.pass.raw)
.framebuffer(clear.framebuffer.raw)
.render_area(area);
let rects = [vk::ClearRect {
rect: area,
base_array_layer: 0,
layer_count: clear.layers,
}];
// SAFETY: the caller's; the command buffer is outside a render pass, of a
// family with graphics (every queue but the staging queue's, which records no
// such move: a memoryless image copies nothing there); the pass and its
// framebuffer, of a view of the image's level and layers in `GENERAL`, the
// pass's layout, live as long as the move, which the submission holds until
// it completed; the aspects are the image format's, the subpass's one
// attachment's; the rectangle is the framebuffer's area and its layers.
unsafe {
device.cmd_begin_render_pass(
command_buffer,
&begin,
vk::SubpassContents::INLINE,
);
device.cmd_clear_attachments(command_buffer, &attachments, &rects);
device.cmd_end_render_pass(command_buffer);
}
exit_guard::called(Call::CmdBeginRenderPass);
exit_guard::called(Call::CmdClearAttachments);
exit_guard::called(Call::CmdEndRenderPass);
}
}
Some(Zero::Clear) if !past_pattern => {}
Some(Zero::Clear) if self.aspects.contains(vk::ImageAspectFlags::COLOR) => {
let black = vk::ClearColorValue::default();
@@ -729,6 +787,18 @@ enum Zero {
Copies(vk::Buffer, Vec<vk::BufferImageCopy>),
/// A clear ([`FirstMove::cleared`]).
Clear,
/// Clears in render passes ([`FirstMove::zero_in_passes`]).
Passes(Vec<PassClear>),
}
/// A clear of one level of an image, over `extent` and `layers` layers from its first, in a
/// render pass of the attachment alone and its framebuffer of a view of them
/// (`render_target::clear_alone`), which the move holds ([`FirstMove::zero_in_passes`]).
pub(crate) struct PassClear {
pub(crate) pass: RenderPassObject,
pub(crate) framebuffer: FramebufferObject,
pub(crate) extent: [u32; 2],
pub(crate) layers: u32,
}
/// The most bytes host calls' copies stage for the device's next submission before one is made
@@ -2160,7 +2230,7 @@ impl<'a> Taken<'a> {
}
for first in moves().filter(|first| first.writes()) {
// SAFETY: as above; the image is in `GENERAL` now and has `TRANSFER_DST` usage where
// it reads zero.
// it reads zero by a transfer.
unsafe { first.record_zero(device, command_buffer, family) };
copied = true;
}
@@ -2168,6 +2238,16 @@ impl<'a> Taken<'a> {
transfer_barrier(device, command_buffer, false);
exit_guard::called(Call::CmdPipelineBarrier);
}
// Zeros cleared in render passes, from their attachments' stages, visible to every
// command after.
if moves().any(FirstMove::clears_in_passes) {
// SAFETY: the caller's contract.
unsafe {
let flags = vk::DependencyFlags::empty();
device.cmd_pipeline_barrier(command_buffer, all, all, flags, &written(), &[], &[]);
}
exit_guard::called(Call::CmdPipelineBarrier);
}
}
/// What owns the memory its work writes ([`Held::owner`]), each once; `None` where one's
@@ -343,6 +343,7 @@ pub(crate) struct Counters {
images_started_on_the_host: AtomicU64,
images_started_zeroed: AtomicU64,
private_textures_zero_filled: AtomicU64,
memoryless_textures_zeroed: AtomicU64,
host_texel_copies: AtomicU64,
heap_shadow_cpu_copies: AtomicU64,
depth_uploads_clamped: AtomicU64,
@@ -4866,6 +4867,12 @@ impl Counters {
(self.private_textures_zero_filled).fetch_add(1, Ordering::Relaxed);
}
/// A new memoryless texture in memory that is not lazily allocated was made to be zeroed at
/// its first move, by render passes (`Device::new_texture_image`).
pub(crate) fn memoryless_texture_zeroed(&self) {
(self.memoryless_textures_zeroed).fetch_add(1, Ordering::Relaxed);
}
/// A texture's CPU copy ran on the host (`texture/host_copy.rs`).
pub(crate) fn host_texel_copy(&self) {
self.host_texel_copies.fetch_add(1, Ordering::Relaxed);
@@ -7042,6 +7049,15 @@ pub struct WorkCounts {
/// reads. Zero on a device that presents an Apple silicon Mac's compression, whose new
/// `Private` textures start as that Mac's.
pub private_textures_zero_filled: u64,
/// New memoryless textures zeroed at their first move, on a device whose memoryless memory
/// is not lazily allocated: a render pass of each level alone clears every aspect over its
/// layers, as no transfer writes a transient attachment. Its first use, a pass that loads it
/// `DontCare` (whose draws test against its depth, or whose resolve reads it), so reads zero,
/// never what its memory held, which may be a released texture's samples of another process
/// of a consumer whose processes share the device; later passes read what earlier ones left,
/// as before. Zero where memoryless memory is lazily allocated (MoltenVK), whose memoryless
/// images hold nothing past a pass.
pub memoryless_textures_zeroed: u64,
/// `replace_region` and `get_bytes` copies that ran on the host, with no submission
/// (`texture/host_copy.rs`).
pub host_texel_copies: u64,
@@ -10034,6 +10050,8 @@ impl Device {
images_started_zeroed: counters.images_started_zeroed.load(Ordering::Relaxed),
private_textures_zero_filled: (counters.private_textures_zero_filled)
.load(Ordering::Relaxed),
memoryless_textures_zeroed: (counters.memoryless_textures_zeroed)
.load(Ordering::Relaxed),
host_texel_copies: counters.host_texel_copies.load(Ordering::Relaxed),
heap_shadow_cpu_copies: counters.heap_shadow_cpu_copies.load(Ordering::Relaxed),
depth_uploads_clamped: counters.depth_uploads_clamped.load(Ordering::Relaxed),
@@ -3157,6 +3157,7 @@ field metal2vulkan-runtime::WorkCounts.memory_frees pub memory_frees: MemoryFree
field metal2vulkan-runtime::WorkCounts.memory_frees_paced pub memory_frees_paced: u64
field metal2vulkan-runtime::WorkCounts.memory_frees_paced_nanos pub memory_frees_paced_nanos: u64
field metal2vulkan-runtime::WorkCounts.memory_frees_posted pub memory_frees_posted: u64
field metal2vulkan-runtime::WorkCounts.memoryless_textures_zeroed pub memoryless_textures_zeroed: u64
field metal2vulkan-runtime::WorkCounts.merged_draw_commands pub merged_draw_commands: u64
field metal2vulkan-runtime::WorkCounts.mipmap_first_levels_fetched pub mipmap_first_levels_fetched: u64
field metal2vulkan-runtime::WorkCounts.mipmaps_filtered pub mipmaps_filtered: u64
Can't render this file because it is too large.