From 38dcc857dd8dbcfe68de31d7b525b5362d1ed44b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 11:27:17 -0800 Subject: [PATCH] Runtime: a sample's run-time texel offset is its own Offset operand where the device has maintenance8 The owner allowed a ninth query-chosen form (Telegram 2465): "I allow the ninth query. Use it where you can". This answers the texel-offset question inside his compile-time order ("Multi minute compiles are unacceptable"). What: the floor reads VK_KHR_maintenance8 and its feature maintenance8 where the device lists the extension (one of OPTIONAL_EXTENSIONS, and one of the OPTIONAL features, each of which chooses one of two forms; VkPhysicalDeviceMaintenance8FeaturesKHR is bound by hand, as ash 0.38 lacks it, its layout checked as the crate compiles). Device creation enables both, Capabilities answers texel_offset_operand, and the translator's description is told of Maintenance8 and KhrMaintenance8 (shader_enables). The translator already takes a run-time offset on a sample as the Offset operand where its profile has maintenance8 (lower::sampler::select::dynamic_offset). Until now the runtime never enabled the feature, so with_enabled dropped it, and every run-time offset that reached lowering became a switch of up to 256 ConstOffset arms. NVIDIA's compiler takes minutes to create that switch (lane stagesize: 255 arms 193 s on an RTX 3090, the operand 80 ms). Canonicalization's unroll of a proven small nest is unchanged on every device. A device without the feature keeps the branch: Intel's Windows driver for the UHD 630 (101.2145) lists no VK_KHR_maintenance8 (vulkaninfo, job 64024). The runtime README records the branch's compile time as a known gap of pipeline states, and its floor tables gain the extension and the optional feature. AGENTS.md rule 2 changes in this commit: "for eight only" becomes "for nine only", and the list gains run-time texel offsets. Spec (1.4.366): VUID-RuntimeSpirv-Offset-10213 is the only gate on Offset outside a gather. The value is OpBitFieldSExtract(v, 0, 4), in [-8, 7], inside the required minTexelOffset <= -8 and maxTexelOffset >= 7 (VUID-RuntimeSpirv-OpImageSample-06435/06436). Gathers already took Offset through shaderImageGatherExtended, which the floor requires. Enabling maintenance8 changes no other path the runtime takes: its blits stay within one 3D image, it names no queue family ownership transfer flag, and it merges no pipeline caches. Caches: the translator is unchanged, so SEMANTICS_VERSION stays. The translator's profile fingerprint (DeviceProfile::fingerprint, over every profile field, ImageCaps::dynamic_sample_offset among them) moves on a device that has the feature, and with it every FunctionCompileKey and render record name in the cache directory. A lowering made without the feature is not taken by a device with it (tests::filter_nest's every_device_keeps_the_operand_s_and_the_switch_s_lowerings_apart). Tests: tests::floor's a_run_time_texel_offset_is_the_sample_s_operand_where_maintenance8_is_reported fails without the change (no Maintenance8 among the enables); the_optional_features_decide_the_ capabilities takes the eighth case. tests::filter_nest (device cfgs): the unrolled kernel, the operand and the switch (a translator told of no maintenance8 on the same device, test-only) write the same 64 sums; the module needs maintenance8 and holds no OpSwitch where creation enabled it, and holds a switch otherwise. --- AGENTS.md | 11 +- crates/metal2vulkan-runtime/README.md | 18 +- crates/metal2vulkan-runtime/src/device.rs | 4 + crates/metal2vulkan-runtime/src/floor.rs | 79 ++++++++- .../src/tests/filter_nest.rs | 165 ++++++++++++++++-- .../metal2vulkan-runtime/src/tests/floor.rs | 34 +++- 6 files changed, 290 insertions(+), 21 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 24823c27d..48bf3800d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,15 +58,18 @@ order, and a lower one never overrides a higher one. limit and memory-type queries. Product code holds no vendor, device or driver ID, and no runtime policy switch. A test enforces this for `metal2vulkan-runtime`. One form means one form per Vulkan capability: where the floor cannot require a feature, that feature's query may choose a - second form, for eight only: 16-bit floats, storage-image reads without a format, 64-bit + second form, for nine only: 16-bit floats, storage-image reads without a format, 64-bit atomics, 64-bit floats, SIMD groups (the subgroup size range with its stages and operations, and maximal reconvergence), driver-zeroed memory (a device with the zero-initialize feature allocates its memory zeroed and a block says so at its take, so zeros the driver wrote are not written again; a device without it writes every zero itself), unified memory (decided by Vulkan's physical device type alone: one copy of a Managed buffer on an integrated or CPU - device, two elsewhere), and the attachment feedback loop (a device without it reads a render - target through a counted copy of that target, recorded as a known gap). A second form chosen - by anything else is not allowed. + device, two elsewhere), the attachment feedback loop (a device without it reads a render + target through a counted copy of that target, recorded as a known gap), and run-time texel + offsets (a device with the maintenance8 feature takes a run-time texel offset as the sampling + or read instruction's own operand; a device without it branches over the offset's values, and + that branch's compile time is recorded as a known gap). A second form chosen by anything else + is not allowed. 3. **Native-like speed.** Structure decides speed: driver-owned memory, optimal images in real layouts, direct addresses, nothing copied that Metal would not copy. Optimal images have two exceptions. A texture over a Shared buffer: a linear image on that buffer's memory, in the diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 1f37c2484..45597295e 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2781,6 +2781,15 @@ cache is answered compile-required on both. ### Known gaps of pipeline states +- A sample at a texel offset the shader computes, on a device without `maintenance8` (Chosen by a + query): the sample branches over the offset's values, one branch per combination of the 16 + values of each lane the shader computes (256 for a 2D offset), each with its value as + `ConstOffset`, where a + device with the feature takes the offset as the sample's own `Offset` operand. The branch costs + compile time: on NVIDIA's driver one fragment function's 255 branches took 193 s to create on an + RTX 3090, against 80 ms with the operand. Intel's Windows driver for the UHD 630 (101.2145) + does not list `VK_KHR_maintenance8`, so it takes the branch; its compile time there is not + measured. Test: `tests::filter_nest`. - A narrow integer's high bits (an 8- or 16-bit value held in a 32-bit word) are cleared by `OpBitwiseAnd` by the width's mask on every device. NVIDIA's driver 615.71.09 on Ampere GA10x dropped that mask after a signed clamp to exactly the narrow range, so such a kernel answered the @@ -4181,6 +4190,7 @@ Presenting runs on the runtime's own device; nothing is exported or imported. | `VK_EXT_image_drm_format_modifier` | device, where listed | a dma-buf surface's planes in place, as `DRM_FORMAT_MOD_LINEAR` images (`Device::new_exported_surface`) | | `VK_NV_linear_color_attachment` | device, where listed | an opaque handle's surface planes in place whose `LINEAR` tiling renders as a linear colour attachment alone, through the linear-attachment feature below | | `VK_EXT_device_fault` | device, where listed | a lost device's fault report, read once at its first loss (`DeviceLoss::fault`), through the fault-report feature below | +| `VK_KHR_maintenance8` | device, where listed | a sample at a texel offset the shader computes, with the offset as the sample's own `Offset` operand, through the optional feature `maintenance8` below | | `VK_EXT_custom_border_color` | device, where reported from the image | Vulkan requires it of a device that enables the border swizzle below; none of its features is enabled | | `VK_EXT_border_color_swizzle` | device, where reported from the image | an opaque-black border sampled through a view whose component mapping is not the identity, defined and read through that mapping (Border swizzle, below) | | `VK_EXT_device_generated_commands` | device, with indirect command buffers | an indirect command buffer's execution, through `deviceGeneratedCommands`, enabled where the device reports it with the limits an execution needs (Indirect command buffers, above) | @@ -4446,8 +4456,9 @@ apart from 1.8 to 3% Private, so the host link's rate above is not on their path ### Chosen by a query -Five features choose between two forms by the device's answer: 16-bit floats, storage-image reads -without a format, 64-bit atomics, 64-bit floats and SIMD groups. Beside them, a device without the +Six features choose between two forms by the device's answer: 16-bit floats, storage-image reads +without a format, 64-bit atomics, 64-bit floats, SIMD groups and run-time texel offsets. Beside +them, a device without the attachment feedback loop reads attachments through a copy, the one form left there, which is a known gap (Known gaps of render encoders). `floor::Capabilities` holds each answer the floor reads, and the features and extensions to enable: the floor's, and each optional one the device @@ -4457,7 +4468,7 @@ has. |---|---|---| | SIMD groups | `minSubgroupSize`, `maxSubgroupSize` and `requiredSubgroupSizeStages` (`VkPhysicalDeviceVulkan13Properties`); `subgroupSupportedStages` and `subgroupSupportedOperations` (`VkPhysicalDeviceVulkan11Properties`); `shaderMaximalReconvergence` (`VK_KHR_shader_maximal_reconvergence`) and `shaderSubgroupUniformControlFlow` (`VK_KHR_shader_subgroup_uniform_control_flow`) | the translator's choice of how a kernel's SIMD groups run (its tier), and their reconvergence mode: maximal where offered, else subgroup-uniform control flow where offered | -The other five are one feature each: +The other six are one feature each: | Optional feature | Structure | Used for | |---|---|---| @@ -4468,6 +4479,7 @@ The other five are one feature each: | `shaderFloat64` | `VkPhysicalDeviceFeatures` | 64-bit floats | | `shaderMaximalReconvergence` | `VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR` | SIMD groups that reconverge as Metal's do | | `shaderSubgroupUniformControlFlow` | `VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR` | SIMD groups' reconvergence where maximal reconvergence is not offered | +| `maintenance8` | `VkPhysicalDeviceMaintenance8FeaturesKHR` | a sample at a texel offset the shader computes, with the offset as the sample's own `Offset` operand; where it is false, the sample branches over the offset's values, each branch with its value as `ConstOffset`, which costs compile time (Known gaps of pipeline states) | `sparseBinding` (`VkPhysicalDeviceFeatures`) chooses no form: device creation enables it only where the device offers imports over several dma-bufs (`Device::import_dma_bufs`, Imported diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs index f4381d1bd..cf6ddf914 100644 --- a/crates/metal2vulkan-runtime/src/device.rs +++ b/crates/metal2vulkan-runtime/src/device.rs @@ -548,6 +548,7 @@ impl Device { mut line_rasterization, mut generated_commands, mut maintenance5, + mut maintenance8, } = enabled_features; // `sparseBinding` for imports over several dma-bufs (`Device::import_dma_bufs`), only where // the device's queries offer that import: it changes no other path, as only that import @@ -616,6 +617,9 @@ impl Device { .push_next(&mut generated_commands) .push_next(&mut maintenance5); } + if enabled(floor::MAINTENANCE8) { + features = features.push_next(&mut maintenance8); + } // SAFETY: as for the floor check. let listed = unsafe { vk_instance.enumerate_device_extension_properties(raw) } .map_err(Error::vulkan("vkEnumerateDeviceExtensionProperties"))?; diff --git a/crates/metal2vulkan-runtime/src/floor.rs b/crates/metal2vulkan-runtime/src/floor.rs index f70188d01..ae5ab6665 100644 --- a/crates/metal2vulkan-runtime/src/floor.rs +++ b/crates/metal2vulkan-runtime/src/floor.rs @@ -56,9 +56,10 @@ pub const TIME_DOMAINS: [vk::TimeDomainKHR; 2] = /// ([`Device::new_exported_surface`](crate::Device::new_exported_surface)), and /// `VK_NV_linear_color_attachment`, with its `linearColorAttachment` feature where the device /// reports it, through which an opaque handle's surface plane whose `LINEAR` tiling renders only -/// as a linear colour attachment lies in place, and `VK_EXT_device_fault`, with its `deviceFault` +/// as a linear colour attachment lies in place, `VK_EXT_device_fault`, with its `deviceFault` /// feature, which Vulkan requires of a device that lists it, through which a lost device's fault -/// report is read once, at its first loss ([`DeviceLoss::fault`](crate::DeviceLoss::fault)). +/// report is read once, at its first loss ([`DeviceLoss::fault`](crate::DeviceLoss::fault)), and +/// `VK_KHR_maintenance8` ([`MAINTENANCE8`]), for the optional feature of its own. pub const OPTIONAL_EXTENSIONS: &[&CStr] = &[ ash::khr::shader_maximal_reconvergence::NAME, ash::khr::shader_subgroup_uniform_control_flow::NAME, @@ -76,8 +77,59 @@ pub const OPTIONAL_EXTENSIONS: &[&CStr] = &[ ash::ext::image_drm_format_modifier::NAME, ash::nv::linear_color_attachment::NAME, ash::ext::device_fault::NAME, + MAINTENANCE8, ]; +/// `VK_KHR_maintenance8`, which ash 0.38 does not bind: one of [`OPTIONAL_EXTENSIONS`], for its +/// feature `maintenance8` ([`Maintenance8Features`]), through which a sample at a texel offset the +/// shader computes takes the offset as its own `Offset` operand. +pub const MAINTENANCE8: &CStr = c"VK_KHR_maintenance8"; + +/// No Metal counterpart: `VkPhysicalDeviceMaintenance8FeaturesKHR`, of `VK_KHR_maintenance8`, +/// which ash 0.38 does not declare, laid out as the registry defines it (`sType`, `pNext`, +/// `maintenance8`), as the floor reads and enables it ([`Features`]). +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Maintenance8Features { + s_type: vk::StructureType, + pub(crate) p_next: *mut std::ffi::c_void, + /// `maintenance8`. + pub maintenance8: vk::Bool32, +} + +// SAFETY: plain data; the chain pointer is cleared once the structure is read, as ash's +// structures' are. +unsafe impl Send for Maintenance8Features {} +// SAFETY: as above. +unsafe impl Sync for Maintenance8Features {} +// SAFETY: it starts with `sType` and `pNext`, as the chain requires, and the registry lists both +// structures in its `structextends`. +unsafe impl vk::ExtendsPhysicalDeviceFeatures2 for Maintenance8Features {} +// SAFETY: as above. +unsafe impl vk::ExtendsDeviceCreateInfo for Maintenance8Features {} + +impl Default for Maintenance8Features { + fn default() -> Maintenance8Features { + Maintenance8Features { + // `VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR`: extension number + // 575, offset 0. + s_type: vk::StructureType::from_raw(1_000_574_000), + p_next: std::ptr::null_mut(), + maintenance8: vk::FALSE, + } + } +} + +/// The structure's size and members' offsets, as the registry's C declaration lays them out on a +/// 64-bit target: a wrong declaration fails the build, not a driver call. +#[cfg(target_pointer_width = "64")] +const _: () = { + use std::mem::{offset_of, size_of}; + assert!(size_of::() == 24); + assert!(offset_of!(Maintenance8Features, p_next) == 8); + assert!(offset_of!(Maintenance8Features, maintenance8) == 16); +}; + /// The device extensions of the attachment feedback loop (`VK_EXT_attachment_feedback_loop_layout` /// and its dynamic state), through which a draw reads, through a texture, an attachment its own /// pass renders (Metal's texture read of a render target): device creation enables both, with @@ -166,6 +218,8 @@ fn shader_extension(name: &CStr) -> Option { Some(VkExtension::KhrVertexAttributeDivisor) } else if name == ash::ext::vertex_attribute_divisor::NAME { Some(VkExtension::ExtVertexAttributeDivisor) + } else if name == MAINTENANCE8 { + Some(VkExtension::KhrMaintenance8) } else { None } @@ -326,6 +380,9 @@ pub struct Features { /// `VkPhysicalDeviceMaintenance5FeaturesKHR`, of `VK_KHR_maintenance5`: read where the device /// lists it, and `maintenance5` enabled with [`INDIRECT_COMMANDS`] alone. pub maintenance5: vk::PhysicalDeviceMaintenance5FeaturesKHR<'static>, + /// `VkPhysicalDeviceMaintenance8FeaturesKHR`, of `VK_KHR_maintenance8` ([`MAINTENANCE8`]): + /// read and enabled only where the device lists it, and then only `maintenance8`. + pub maintenance8: Maintenance8Features, } /// One feature: the Vulkan structure that reports it, its member as ash spells it, the member, and @@ -392,6 +449,9 @@ macro_rules! feature { (@structure line_rasterization) => { "VkPhysicalDeviceLineRasterizationFeaturesEXT" }; + (@structure maintenance8) => { + "VkPhysicalDeviceMaintenance8FeaturesKHR" + }; (@translator) => { None }; @@ -594,6 +654,10 @@ pub(crate) const OPTIONAL: &[Feature] = &[ // control flow where it offers that. feature!(maximal_reconvergence.shader_maximal_reconvergence => ShaderMaximalReconvergence), feature!(subgroup_uniform_control_flow.shader_subgroup_uniform_control_flow => ShaderSubgroupUniformControlFlow), + // A sample at a texel offset the shader computes: the instruction's own `Offset` operand where + // the device offers it, else a branch over the offset's values, each with its value as + // `ConstOffset` (Vulkan 1.0's). + feature!(maintenance8.maintenance8 => Maintenance8), ]; /// The features of the attachment feedback loop ([`ATTACHMENT_READ_EXTENSIONS`]): enabled together @@ -859,6 +923,10 @@ pub struct Capabilities { /// `shaderSubgroupUniformControlFlow`: SIMD groups reconverge where control flow is uniform, /// the mode where maximal reconvergence is not offered. pub subgroup_uniform_control_flow: bool, + /// `maintenance8` (`VK_KHR_maintenance8`): a sample at a texel offset the shader computes + /// takes the offset as its own `Offset` operand. Where it is false, the sample branches over + /// the offset's values, each branch with its value as `ConstOffset`. + pub texel_offset_operand: bool, /// The device's descriptor limits hold the sampled-texture array's second elements beside the /// floor's arrays: a draw may read, through a texture, an attachment its own pass renders, as /// Metal reads a render target. It reads through the attachment feedback loop where @@ -1002,6 +1070,7 @@ unsafe fn query( let fault_listed = listed(ash::ext::device_fault::NAME); let line_rasterization_listed = listed(ash::ext::line_rasterization::NAME); let maintenance5_listed = listed(ash::khr::maintenance5::NAME); + let maintenance8_listed = listed(MAINTENANCE8); let Features { core, @@ -1024,6 +1093,7 @@ unsafe fn query( line_rasterization, generated_commands, maintenance5, + maintenance8, } = &mut queried.features; let mut features = vk::PhysicalDeviceFeatures2::default() .push_next(&mut *vulkan11) @@ -1077,6 +1147,9 @@ unsafe fn query( if maintenance5_listed { features = features.push_next(&mut *maintenance5); } + if maintenance8_listed { + features = features.push_next(&mut *maintenance8); + } instance.get_physical_device_features2(physical, &mut features); *core = features.features; vulkan11.p_next = std::ptr::null_mut(); @@ -1098,6 +1171,7 @@ unsafe fn query( line_rasterization.p_next = std::ptr::null_mut(); generated_commands.p_next = std::ptr::null_mut(); maintenance5.p_next = std::ptr::null_mut(); + maintenance8.p_next = std::ptr::null_mut(); queried.families = instance.get_physical_device_queue_family_properties(physical); queried.memory = instance.get_physical_device_memory_properties(physical); @@ -1239,6 +1313,7 @@ pub(crate) fn decide(device: &Queried) -> Result { .subgroup_uniform_control_flow .shader_subgroup_uniform_control_flow == vk::TRUE, + texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE, attachment_reads, feedback_loop, features, diff --git a/crates/metal2vulkan-runtime/src/tests/filter_nest.rs b/crates/metal2vulkan-runtime/src/tests/filter_nest.rs index 21d77d243..199059b41 100644 --- a/crates/metal2vulkan-runtime/src/tests/filter_nest.rs +++ b/crates/metal2vulkan-runtime/src/tests/filter_nest.rs @@ -3,20 +3,33 @@ //! its 64 texel centres, in a 3x3 nest whose counters make the texel offset, summing the red //! channel. Where the constants decide the counters, the translator unrolls the nest and every //! offset is a constant; where the inner loop's end is loaded (2: the same runs), the offset stays -//! dynamic, a switch over its values where the device takes no `Offset` operand on a sample. Both -//! kernels write the same sums, the nearest filter's. +//! dynamic: the sample's own `Offset` operand where device creation enabled `maintenance8`, and a +//! switch over its values where it did not, which a translator told of no `maintenance8` (the +//! tests' description of the device) shows on a device that has it. Every form writes the same +//! sums, the nearest filter's, and the cache directory keeps the operand's and the switch's +//! lowerings apart. //! //! `llvm-as` assembles the kernels; without it the test skips visibly. #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { - use crate::tests::command::on_device::{each_device, finished, Arena}; - use crate::{ - ComputePipelineDescriptor, Device, DispatchType, FunctionDescriptor, IndexClass, Library, - NumberedSampler, PixelFormat, Region, StageSource, TextureDescriptor, TextureType, - TextureUsage, + use crate::floor::MAINTENANCE8; + use crate::tests::command::on_device::{ + each_device, each_device_with, finished, within, Arena, }; + use crate::tests::devices_of_the_cfgs_kind; + use crate::{ + ComputePipelineDescriptor, Device, DeviceOptions, DispatchType, FunctionDescriptor, Gauges, + IndexClass, Library, NumberedSampler, PixelFormat, Region, StageSource, TextureDescriptor, + TextureType, TextureUsage, + }; + use metal2vulkan::device::{DeviceDescription, VkFeature}; + use metal2vulkan::Budget; use metal2vulkan_devtools::{llvm_assemble_text, AssembleError}; + use std::collections::BTreeMap; + + /// SPIR-V's `OpSwitch`. + const OP_SWITCH: u32 = 251; /// The texture's side. const SIDE: u32 = 8; @@ -170,19 +183,61 @@ declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr words.to_vec() } + /// As a device without `maintenance8` answers, on the same Vulkan device: its translator takes + /// no `Offset` operand on a sample, and branches over a run-time offset's values. + fn no_offset_operand(mut d: DeviceDescription) -> DeviceDescription { + d.features.remove(&VkFeature::Maintenance8); + d + } + + /// The form `device`'s translator gives `library`'s kernel: whether its module needs + /// `maintenance8` (an `Offset` operand on a sample), and its `OpSwitch` count. + fn form(name: &str, device: &Device, library: &Library) -> (bool, usize) { + let function = library.function("filter_nest").expect("the kernel"); + let descriptor = ComputePipelineDescriptor::new(StageSource::Function( + FunctionDescriptor::new(function), + )); + let pipeline = (device.translator()) + .compile_compute_pipeline(&descriptor, &Budget::standard()) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let words = &pipeline.stage.spirv; + let (mut at, mut switches) = (5, 0); + while let Some(&word) = words.get(at) { + switches += usize::from(word & 0xffff == OP_SWITCH); + at += (word >> 16).max(1) as usize; + } + let operand = (pipeline.requirements.features).contains(&VkFeature::Maintenance8); + (operand, switches) + } + + /// The unrolled kernel and the loaded one write the same sums, the nearest filter's, on every + /// device: the loaded one with the run-time offset as the sample's `Offset` operand where + /// device creation enabled `maintenance8` (no switch in its module), and as a switch over its + /// values otherwise. On the same device with a translator told of no `maintenance8`, the loaded + /// kernel takes the switch, and writes the same sums as the operand. #[test] - fn every_device_samples_a_filter_nest_alike_unrolled_and_switched() { + fn every_device_samples_a_filter_nest_alike_unrolled_by_operand_and_switched() { let (Some(decided), Some(loaded)) = (library("2"), library("%end")) else { return; }; + let mut dynamic = BTreeMap::new(); each_device("filter nest", |name, _, device| { let _textures = (device.grant_indices(IndexClass::Texture, 1, 2)) .unwrap_or_else(|error| panic!("{name}: {error}")); let _samplers = (device.grant_indices(IndexClass::Sampler, CONSTEXPR, 1)) .unwrap_or_else(|error| panic!("{name}: {error}")); + let operand = device.translator().profile().images().dynamic_sample_offset; + let enabled = (device.extensions().iter()).any(|e| e.as_c_str() == MAINTENANCE8); + assert_eq!( + operand, enabled, + "{name}: the translator's answer is creation's" + ); + let (needs, switches) = form(name, &device, &loaded); + assert_eq!(needs, operand, "{name}: the module's Offset operand"); + assert_eq!(switches == 0, operand, "{name}: {switches} switches"); let unrolled = sums(name, &device, &decided, 1); - let switched = sums(name, &device, &loaded, 2); - assert_eq!(unrolled, switched, "{name}: the two forms' sums"); + let sampled = sums(name, &device, &loaded, 2); + assert_eq!(unrolled, sampled, "{name}: the two kernels' sums"); // Both are the nearest filter's: the clamped texels' red channels, summed in order. for (tid, sum) in unrolled.iter().enumerate() { let (tx, ty) = (tid as i32 % 8, tid as i32 / 8); @@ -199,7 +254,95 @@ declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr "{name}: thread {tid}: {got} against {want}" ); } - println!("filter nest: {name}: the unrolled and switched forms write the same 64 sums"); + let taken = if operand { + "the Offset operand (maintenance8)" + } else { + "a switch (no maintenance8)" + }; + println!("filter nest: {name}: the unrolled kernel and {taken} write the same 64 sums"); + dynamic.insert(name.to_owned(), sampled); + }); + let options = || DeviceOptions { + described: Some(no_offset_operand), + ..DeviceOptions::default() + }; + each_device_with("filter nest switched", options, |name, _, device| { + let _textures = (device.grant_indices(IndexClass::Texture, 2, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let _samplers = (device.grant_indices(IndexClass::Sampler, CONSTEXPR, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + assert!(!device.translator().profile().images().dynamic_sample_offset); + let (needs, switches) = form(name, &device, &loaded); + assert!(!needs && switches > 0, "{name}: {needs} {switches}"); + let switched = sums(name, &device, &loaded, 2); + assert_eq!( + Some(&switched), + dynamic.get(name), + "{name}: the switch's sums" + ); + println!("filter nest: {name}: the switch writes the default form's 64 sums"); }); } + + /// One cache directory, three devices of one physical device in turn: a translator told of no + /// `maintenance8` lowers the loaded kernel (the switch); a default one, which takes the `Offset` + /// operand where creation enabled `maintenance8`, lowers it again and loads nothing, as the + /// translator's profile fingerprint in the lowering's key moved; a third told of none again + /// loads the switch's lowering and lowers nothing. On a device without `maintenance8` the + /// default one loads the switch's. + #[test] + fn every_device_keeps_the_operand_s_and_the_switch_s_lowerings_apart() { + let Some(loaded) = library("%end") else { + return; + }; + let instance = crate::tests::validation::instance(&[]); + let devices = devices_of_the_cfgs_kind(&instance); + assert!(!devices.is_empty(), "no device of this cfg's kind"); + for (name, physical) in &devices { + let dir = std::env::temp_dir().join(format!("m2v-rt-texoff-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut lowered = 0; + for (round, described) in [ + Some(no_offset_operand as fn(_) -> _), + None, + Some(no_offset_operand), + ] + .into_iter() + .enumerate() + { + let options = DeviceOptions { + pipeline_cache_dir: Some(dir.clone()), + described, + ..DeviceOptions::default() + }; + let device = Device::new(physical, options) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let operand = device.translator().profile().images().dynamic_sample_offset; + let counters = device.counters(); + { + let _textures = (device.grant_indices(IndexClass::Texture, 1, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let _samplers = (device.grant_indices(IndexClass::Sampler, CONSTEXPR, 1)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + sums(name, &device, &loaded, 1); + } + let metrics = counters.metrics(); + let counted = (metrics.translations, metrics.translations_loaded); + if round == 0 { + assert!(counted.0 > 0 && counted.1 == 0, "{name}: {counted:?}"); + lowered = counted.0; + } + let want = match (round, operand) { + (1, true) => (lowered, 0), + _ if round > 0 => (0, lowered), + _ => counted, + }; + assert_eq!(counted, want, "{name}: device {round} (operand {operand})"); + drop(device); + within("the teardown", || counters.gauges() == Gauges::default()); + } + let _ = std::fs::remove_dir_all(&dir); + println!("filter nest: {name}: the operand's and the switch's lowerings kept apart"); + } + } } diff --git a/crates/metal2vulkan-runtime/src/tests/floor.rs b/crates/metal2vulkan-runtime/src/tests/floor.rs index eae49a905..1ecfccd57 100644 --- a/crates/metal2vulkan-runtime/src/tests/floor.rs +++ b/crates/metal2vulkan-runtime/src/tests/floor.rs @@ -416,6 +416,7 @@ fn a_device_at_the_floor_is_above_it() { assert!(!capabilities.float64); assert!(!capabilities.maximal_reconvergence); assert!(!capabilities.subgroup_uniform_control_flow); + assert!(!capabilities.texel_offset_operand); assert_eq!(capabilities.extensions, DEVICE_EXTENSIONS); assert_eq!(capabilities.queue_family, 0); assert_eq!( @@ -1586,6 +1587,32 @@ fn the_fault_report_is_enabled_where_listed_and_reported() { assert_eq!(answer(&device), (true, true), "listed and reported"); } +/// A device that lists `VK_KHR_maintenance8` and reports `maintenance8` has both enabled, and the +/// translator is told of both, so a sample at a texel offset the shader computes takes it as its +/// own `Offset` operand; a device at the floor has neither, and the translator, told of neither, +/// branches over the offset's values. +#[test] +fn a_run_time_texel_offset_is_the_sample_s_operand_where_maintenance8_is_reported() { + use crate::floor::{shader_enables, MAINTENANCE8}; + use metal2vulkan::device::{VkExtension, VkFeature}; + let answer = |device: &Queried| { + let capabilities = decide(device).unwrap_or_else(|below| panic!("{below}")); + let enables = shader_enables(&capabilities); + ( + capabilities.texel_offset_operand, + capabilities.extensions.contains(&MAINTENANCE8), + capabilities.features.maintenance8.maintenance8 == vk::TRUE, + enables.features.contains(&VkFeature::Maintenance8), + enables.extensions.contains(&VkExtension::KhrMaintenance8), + ) + }; + let mut device = at_the_floor(); + assert_eq!(answer(&device), (false, false, false, false, false)); + device.extensions.push(MAINTENANCE8.to_owned()); + device.features.maintenance8.maintenance8 = vk::TRUE; + assert_eq!(answer(&device), (true, true, true, true, true)); +} + /// A device reads attachments where its descriptor limits hold the sampled-texture array's second /// elements: through the attachment feedback loop where it lists both extensions and reports both /// features, which device creation then enables, and through a copy of the image where it does @@ -1667,7 +1694,7 @@ fn a_set_layout_the_device_does_not_support_is_named() { #[test] fn the_optional_features_decide_the_capabilities() { type Set = fn(&mut Features); - let cases: [(Set, &str); 7] = [ + let cases: [(Set, &str); 8] = [ (|f| f.vulkan12.shader_float16 = vk::TRUE, "float16"), ( |f| f.core.shader_storage_image_read_without_format = vk::TRUE, @@ -1693,6 +1720,10 @@ fn the_optional_features_decide_the_capabilities() { }, "subgroup_uniform_control_flow", ), + ( + |f| f.maintenance8.maintenance8 = vk::TRUE, + "texel_offset_operand", + ), ]; assert_eq!( cases.len(), @@ -1717,6 +1748,7 @@ fn the_optional_features_decide_the_capabilities() { "subgroup_uniform_control_flow", capabilities.subgroup_uniform_control_flow, ), + ("texel_offset_operand", capabilities.texel_offset_operand), ]; for (name, value) in answers { assert_eq!(