diff --git a/crates/metal2vulkan-runtime/src/pipeline/render/residual.rs b/crates/metal2vulkan-runtime/src/pipeline/render/residual.rs index 494d8d662..6b8f1f532 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render/residual.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render/residual.rs @@ -62,7 +62,9 @@ //! specializations and the dispatches' regions take that form before any key is looked up //! (`RenderVariant::plan`, `Variant::keyed_regions`): off that profile a state's creation makes //! the one pipeline its draws at every bind offset take, and on it the two the module's -//! **Made at creation, both forms** names. The shapes and plans stay every device's +//! **Made at creation, both forms** names. A kernel's uniform view there has a storage twin +//! (`DescriptorView::UniformWithStorageTwin`), whose key the plan keeps too: at 1 it reads the +//! twin at its bind offset alone, not the uniform view. The shapes and plans stay every device's //! (`argument_table::AtBindViews`): a bind offset the view base alignment divides still makes a //! shape and a plan of its own, whose key's uniform views alone take their residual form. //! - **Only GPU time moves.** Until the key's making lands, its draws' uniform reads take the @@ -225,10 +227,11 @@ pub(crate) fn residual_form<'a>( /// `specialization` with each `SpecKey::RangeAtBindOffset` constant of `constants` (a pipeline's /// stages') whose slot `interface` (the pipeline's) reads through a uniform view at 0, the key a /// plan takes where the device reads its uniform views at their residuals (the module docs); -/// `None` where every one of them is 0 there already. A storage view's constant, which only a -/// profile taking `DriverWorkaround::PushReadsLengthenThreadPayload` declares, keeps its value: its -/// bind at offset 0 reads no residual word there. Where no storage view declares the key this is -/// [`residual_form`]. +/// `None` where every one of them is 0 there already. A storage view's constant, and a uniform +/// view's with a storage twin (`DescriptorView::UniformWithStorageTwin`), which only a profile +/// taking `DriverWorkaround::PushReadsLengthenThreadPayload` declares, keep their values: at its +/// bind offset alone the first reads no residual word there, and the second reads its twin, not +/// its uniform view. Where neither declares the key this is [`residual_form`]. pub(crate) fn uniform_residual_form<'a>( constants: impl Iterator + Clone, interface: &PipelineInterface, @@ -236,7 +239,7 @@ pub(crate) fn uniform_residual_form<'a>( ) -> Option { let uniform = |slot| { matches!(interface.slots.get(&slot), - Some(SlotInterface::Buffer(b)) if b.form.uniform_view()) + Some(SlotInterface::Buffer(b)) if b.form.uniform_view() && !b.form.storage_twin()) }; let constants = constants.map(|constant| (constant.id, constant.key)); residual_form_of(constants, uniform, specialization) diff --git a/crates/metal2vulkan-runtime/src/tests/uniform_bind_offsets.rs b/crates/metal2vulkan-runtime/src/tests/uniform_bind_offsets.rs index a59816756..d84901a60 100644 --- a/crates/metal2vulkan-runtime/src/tests/uniform_bind_offsets.rs +++ b/crates/metal2vulkan-runtime/src/tests/uniform_bind_offsets.rs @@ -17,6 +17,8 @@ //! bound to nothing as one bound at offset 0, and makes that key and its residual form both //! ([`storage_views_keyed`]): `ubo_offsets_kernel`'s output, bound at offset 0, takes the //! creation's key, and a draw binding a storage view elsewhere takes the residual form at once. +//! There a kernel's constants also have a storage twin, read where their key holds, which a +//! dispatch at an aligned offset or of inline bytes takes, the creation's key. //! //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are those of the owned @@ -960,6 +962,96 @@ fn kernel_constants_read_at_every_bind_offset() { } } +/// A kernel's constants bound at offsets the view base alignment divides (0 and 128, a multiple +/// of every device's) and as inline bytes take the key its creation predicted and made, and make +/// nothing; on a profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload` that key +/// reads them through their storage twin (`DescriptorView::UniformWithStorageTwin`) at their bind +/// offset. Bound then at offset 4, which no alignment divides, they are read through the uniform +/// view at their residual: there a key of its own (the output still read at its bind offset 0), +/// taken through the creation's residual form at once while it is made on the pool, one +/// pipeline; elsewhere the creation's. With the device's pool held, each dispatch reads its bytes. +#[test] +fn kernel_constants_at_aligned_offsets_take_the_creations_key() { + let scratch = Scratch::new("uniform-twin-kernel"); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let function = library(&device) + .new_function_with_name("ubo_offsets_kernel") + .unwrap(); + let keyed = u64::from(storage_views_keyed(&device)); + let state = kernel_state(&device, &function); + let created = idle(&device); + let [width, height, depth] = PREDICTED_THREADS; + let threads = Size::new(u64::from(width), u64::from(height), u64::from(depth)); + let data = constants(); + let constants = device + .new_buffer_with_bytes(&data, ResourceOptions::shared()) + .unwrap(); + // `None`: inline bytes from offset 8. + let offsets = [Some(0), Some(128), None, Some(4)]; + let outputs: Vec = offsets + .iter() + .map(|_| device.new_buffer(16, ResourceOptions::shared()).unwrap()) + .collect(); + let took = |from: &crate::WorkCounts, to: &crate::WorkCounts| { + ( + to.residual_form_draws - from.residual_form_draws, + to.dispatch_pipelines_pooled - from.dispatch_pipelines_pooled, + to.variant_pipelines_made - from.variant_pipelines_made, + ) + }; + let hold = crate::pipeline::pool::held::hold(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + let mut counts = vec![device.work_counts()]; + for (offset, output) in offsets.iter().zip(&outputs) { + match offset { + Some(at) => encoder.set_buffer(Some(&constants), *at, 0).unwrap(), + None => encoder.set_bytes(&data[8..24], 0).unwrap(), + } + encoder.set_buffer(Some(output), 0, 1).unwrap(); + encoder + .dispatch_threadgroups(Size::new(1, 1, 1), threads) + .unwrap(); + counts.push(device.work_counts()); + } + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer + .wait_until_completed_for(WAIT) + .expect("the dispatches' command buffer waits for no making"); + assert_eq!(command_buffer.error(), None); + drop(hold); + assert_eq!( + took(&counts[0], &counts[3]), + (0, 0, 0), + "dispatches at 0 and 128 and of inline bytes: residual-form dispatches, regions pooled, \ + pipelines made" + ); + assert_eq!( + took(&counts[3], &counts[4]), + (keyed, keyed, 0), + "a dispatch at 4: residual-form dispatches, regions pooled, pipelines made" + ); + assert_eq!( + idle(&device).variant_pipelines_made - created.variant_pipelines_made, + keyed, + "pipelines made once the pool ran" + ); + for (offset, output) in offsets.iter().zip(&outputs) { + let at = offset.unwrap_or(8) as usize / 4; + let words = bytes_of(output); + let read = |w: usize| f32::from_le_bytes(words[w * 4..w * 4 + 4].try_into().unwrap()); + let want = |i: usize| i as f32 / 255.0; + assert_eq!( + [read(0), read(1)], + [want(at), want(at + 2)], + "offset {offset:?}" + ); + } +} + /// A kernel reads a `device` buffer through a storage view at bind offset 0, then at offsets past /// it and at 0 again (`engine/buffer_end_byte_load.ll`: `out[0] = in[5]`), and each dispatch reads /// the bound bytes, whichever form its key takes. On a device whose profile takes diff --git a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs index bc5278c25..c3a7bae3b 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs @@ -556,7 +556,10 @@ pub fn containment( (ContainmentForm::BufferAtomic, atomic_check) } DescriptorView::Storage => (ContainmentForm::StorageBuffer, robust), - DescriptorView::UniformWords | DescriptorView::UniformVec4 => { + // A storage twin reads the same range under the same robustness. + DescriptorView::UniformWords + | DescriptorView::UniformVec4 + | DescriptorView::UniformWithStorageTwin => { (ContainmentForm::UniformBuffer, robust) } _ => return unknown(), @@ -650,7 +653,8 @@ pub fn containment( BufferForm::Descriptor( DescriptorView::Storage | DescriptorView::UniformWords - | DescriptorView::UniformVec4, + | DescriptorView::UniformVec4 + | DescriptorView::UniformWithStorageTwin, ) => made(target.form, Medium::DescriptorView, robust, false), _ => unknown(), }, diff --git a/crates/metal2vulkan/src/bind/dispatch/tests.rs b/crates/metal2vulkan/src/bind/dispatch/tests.rs index 56995592d..f3c8410d2 100644 --- a/crates/metal2vulkan/src/bind/dispatch/tests.rs +++ b/crates/metal2vulkan/src/bind/dispatch/tests.rs @@ -84,6 +84,7 @@ fn template() -> ComputeTemplate { length_class: crate::bind::state::length_class(4096), }, disjoint: false, + twin: None, }], spec: vec![ spec(0, SpecKey::LocalSize(Axis::X)), diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index d1124c227..9c87f399a 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -331,7 +331,7 @@ use crate::bind::neutral::{zero_buffer_bytes, NeutralResource}; use crate::bind::plan::compute::{internal, not_implemented, spec_key, tile_memory}; 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, + address_map_variant, anisotropic_variant, bindings, bound_value, buffer_uses, check_slots, check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes, large_view_candidates, mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted, record_specialized, snapshot_forms, srgb_variant, storage_view_variant, @@ -2018,7 +2018,8 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result { + // A uniform view's storage twin binds the slot's own buffer, at its own range. + BindingSource::Buffer(slot) | BindingSource::StorageTwin(slot) => { let pb = planned(slot).ok_or_else(|| { internal(format!("binding of {slot:?} without an interface slot")) })?; @@ -2502,7 +2503,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result = buffers .iter() .filter(|b| matches!(b.bound, BoundKind::Buffer { .. })) - .map(|b| buffer_use(b, stage_flags(b.slot.stage))) + .flat_map(|b| buffer_uses(b, stage_flags(b.slot.stage))) .collect(); // The factors: the control stage's, or an emulated pipeline's scan's. if factor_binding.is_some() @@ -5143,8 +5144,8 @@ fn rebinds_into(t: &GraphicsTemplate, slots: &[SlotRef], into: &mut SlotRebinds) into.vertex.clear(); let changed = |slot: SlotRef| slot.class == SlotClass::Buffer && slots.contains(&slot); // What the slots decide some other way than below: a stage's argument or root table, a mesh - // or patch draw's own reads, a de-indexed draw's layout, and a uniform view a written slot - // may alias. + // or patch draw's own reads, a de-indexed draw's layout, a uniform view a written slot may + // alias, and a uniform view's storage twin, a second range of its slot. let other_reads = t .stages .iter() @@ -5152,7 +5153,8 @@ fn rebinds_into(t: &GraphicsTemplate, slots: &[SlotRef], into: &mut SlotRebinds) || t.mesh.is_some() || t.tessellation.is_some() || t.deindexed.is_some() - || (t.buffers.iter().any(|b| b.disjoint) && t.buffers.iter().any(|b| b.access.write)); + || (t.buffers.iter().any(|b| b.disjoint) && t.buffers.iter().any(|b| b.access.write)) + || t.buffers.iter().any(|b| b.twin.is_some()); // A texture slot's texels a texture buffer's range bounds, which the commands hold. let texel_range = |slot: &SlotRef| t.resources.texel_buffers.iter().any(|pt| pt.slot == *slot); let texels = slots diff --git a/crates/metal2vulkan/src/bind/graphics/tests.rs b/crates/metal2vulkan/src/bind/graphics/tests.rs index 1a9758878..c6611cba2 100644 --- a/crates/metal2vulkan/src/bind/graphics/tests.rs +++ b/crates/metal2vulkan/src/bind/graphics/tests.rs @@ -821,6 +821,7 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() { length_class: length_class(4096), }, disjoint: false, + twin: None, }], stages: Vec::new(), vertex_buffers: vertex_buffers(), diff --git a/crates/metal2vulkan/src/bind/instantiate.rs b/crates/metal2vulkan/src/bind/instantiate.rs index 87c67941f..92673ab6b 100644 --- a/crates/metal2vulkan/src/bind/instantiate.rs +++ b/crates/metal2vulkan/src/bind/instantiate.rs @@ -615,7 +615,9 @@ pub(crate) fn shared_range( /// offset 0 (`SpecKey::RangeAtBindOffset`, where its profile declares the key, set only where /// [`starts_at_bind`] holds there, which leaves that range's residual 0), and a uniform view of /// one where `views_at_residual` (no function reads it at its bind offset alone), take -/// [`shared_range`]'s, where it holds the window; +/// [`shared_range`]'s, where it holds the window; not a uniform view with a storage twin +/// (`DescriptorView::UniformWithStorageTwin`), whose key reads the twin at its bind offset alone +/// whatever `views_at_residual` says; /// - every other slot takes [`descriptor_range`]'s, which starts at the bind offset aligned down /// to the descriptor base alignment: a uniform view's key may read it at its bind offset alone, /// where its residual is 0. @@ -633,7 +635,8 @@ pub(crate) fn planned_range( && end <= pb.max_range && end <= 1 << 32; if !from_start { - let shared = (storage || (views_at_residual && pb.form.uniform_view())) + let at_residual = views_at_residual && !pb.form.storage_twin(); + let shared = (storage || (at_residual && pb.form.uniform_view())) .then(|| shared_range(bind_offset, length, pb.window, pb.alignment, pb.max_range)) .flatten(); return match shared { @@ -813,6 +816,15 @@ pub(crate) fn bind_buffers( element: 0, range, }); + // A uniform view's storage twin binds the same range. + if let Some((set, binding)) = pb.twin { + descriptor_ranges.push(DescriptorRange { + set, + binding, + element: 0, + range, + }); + } out.residuals.push(pb.slot, residual); } (BufferForm::Psb, _) => { diff --git a/crates/metal2vulkan/src/bind/instantiate/tests.rs b/crates/metal2vulkan/src/bind/instantiate/tests.rs index c2183c5d8..8f2d6051a 100644 --- a/crates/metal2vulkan/src/bind/instantiate/tests.rs +++ b/crates/metal2vulkan/src/bind/instantiate/tests.rs @@ -208,6 +208,7 @@ fn planned(window: Window, view: DescriptorView, alignment: u64, max_range: u64) length_class: crate::bind::state::length_class(1 << 12), }, disjoint: false, + twin: None, } } @@ -484,6 +485,59 @@ fn bounded_slots_read_at_their_residual_share_one_range_along_a_buffer() { } } +/// A uniform view with a storage twin binds its range from its bind offset, its residual 0, also +/// where the consumer reads every uniform view at its residual: its key reads the twin at its +/// bind offset alone. A plain uniform view there shares one range from the buffer's start, the +/// negative control. `bind_buffers` writes the twin's binding with the uniform binding's range. +#[test] +fn a_uniform_view_with_a_storage_twin_binds_its_range_from_its_bind_offset() { + use crate::bind::state::{BindState, BoundBuffer, StageTable}; + const CHUNK: u64 = 64 * 1024; + let bounded = Window::Bounded { start: 0, len: 16 }; + let mut twin = planned(bounded, DescriptorView::UniformWithStorageTwin, 64, CHUNK); + let plain = planned(bounded, DescriptorView::UniformWords, 64, CHUNK); + for bind_offset in (0..CHUNK).step_by(256) { + for at_residual in [false, true] { + let (range, residual) = planned_range(&twin, bind_offset, CHUNK, at_residual).unwrap(); + assert_eq!( + (range.offset, residual), + (bind_offset, 0), + "{bind_offset} {at_residual}" + ); + } + let (range, residual) = planned_range(&plain, bind_offset, CHUNK, true).unwrap(); + assert_eq!( + (range.offset, u64::from(residual)), + (0, bind_offset), + "{bind_offset}" + ); + } + twin.twin = Some((0, 3)); + let mut table = StageTable::default(); + table.buffers.insert( + twin.slot.index, + BoundBuffer::Buffer { + gpu_address: 0x1_0000, + // `planned`'s length class. + length: 1 << 12, + offset: 256, + device_address: None, + attribute_stride: None, + }, + ); + let mut state = BindState::default(); + state.stages.insert(twin.slot.stage, table); + state.uniform_views_at_residual = true; + let slot = twin.slot; + let (mut ranges, mut extents) = (Vec::new(), Vec::new()); + let bound = bind_buffers(&[twin], &state, &mut ranges, &mut extents).unwrap(); + let keys: Vec<_> = ranges.iter().map(|r| (r.set, r.binding)).collect(); + assert_eq!(keys, [(0, 0), (0, 3)]); + assert_eq!(ranges[0].range, ranges[1].range); + assert_eq!(ranges[0].range.offset, 256); + assert_eq!(bound.residuals.of(slot), Some(0)); +} + fn entry(host: u64, guest: u64, size: u64) -> RootEntry { RootEntry { host, diff --git a/crates/metal2vulkan/src/bind/plan.rs b/crates/metal2vulkan/src/bind/plan.rs index 06adac2bf..509c60f8f 100644 --- a/crates/metal2vulkan/src/bind/plan.rs +++ b/crates/metal2vulkan/src/bind/plan.rs @@ -561,6 +561,10 @@ pub(crate) struct PlannedBuffer { /// its window (`RuntimeFact::UniformViewAliasing`). #[cfg_attr(feature = "serde", serde(default))] pub disjoint: bool, + /// `(set, binding)` of the slot's storage twin (`DescriptorView::UniformWithStorageTwin`), + /// written with the slot's own buffer and range. + #[cfg_attr(feature = "serde", serde(default))] + pub twin: Option<(u32, u32)>, } /// What a shape binds at a buffer slot. diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index eb9837bcd..e97c5c4a3 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -61,7 +61,7 @@ use super::resources::{separate_samplers, ResourcePlanner}; use super::slots::{ - address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots, + address_map_variant, anisotropic_variant, bindings, bound_value, buffer_uses, check_slots, check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes, mark_disjoint, plan_buffer, psb_variant, record_noted, record_specialized, srgb_variant, storage_view_variant, texel_buffer_parts_variant, used_uses, ycbcr_in_place_variant, @@ -574,7 +574,8 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result { + // A uniform view's storage twin binds the slot's own buffer, at its own range. + BindingSource::Buffer(slot) | BindingSource::StorageTwin(slot) => { let pb = planned(slot).ok_or_else(|| { internal(format!("binding of {slot:?} without an interface slot")) })?; @@ -828,7 +829,7 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result = buffers .iter() .filter(|b| matches!(b.bound, BoundKind::Buffer { .. })) - .map(|b| buffer_use(b, compute_stage)) + .flat_map(|b| buffer_uses(b, compute_stage)) .collect(); uses.extend(used_uses( &shape.used, diff --git a/crates/metal2vulkan/src/bind/plan/slots.rs b/crates/metal2vulkan/src/bind/plan/slots.rs index e762efb9a..3a955c21b 100644 --- a/crates/metal2vulkan/src/bind/plan/slots.rs +++ b/crates/metal2vulkan/src/bind/plan/slots.rs @@ -155,6 +155,15 @@ pub(crate) fn plan_buffer( None } }; + let twin = match b.form.storage_twin() { + true => Some( + bindings + .get(&BindingSource::StorageTwin(slot)) + .copied() + .ok_or_else(|| internal(format!("slot {slot:?} has no storage twin binding")))?, + ), + false => None, + }; Ok(PlannedBuffer { slot, window: b.window, @@ -165,6 +174,7 @@ pub(crate) fn plan_buffer( max_range, bound, disjoint: false, + twin, }) } @@ -182,8 +192,9 @@ pub(crate) fn plan_buffer( /// nothing has the residual 0 (`instantiate::slot_field`), so either form reads the Metal offset /// alone of the same descriptor: a uniform view's takes false, the form that reads at the /// residual, which keeps the key of a draw that leaves the slot unbound the key that reads every -/// such slot at its residual; a storage view's takes what a bind at offset 0 takes, the -/// commonest bind, so that a plan of nothing bound, which a consumer makes before any draw binds +/// such slot at its residual; a storage view's, and a uniform view's with a storage twin +/// (`DescriptorView::UniformWithStorageTwin`), whose key reads the twin, take what a bind at +/// offset 0 takes, the commonest bind, so that a plan of nothing bound, which a consumer makes before any draw binds /// the slot (the runtime's creation, `pipeline/predicted.rs` and `pipeline/dispatch_making.rs`, /// and a warm pass's replay of a dispatch, `pipeline/dispatch_record.rs`), names the key of the /// draw that binds it there. @@ -207,7 +218,7 @@ pub(crate) fn range_at_bind_offset( offset_alignment, .. }) => u64::from(offset_alignment), Some(BufferShape::Bytes { .. }) => 0, - None if !b.form.uniform_view() => 0, + None if !b.form.uniform_view() || b.form.storage_twin() => 0, None => return false, }; let alignment = crate::memory::views::base_alignment(min); @@ -999,27 +1010,37 @@ pub(crate) fn range_variant(slot: SlotRef, bound: BoundKind, profile: &DevicePro && matches!(bound, BoundKind::Buffer { length_class, .. } if !class_fits(length_class, storage)) } -/// The `uses` entry of a bound buffer slot: its proven access, `Uniform` for a uniform view and +/// The `uses` entries of a bound buffer slot: its proven access, `Uniform` for a uniform view and /// `Storage` otherwise, `stages`, and the window as a range when it starts at or after the bind -/// offset. -pub(crate) fn buffer_use(b: &PlannedBuffer, stages: vk::PipelineStageFlags2) -> ResourceUse { - ResourceUse { - resource: UseTarget::Slot(b.slot), - access: b.access, - class: if b.form.uniform_view() { - AccessClass::Uniform - } else { - AccessClass::Storage - }, - stages, - range: match b.window { - Window::Bounded { start, len } if start >= 0 => Some(ByteRange { - offset: start as u64, - len, - }), - _ => None, - }, - } +/// offset; a uniform view's storage twin (`DescriptorView::UniformWithStorageTwin`) reads the +/// same bytes as a storage buffer, a `Storage` use of them beside the `Uniform` one. +pub(crate) fn buffer_uses( + b: &PlannedBuffer, + stages: vk::PipelineStageFlags2, +) -> impl Iterator { + let class = if b.form.uniform_view() { + AccessClass::Uniform + } else { + AccessClass::Storage + }; + let twin = b.form.storage_twin().then_some(AccessClass::Storage); + let (slot, access) = (b.slot, b.access); + let range = match b.window { + Window::Bounded { start, len } if start >= 0 => Some(ByteRange { + offset: start as u64, + len, + }), + _ => None, + }; + std::iter::once(class) + .chain(twin) + .map(move |class| ResourceUse { + resource: UseTarget::Slot(slot), + access, + class, + stages, + range, + }) } /// The `uses` of the used resources a pipeline can reach (the handback): buffers and heaps when a diff --git a/crates/metal2vulkan/src/bind/plan/slots/tests.rs b/crates/metal2vulkan/src/bind/plan/slots/tests.rs index 13c788770..f7439cf51 100644 --- a/crates/metal2vulkan/src/bind/plan/slots/tests.rs +++ b/crates/metal2vulkan/src/bind/plan/slots/tests.rs @@ -66,6 +66,7 @@ fn planned(index: u32, bound: BoundKind, form: BufferForm) -> PlannedBuffer { max_range: 0, bound, disjoint: false, + twin: None, } } @@ -708,6 +709,97 @@ fn a_storage_range_starts_at_the_bind_offset_only_at_offset_0() { } } +/// A uniform view with a storage twin (`DescriptorView::UniformWithStorageTwin`) takes a uniform +/// view's `RangeAtBindOffset` wherever its slot is bound (a buffer at each offset class, inline +/// bytes), on every committed profile and under each window, and bound to nothing what a bind at +/// offset 0 takes, where a plain uniform view takes false. Its plan names the twin's binding, and +/// a plan of the layout without one is refused. +#[test] +fn a_storage_twin_takes_a_uniform_views_key_and_offset_0_s_unbound() { + for (stem, p) in committed_profiles().expect("profiles") { + let limits = &p.fields().limits; + let alignment = + crate::memory::views::base_alignment(limits.min_uniform_buffer_offset_alignment); + for window in [ + Window::Bounded { start: 0, len: 64 }, + Window::Bounded { start: 4, len: 28 }, + Window::Bounded { start: -8, len: 40 }, + ] { + let slot_of = |view| BufferSlot { + access: AccessSet::READ, + window, + form: BufferForm::Descriptor(view), + kind: BufferKind::Buffer, + }; + let (twin, plain) = ( + slot_of(DescriptorView::UniformWithStorageTwin), + slot_of(DescriptorView::UniformWords), + ); + let what = format!("{stem} {window:?}"); + for bind_offset in [0, 4, 16, 20, 64, 260, 1024] { + let shape = BoundBuffer::Buffer { + gpu_address: 0x1_0000, + length: 4096, + offset: bind_offset, + device_address: None, + attribute_stride: None, + } + .shape(alignment as u32); + assert_eq!( + range_at_bind_offset(&twin, Some(&shape), limits), + range_at_bind_offset(&plain, Some(&shape), limits), + "{what} {bind_offset}" + ); + } + let bytes = BufferShape::Bytes { + attribute_stride: None, + }; + assert_eq!( + range_at_bind_offset(&twin, Some(&bytes), limits), + range_at_bind_offset(&plain, Some(&bytes), limits), + "{what} bytes" + ); + let at_0 = BoundBuffer::Buffer { + gpu_address: 0x1_0000, + length: 4096, + offset: 0, + device_address: None, + attribute_stride: None, + } + .shape(alignment as u32); + assert_eq!( + range_at_bind_offset(&twin, None, limits), + range_at_bind_offset(&twin, Some(&at_0), limits), + "{what} unbound" + ); + assert!( + !range_at_bind_offset(&plain, None, limits), + "{what} unbound" + ); + let both = [ + (BindingSource::Buffer(slot(0)), (0, 0)), + (BindingSource::StorageTwin(slot(0)), (0, 3)), + ] + .into(); + let pb = plan_buffer((slot(0), &twin, Some(&at_0)), false, limits, &both) + .unwrap_or_else(|e| panic!("{what}: {e:?}")); + assert_eq!( + (pb.binding, pb.twin), + (Some((0, 0)), Some((0, 3))), + "{what}" + ); + let pb = plan_buffer((slot(0), &plain, Some(&at_0)), false, limits, &both) + .unwrap_or_else(|e| panic!("{what}: {e:?}")); + assert_eq!(pb.twin, None, "{what}"); + let alone = [(BindingSource::Buffer(slot(0)), (0, 0))].into(); + assert!( + plan_buffer((slot(0), &twin, Some(&at_0)), false, limits, &alone).is_err(), + "{what}: no twin binding" + ); + } + } +} + /// A slot whose function observes residency (`RuntimeFact::SparseTexture`) binds a texture that is /// not sparse (or nothing) on every profile, and a sparse one where the module has the sparse arm /// or the tile-map arm; without either a sparse texture is refused, naming diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 6d3cc82dd..c89ff7411 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -873,6 +873,7 @@ codec_enum! { SnapshotTexels(f0), YCbCrPlanes(f0), SamplerArray { compare, integer }, + StorageTwin, } AccelerationStructureLevel { Primitive, Instance } SamplerRef { Slot(f0), Constexpr(f0) } @@ -1201,7 +1202,7 @@ codec_enum! { Window { Bounded { start, len }, Whole } BufferForm { Descriptor(f0), Psb } BufferKind { Buffer, VisibleFunctionTable, IntersectionFunctionTable } - DescriptorView { Storage, UniformWords, UniformVec4 } + DescriptorView { Storage, UniformWords, UniformVec4, UniformWithStorageTwin } PushLoc { Push { offset }, ArgumentTable { offset } } IoRole { Attribute { index }, Varying { user, interpolation }, @@ -1534,6 +1535,7 @@ codec_enum! { SnapshotTexels(f0), YCbCrPlanes(f0), SamplerArray { stage, compare, integer }, + StorageTwin(f0), } VertexStride { Static(f0), PerBind } } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 9d2edb693..a915ea801 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2131; +pub const SEMANTICS_VERSION: u32 = 2132; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2412; +pub const RUNTIME_VERSION: u32 = 2413; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 17b8cae86..fe13369b2 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -894,7 +894,9 @@ const fn moltenvk_on_apple(fact: F) -> Measured { /// reads its storage views at their bind offsets, which a command binding them at offset 0, the /// commonest bind, takes, and its general form, which one binding a storage view elsewhere takes /// at once; with the general form alone, every state's first command at offset 0 made a second -/// pipeline. +/// pipeline. There a kernel's uniform view also binds a storage twin of its range, which it +/// reads at its bind offset alone where its key holds (`DescriptorView::UniformWithStorageTwin`; +/// the workaround's own documentation holds the figures). pub(crate) const DEFECTS: &[Measured] = &[ Measured { fact: DriverWorkaround::BothBarycentricFormsRejected, diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 68beab035..bfab7cad9 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -1585,12 +1585,16 @@ pub enum DriverWorkaround { /// The runtime's creation of a state makes that key and, beside it and at the same time, its /// general form, every view read at its residual, which a command binding a storage view /// elsewhere takes at once while its own key is made: otherwise one of the two would be a - /// second pipeline made at the state's first command. It reads - /// a uniform view at its residual there, as on every device without - /// `DriverFact::ConstantOffsetUniformReadsPreloaded`: a kernel of three storage views at offset - /// 0 and inline bytes ran in 161.8 us a dispatch with the bytes' uniform view read at its bind - /// offset and in 142.8 us with it read at its residual (job m3-max-34275). It changes no - /// answer. + /// second pipeline made at the state's first command. A uniform view read at its bind offset + /// alone is no faster there: a kernel of three storage views at offset 0 and inline bytes ran + /// in 161.8 us a dispatch with the bytes' uniform view read so and in 142.8 us with it read at + /// its residual, and in 102.1 us with the bytes read through a storage view at their bind + /// offset (job m3-max-34275). So a kernel's uniform view there also has a storage twin + /// (`DescriptorView::UniformWithStorageTwin`, `lower::access`): a storage + /// buffer of the uniform view's own range, which the kernel reads instead where the slot's + /// key holds (a bind offset the view base alignment divides, inline bytes, nothing bound), and + /// elsewhere the uniform view at its residual, as on every device without + /// `DriverFact::ConstantOffsetUniformReadsPreloaded`. It changes no answer. PushReadsLengthenThreadPayload, } diff --git a/crates/metal2vulkan/src/lower/access/atomic.rs b/crates/metal2vulkan/src/lower/access/atomic.rs index 3476033c1..8b6490dc7 100644 --- a/crates/metal2vulkan/src/lower/access/atomic.rs +++ b/crates/metal2vulkan/src/lower/access/atomic.rs @@ -1120,8 +1120,9 @@ fn on_target(fb: &mut FunctionBuilder<'_>, p: Prepared, o: Op) -> BResult